codemirror.js 386 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765
  1. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  2. // Distributed under an MIT license: https://codemirror.net/LICENSE
  3. // This is CodeMirror (https://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 (global, factory) {
  9. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  10. typeof define === 'function' && define.amd ? define(factory) :
  11. (global.CodeMirror = factory());
  12. }(this, (function () { 'use strict';
  13. // Kludges for bugs and behavior differences that can't be feature
  14. // detected are enabled based on userAgent etc sniffing.
  15. var userAgent = navigator.userAgent;
  16. var platform = navigator.platform;
  17. var gecko = /gecko\/\d/i.test(userAgent);
  18. var ie_upto10 = /MSIE \d/.test(userAgent);
  19. var ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(userAgent);
  20. var edge = /Edge\/(\d+)/.exec(userAgent);
  21. var ie = ie_upto10 || ie_11up || edge;
  22. var ie_version = ie && (ie_upto10 ? document.documentMode || 6 : +(edge || ie_11up)[1]);
  23. var webkit = !edge && /WebKit\//.test(userAgent);
  24. var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(userAgent);
  25. var chrome = !edge && /Chrome\//.test(userAgent);
  26. var presto = /Opera\//.test(userAgent);
  27. var safari = /Apple Computer/.test(navigator.vendor);
  28. var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(userAgent);
  29. var phantom = /PhantomJS/.test(userAgent);
  30. var ios = !edge && /AppleWebKit/.test(userAgent) && /Mobile\/\w+/.test(userAgent);
  31. var android = /Android/.test(userAgent);
  32. // This is woefully incomplete. Suggestions for alternative methods welcome.
  33. var mobile = ios || android || /webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(userAgent);
  34. var mac = ios || /Mac/.test(platform);
  35. var chromeOS = /\bCrOS\b/.test(userAgent);
  36. var windows = /win/i.test(platform);
  37. var presto_version = presto && 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. function classTest(cls) { return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*") }
  44. var rmClass = function(node, cls) {
  45. var current = node.className;
  46. var match = classTest(cls).exec(current);
  47. if (match) {
  48. var after = current.slice(match.index + match[0].length);
  49. node.className = current.slice(0, match.index) + (after ? match[1] + after : "");
  50. }
  51. };
  52. function removeChildren(e) {
  53. for (var count = e.childNodes.length; count > 0; --count)
  54. { e.removeChild(e.firstChild); }
  55. return e
  56. }
  57. function removeChildrenAndAdd(parent, e) {
  58. return removeChildren(parent).appendChild(e)
  59. }
  60. function elt(tag, content, className, style) {
  61. var e = document.createElement(tag);
  62. if (className) { e.className = className; }
  63. if (style) { e.style.cssText = style; }
  64. if (typeof content == "string") { e.appendChild(document.createTextNode(content)); }
  65. else if (content) { for (var i = 0; i < content.length; ++i) { e.appendChild(content[i]); } }
  66. return e
  67. }
  68. // wrapper for elt, which removes the elt from the accessibility tree
  69. function eltP(tag, content, className, style) {
  70. var e = elt(tag, content, className, style);
  71. e.setAttribute("role", "presentation");
  72. return e
  73. }
  74. var range;
  75. if (document.createRange) { range = function(node, start, end, endNode) {
  76. var r = document.createRange();
  77. r.setEnd(endNode || node, end);
  78. r.setStart(node, start);
  79. return r
  80. }; }
  81. else { range = function(node, start, end) {
  82. var r = document.body.createTextRange();
  83. try { r.moveToElementText(node.parentNode); }
  84. catch(e) { return r }
  85. r.collapse(true);
  86. r.moveEnd("character", end);
  87. r.moveStart("character", start);
  88. return r
  89. }; }
  90. function contains(parent, child) {
  91. if (child.nodeType == 3) // Android browser always returns false when child is a textnode
  92. { child = child.parentNode; }
  93. if (parent.contains)
  94. { return parent.contains(child) }
  95. do {
  96. if (child.nodeType == 11) { child = child.host; }
  97. if (child == parent) { return true }
  98. } while (child = child.parentNode)
  99. }
  100. function activeElt() {
  101. // IE and Edge may throw an "Unspecified Error" when accessing document.activeElement.
  102. // IE < 10 will throw when accessed while the page is loading or in an iframe.
  103. // IE > 9 and Edge will throw when accessed in an iframe if document.body is unavailable.
  104. var activeElement;
  105. try {
  106. activeElement = document.activeElement;
  107. } catch(e) {
  108. activeElement = document.body || null;
  109. }
  110. while (activeElement && activeElement.shadowRoot && activeElement.shadowRoot.activeElement)
  111. { activeElement = activeElement.shadowRoot.activeElement; }
  112. return activeElement
  113. }
  114. function addClass(node, cls) {
  115. var current = node.className;
  116. if (!classTest(cls).test(current)) { node.className += (current ? " " : "") + cls; }
  117. }
  118. function joinClasses(a, b) {
  119. var as = a.split(" ");
  120. for (var i = 0; i < as.length; i++)
  121. { if (as[i] && !classTest(as[i]).test(b)) { b += " " + as[i]; } }
  122. return b
  123. }
  124. var selectInput = function(node) { node.select(); };
  125. if (ios) // Mobile Safari apparently has a bug where select() is broken.
  126. { selectInput = function(node) { node.selectionStart = 0; node.selectionEnd = node.value.length; }; }
  127. else if (ie) // Suppress mysterious IE10 errors
  128. { selectInput = function(node) { try { node.select(); } catch(_e) {} }; }
  129. function bind(f) {
  130. var args = Array.prototype.slice.call(arguments, 1);
  131. return function(){return f.apply(null, args)}
  132. }
  133. function copyObj(obj, target, overwrite) {
  134. if (!target) { target = {}; }
  135. for (var prop in obj)
  136. { if (obj.hasOwnProperty(prop) && (overwrite !== false || !target.hasOwnProperty(prop)))
  137. { target[prop] = obj[prop]; } }
  138. return target
  139. }
  140. // Counts the column offset in a string, taking tabs into account.
  141. // Used mostly to find indentation.
  142. function countColumn(string, end, tabSize, startIndex, startValue) {
  143. if (end == null) {
  144. end = string.search(/[^\s\u00a0]/);
  145. if (end == -1) { end = string.length; }
  146. }
  147. for (var i = startIndex || 0, n = startValue || 0;;) {
  148. var nextTab = string.indexOf("\t", i);
  149. if (nextTab < 0 || nextTab >= end)
  150. { return n + (end - i) }
  151. n += nextTab - i;
  152. n += tabSize - (n % tabSize);
  153. i = nextTab + 1;
  154. }
  155. }
  156. var Delayed = function() {this.id = null;};
  157. Delayed.prototype.set = function (ms, f) {
  158. clearTimeout(this.id);
  159. this.id = setTimeout(f, ms);
  160. };
  161. function indexOf(array, elt) {
  162. for (var i = 0; i < array.length; ++i)
  163. { if (array[i] == elt) { return i } }
  164. return -1
  165. }
  166. // Number of pixels added to scroller and sizer to hide scrollbar
  167. var scrollerGap = 30;
  168. // Returned or thrown by various protocols to signal 'I'm not
  169. // handling this'.
  170. var Pass = {toString: function(){return "CodeMirror.Pass"}};
  171. // Reused option objects for setSelection & friends
  172. var sel_dontScroll = {scroll: false}, sel_mouse = {origin: "*mouse"}, sel_move = {origin: "+move"};
  173. // The inverse of countColumn -- find the offset that corresponds to
  174. // a particular column.
  175. function findColumn(string, goal, tabSize) {
  176. for (var pos = 0, col = 0;;) {
  177. var nextTab = string.indexOf("\t", pos);
  178. if (nextTab == -1) { nextTab = string.length; }
  179. var skipped = nextTab - pos;
  180. if (nextTab == string.length || col + skipped >= goal)
  181. { return pos + Math.min(skipped, goal - col) }
  182. col += nextTab - pos;
  183. col += tabSize - (col % tabSize);
  184. pos = nextTab + 1;
  185. if (col >= goal) { return pos }
  186. }
  187. }
  188. var spaceStrs = [""];
  189. function spaceStr(n) {
  190. while (spaceStrs.length <= n)
  191. { spaceStrs.push(lst(spaceStrs) + " "); }
  192. return spaceStrs[n]
  193. }
  194. function lst(arr) { return arr[arr.length-1] }
  195. function map(array, f) {
  196. var out = [];
  197. for (var i = 0; i < array.length; i++) { out[i] = f(array[i], i); }
  198. return out
  199. }
  200. function insertSorted(array, value, score) {
  201. var pos = 0, priority = score(value);
  202. while (pos < array.length && score(array[pos]) <= priority) { pos++; }
  203. array.splice(pos, 0, value);
  204. }
  205. function nothing() {}
  206. function createObj(base, props) {
  207. var inst;
  208. if (Object.create) {
  209. inst = Object.create(base);
  210. } else {
  211. nothing.prototype = base;
  212. inst = new nothing();
  213. }
  214. if (props) { copyObj(props, inst); }
  215. return inst
  216. }
  217. var nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;
  218. function isWordCharBasic(ch) {
  219. return /\w/.test(ch) || ch > "\x80" &&
  220. (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch))
  221. }
  222. function isWordChar(ch, helper) {
  223. if (!helper) { return isWordCharBasic(ch) }
  224. if (helper.source.indexOf("\\w") > -1 && isWordCharBasic(ch)) { return true }
  225. return helper.test(ch)
  226. }
  227. function isEmpty(obj) {
  228. for (var n in obj) { if (obj.hasOwnProperty(n) && obj[n]) { return false } }
  229. return true
  230. }
  231. // Extending unicode characters. A series of a non-extending char +
  232. // any number of extending chars is treated as a single unit as far
  233. // as editing and measuring is concerned. This is not fully correct,
  234. // since some scripts/fonts/browsers also treat other configurations
  235. // of code points as a group.
  236. 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]/;
  237. function isExtendingChar(ch) { return ch.charCodeAt(0) >= 768 && extendingChars.test(ch) }
  238. // Returns a number from the range [`0`; `str.length`] unless `pos` is outside that range.
  239. function skipExtendingChars(str, pos, dir) {
  240. while ((dir < 0 ? pos > 0 : pos < str.length) && isExtendingChar(str.charAt(pos))) { pos += dir; }
  241. return pos
  242. }
  243. // Returns the value from the range [`from`; `to`] that satisfies
  244. // `pred` and is closest to `from`. Assumes that at least `to`
  245. // satisfies `pred`. Supports `from` being greater than `to`.
  246. function findFirst(pred, from, to) {
  247. // At any point we are certain `to` satisfies `pred`, don't know
  248. // whether `from` does.
  249. var dir = from > to ? -1 : 1;
  250. for (;;) {
  251. if (from == to) { return from }
  252. var midF = (from + to) / 2, mid = dir < 0 ? Math.ceil(midF) : Math.floor(midF);
  253. if (mid == from) { return pred(mid) ? from : to }
  254. if (pred(mid)) { to = mid; }
  255. else { from = mid + dir; }
  256. }
  257. }
  258. // BIDI HELPERS
  259. function iterateBidiSections(order, from, to, f) {
  260. if (!order) { return f(from, to, "ltr", 0) }
  261. var found = false;
  262. for (var i = 0; i < order.length; ++i) {
  263. var part = order[i];
  264. if (part.from < to && part.to > from || from == to && part.to == from) {
  265. f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr", i);
  266. found = true;
  267. }
  268. }
  269. if (!found) { f(from, to, "ltr"); }
  270. }
  271. var bidiOther = null;
  272. function getBidiPartAt(order, ch, sticky) {
  273. var found;
  274. bidiOther = null;
  275. for (var i = 0; i < order.length; ++i) {
  276. var cur = order[i];
  277. if (cur.from < ch && cur.to > ch) { return i }
  278. if (cur.to == ch) {
  279. if (cur.from != cur.to && sticky == "before") { found = i; }
  280. else { bidiOther = i; }
  281. }
  282. if (cur.from == ch) {
  283. if (cur.from != cur.to && sticky != "before") { found = i; }
  284. else { bidiOther = i; }
  285. }
  286. }
  287. return found != null ? found : bidiOther
  288. }
  289. // Bidirectional ordering algorithm
  290. // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm
  291. // that this (partially) implements.
  292. // One-char codes used for character types:
  293. // L (L): Left-to-Right
  294. // R (R): Right-to-Left
  295. // r (AL): Right-to-Left Arabic
  296. // 1 (EN): European Number
  297. // + (ES): European Number Separator
  298. // % (ET): European Number Terminator
  299. // n (AN): Arabic Number
  300. // , (CS): Common Number Separator
  301. // m (NSM): Non-Spacing Mark
  302. // b (BN): Boundary Neutral
  303. // s (B): Paragraph Separator
  304. // t (S): Segment Separator
  305. // w (WS): Whitespace
  306. // N (ON): Other Neutrals
  307. // Returns null if characters are ordered as they appear
  308. // (left-to-right), or an array of sections ({from, to, level}
  309. // objects) in the order in which they occur visually.
  310. var bidiOrdering = (function() {
  311. // Character types for codepoints 0 to 0xff
  312. var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN";
  313. // Character types for codepoints 0x600 to 0x6f9
  314. var arabicTypes = "nnnnnnNNr%%r,rNNmmmmmmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmmmnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmnNmmmmmmrrmmNmmmmrr1111111111";
  315. function charType(code) {
  316. if (code <= 0xf7) { return lowTypes.charAt(code) }
  317. else if (0x590 <= code && code <= 0x5f4) { return "R" }
  318. else if (0x600 <= code && code <= 0x6f9) { return arabicTypes.charAt(code - 0x600) }
  319. else if (0x6ee <= code && code <= 0x8ac) { return "r" }
  320. else if (0x2000 <= code && code <= 0x200b) { return "w" }
  321. else if (code == 0x200c) { return "b" }
  322. else { return "L" }
  323. }
  324. var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/;
  325. var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/;
  326. function BidiSpan(level, from, to) {
  327. this.level = level;
  328. this.from = from; this.to = to;
  329. }
  330. return function(str, direction) {
  331. var outerType = direction == "ltr" ? "L" : "R";
  332. if (str.length == 0 || direction == "ltr" && !bidiRE.test(str)) { return false }
  333. var len = str.length, types = [];
  334. for (var i = 0; i < len; ++i)
  335. { types.push(charType(str.charCodeAt(i))); }
  336. // W1. Examine each non-spacing mark (NSM) in the level run, and
  337. // change the type of the NSM to the type of the previous
  338. // character. If the NSM is at the start of the level run, it will
  339. // get the type of sor.
  340. for (var i$1 = 0, prev = outerType; i$1 < len; ++i$1) {
  341. var type = types[i$1];
  342. if (type == "m") { types[i$1] = prev; }
  343. else { prev = type; }
  344. }
  345. // W2. Search backwards from each instance of a European number
  346. // until the first strong type (R, L, AL, or sor) is found. If an
  347. // AL is found, change the type of the European number to Arabic
  348. // number.
  349. // W3. Change all ALs to R.
  350. for (var i$2 = 0, cur = outerType; i$2 < len; ++i$2) {
  351. var type$1 = types[i$2];
  352. if (type$1 == "1" && cur == "r") { types[i$2] = "n"; }
  353. else if (isStrong.test(type$1)) { cur = type$1; if (type$1 == "r") { types[i$2] = "R"; } }
  354. }
  355. // W4. A single European separator between two European numbers
  356. // changes to a European number. A single common separator between
  357. // two numbers of the same type changes to that type.
  358. for (var i$3 = 1, prev$1 = types[0]; i$3 < len - 1; ++i$3) {
  359. var type$2 = types[i$3];
  360. if (type$2 == "+" && prev$1 == "1" && types[i$3+1] == "1") { types[i$3] = "1"; }
  361. else if (type$2 == "," && prev$1 == types[i$3+1] &&
  362. (prev$1 == "1" || prev$1 == "n")) { types[i$3] = prev$1; }
  363. prev$1 = type$2;
  364. }
  365. // W5. A sequence of European terminators adjacent to European
  366. // numbers changes to all European numbers.
  367. // W6. Otherwise, separators and terminators change to Other
  368. // Neutral.
  369. for (var i$4 = 0; i$4 < len; ++i$4) {
  370. var type$3 = types[i$4];
  371. if (type$3 == ",") { types[i$4] = "N"; }
  372. else if (type$3 == "%") {
  373. var end = (void 0);
  374. for (end = i$4 + 1; end < len && types[end] == "%"; ++end) {}
  375. var replace = (i$4 && types[i$4-1] == "!") || (end < len && types[end] == "1") ? "1" : "N";
  376. for (var j = i$4; j < end; ++j) { types[j] = replace; }
  377. i$4 = end - 1;
  378. }
  379. }
  380. // W7. Search backwards from each instance of a European number
  381. // until the first strong type (R, L, or sor) is found. If an L is
  382. // found, then change the type of the European number to L.
  383. for (var i$5 = 0, cur$1 = outerType; i$5 < len; ++i$5) {
  384. var type$4 = types[i$5];
  385. if (cur$1 == "L" && type$4 == "1") { types[i$5] = "L"; }
  386. else if (isStrong.test(type$4)) { cur$1 = type$4; }
  387. }
  388. // N1. A sequence of neutrals takes the direction of the
  389. // surrounding strong text if the text on both sides has the same
  390. // direction. European and Arabic numbers act as if they were R in
  391. // terms of their influence on neutrals. Start-of-level-run (sor)
  392. // and end-of-level-run (eor) are used at level run boundaries.
  393. // N2. Any remaining neutrals take the embedding direction.
  394. for (var i$6 = 0; i$6 < len; ++i$6) {
  395. if (isNeutral.test(types[i$6])) {
  396. var end$1 = (void 0);
  397. for (end$1 = i$6 + 1; end$1 < len && isNeutral.test(types[end$1]); ++end$1) {}
  398. var before = (i$6 ? types[i$6-1] : outerType) == "L";
  399. var after = (end$1 < len ? types[end$1] : outerType) == "L";
  400. var replace$1 = before == after ? (before ? "L" : "R") : outerType;
  401. for (var j$1 = i$6; j$1 < end$1; ++j$1) { types[j$1] = replace$1; }
  402. i$6 = end$1 - 1;
  403. }
  404. }
  405. // Here we depart from the documented algorithm, in order to avoid
  406. // building up an actual levels array. Since there are only three
  407. // levels (0, 1, 2) in an implementation that doesn't take
  408. // explicit embedding into account, we can build up the order on
  409. // the fly, without following the level-based algorithm.
  410. var order = [], m;
  411. for (var i$7 = 0; i$7 < len;) {
  412. if (countsAsLeft.test(types[i$7])) {
  413. var start = i$7;
  414. for (++i$7; i$7 < len && countsAsLeft.test(types[i$7]); ++i$7) {}
  415. order.push(new BidiSpan(0, start, i$7));
  416. } else {
  417. var pos = i$7, at = order.length;
  418. for (++i$7; i$7 < len && types[i$7] != "L"; ++i$7) {}
  419. for (var j$2 = pos; j$2 < i$7;) {
  420. if (countsAsNum.test(types[j$2])) {
  421. if (pos < j$2) { order.splice(at, 0, new BidiSpan(1, pos, j$2)); }
  422. var nstart = j$2;
  423. for (++j$2; j$2 < i$7 && countsAsNum.test(types[j$2]); ++j$2) {}
  424. order.splice(at, 0, new BidiSpan(2, nstart, j$2));
  425. pos = j$2;
  426. } else { ++j$2; }
  427. }
  428. if (pos < i$7) { order.splice(at, 0, new BidiSpan(1, pos, i$7)); }
  429. }
  430. }
  431. if (direction == "ltr") {
  432. if (order[0].level == 1 && (m = str.match(/^\s+/))) {
  433. order[0].from = m[0].length;
  434. order.unshift(new BidiSpan(0, 0, m[0].length));
  435. }
  436. if (lst(order).level == 1 && (m = str.match(/\s+$/))) {
  437. lst(order).to -= m[0].length;
  438. order.push(new BidiSpan(0, len - m[0].length, len));
  439. }
  440. }
  441. return direction == "rtl" ? order.reverse() : order
  442. }
  443. })();
  444. // Get the bidi ordering for the given line (and cache it). Returns
  445. // false for lines that are fully left-to-right, and an array of
  446. // BidiSpan objects otherwise.
  447. function getOrder(line, direction) {
  448. var order = line.order;
  449. if (order == null) { order = line.order = bidiOrdering(line.text, direction); }
  450. return order
  451. }
  452. // EVENT HANDLING
  453. // Lightweight event framework. on/off also work on DOM nodes,
  454. // registering native DOM handlers.
  455. var noHandlers = [];
  456. var on = function(emitter, type, f) {
  457. if (emitter.addEventListener) {
  458. emitter.addEventListener(type, f, false);
  459. } else if (emitter.attachEvent) {
  460. emitter.attachEvent("on" + type, f);
  461. } else {
  462. var map$$1 = emitter._handlers || (emitter._handlers = {});
  463. map$$1[type] = (map$$1[type] || noHandlers).concat(f);
  464. }
  465. };
  466. function getHandlers(emitter, type) {
  467. return emitter._handlers && emitter._handlers[type] || noHandlers
  468. }
  469. function off(emitter, type, f) {
  470. if (emitter.removeEventListener) {
  471. emitter.removeEventListener(type, f, false);
  472. } else if (emitter.detachEvent) {
  473. emitter.detachEvent("on" + type, f);
  474. } else {
  475. var map$$1 = emitter._handlers, arr = map$$1 && map$$1[type];
  476. if (arr) {
  477. var index = indexOf(arr, f);
  478. if (index > -1)
  479. { map$$1[type] = arr.slice(0, index).concat(arr.slice(index + 1)); }
  480. }
  481. }
  482. }
  483. function signal(emitter, type /*, values...*/) {
  484. var handlers = getHandlers(emitter, type);
  485. if (!handlers.length) { return }
  486. var args = Array.prototype.slice.call(arguments, 2);
  487. for (var i = 0; i < handlers.length; ++i) { handlers[i].apply(null, args); }
  488. }
  489. // The DOM events that CodeMirror handles can be overridden by
  490. // registering a (non-DOM) handler on the editor for the event name,
  491. // and preventDefault-ing the event in that handler.
  492. function signalDOMEvent(cm, e, override) {
  493. if (typeof e == "string")
  494. { e = {type: e, preventDefault: function() { this.defaultPrevented = true; }}; }
  495. signal(cm, override || e.type, cm, e);
  496. return e_defaultPrevented(e) || e.codemirrorIgnore
  497. }
  498. function signalCursorActivity(cm) {
  499. var arr = cm._handlers && cm._handlers.cursorActivity;
  500. if (!arr) { return }
  501. var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = []);
  502. for (var i = 0; i < arr.length; ++i) { if (indexOf(set, arr[i]) == -1)
  503. { set.push(arr[i]); } }
  504. }
  505. function hasHandler(emitter, type) {
  506. return getHandlers(emitter, type).length > 0
  507. }
  508. // Add on and off methods to a constructor's prototype, to make
  509. // registering events on such objects more convenient.
  510. function eventMixin(ctor) {
  511. ctor.prototype.on = function(type, f) {on(this, type, f);};
  512. ctor.prototype.off = function(type, f) {off(this, type, f);};
  513. }
  514. // Due to the fact that we still support jurassic IE versions, some
  515. // compatibility wrappers are needed.
  516. function e_preventDefault(e) {
  517. if (e.preventDefault) { e.preventDefault(); }
  518. else { e.returnValue = false; }
  519. }
  520. function e_stopPropagation(e) {
  521. if (e.stopPropagation) { e.stopPropagation(); }
  522. else { e.cancelBubble = true; }
  523. }
  524. function e_defaultPrevented(e) {
  525. return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false
  526. }
  527. function e_stop(e) {e_preventDefault(e); e_stopPropagation(e);}
  528. function e_target(e) {return e.target || e.srcElement}
  529. function e_button(e) {
  530. var b = e.which;
  531. if (b == null) {
  532. if (e.button & 1) { b = 1; }
  533. else if (e.button & 2) { b = 3; }
  534. else if (e.button & 4) { b = 2; }
  535. }
  536. if (mac && e.ctrlKey && b == 1) { b = 3; }
  537. return b
  538. }
  539. // Detect drag-and-drop
  540. var dragAndDrop = function() {
  541. // There is *some* kind of drag-and-drop support in IE6-8, but I
  542. // couldn't get it to work yet.
  543. if (ie && ie_version < 9) { return false }
  544. var div = elt('div');
  545. return "draggable" in div || "dragDrop" in div
  546. }();
  547. var zwspSupported;
  548. function zeroWidthElement(measure) {
  549. if (zwspSupported == null) {
  550. var test = elt("span", "\u200b");
  551. removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")]));
  552. if (measure.firstChild.offsetHeight != 0)
  553. { zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8); }
  554. }
  555. var node = zwspSupported ? elt("span", "\u200b") :
  556. elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px");
  557. node.setAttribute("cm-text", "");
  558. return node
  559. }
  560. // Feature-detect IE's crummy client rect reporting for bidi text
  561. var badBidiRects;
  562. function hasBadBidiRects(measure) {
  563. if (badBidiRects != null) { return badBidiRects }
  564. var txt = removeChildrenAndAdd(measure, document.createTextNode("A\u062eA"));
  565. var r0 = range(txt, 0, 1).getBoundingClientRect();
  566. var r1 = range(txt, 1, 2).getBoundingClientRect();
  567. removeChildren(measure);
  568. if (!r0 || r0.left == r0.right) { return false } // Safari returns null in some cases (#2780)
  569. return badBidiRects = (r1.right - r0.right < 3)
  570. }
  571. // See if "".split is the broken IE version, if so, provide an
  572. // alternative way to split lines.
  573. var splitLinesAuto = "\n\nb".split(/\n/).length != 3 ? function (string) {
  574. var pos = 0, result = [], l = string.length;
  575. while (pos <= l) {
  576. var nl = string.indexOf("\n", pos);
  577. if (nl == -1) { nl = string.length; }
  578. var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl);
  579. var rt = line.indexOf("\r");
  580. if (rt != -1) {
  581. result.push(line.slice(0, rt));
  582. pos += rt + 1;
  583. } else {
  584. result.push(line);
  585. pos = nl + 1;
  586. }
  587. }
  588. return result
  589. } : function (string) { return string.split(/\r\n?|\n/); };
  590. var hasSelection = window.getSelection ? function (te) {
  591. try { return te.selectionStart != te.selectionEnd }
  592. catch(e) { return false }
  593. } : function (te) {
  594. var range$$1;
  595. try {range$$1 = te.ownerDocument.selection.createRange();}
  596. catch(e) {}
  597. if (!range$$1 || range$$1.parentElement() != te) { return false }
  598. return range$$1.compareEndPoints("StartToEnd", range$$1) != 0
  599. };
  600. var hasCopyEvent = (function () {
  601. var e = elt("div");
  602. if ("oncopy" in e) { return true }
  603. e.setAttribute("oncopy", "return;");
  604. return typeof e.oncopy == "function"
  605. })();
  606. var badZoomedRects = null;
  607. function hasBadZoomedRects(measure) {
  608. if (badZoomedRects != null) { return badZoomedRects }
  609. var node = removeChildrenAndAdd(measure, elt("span", "x"));
  610. var normal = node.getBoundingClientRect();
  611. var fromRange = range(node, 0, 1).getBoundingClientRect();
  612. return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1
  613. }
  614. // Known modes, by name and by MIME
  615. var modes = {}, mimeModes = {};
  616. // Extra arguments are stored as the mode's dependencies, which is
  617. // used by (legacy) mechanisms like loadmode.js to automatically
  618. // load a mode. (Preferred mechanism is the require/define calls.)
  619. function defineMode(name, mode) {
  620. if (arguments.length > 2)
  621. { mode.dependencies = Array.prototype.slice.call(arguments, 2); }
  622. modes[name] = mode;
  623. }
  624. function defineMIME(mime, spec) {
  625. mimeModes[mime] = spec;
  626. }
  627. // Given a MIME type, a {name, ...options} config object, or a name
  628. // string, return a mode config object.
  629. function resolveMode(spec) {
  630. if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) {
  631. spec = mimeModes[spec];
  632. } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) {
  633. var found = mimeModes[spec.name];
  634. if (typeof found == "string") { found = {name: found}; }
  635. spec = createObj(found, spec);
  636. spec.name = found.name;
  637. } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) {
  638. return resolveMode("application/xml")
  639. } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+json$/.test(spec)) {
  640. return resolveMode("application/json")
  641. }
  642. if (typeof spec == "string") { return {name: spec} }
  643. else { return spec || {name: "null"} }
  644. }
  645. // Given a mode spec (anything that resolveMode accepts), find and
  646. // initialize an actual mode object.
  647. function getMode(options, spec) {
  648. spec = resolveMode(spec);
  649. var mfactory = modes[spec.name];
  650. if (!mfactory) { return getMode(options, "text/plain") }
  651. var modeObj = mfactory(options, spec);
  652. if (modeExtensions.hasOwnProperty(spec.name)) {
  653. var exts = modeExtensions[spec.name];
  654. for (var prop in exts) {
  655. if (!exts.hasOwnProperty(prop)) { continue }
  656. if (modeObj.hasOwnProperty(prop)) { modeObj["_" + prop] = modeObj[prop]; }
  657. modeObj[prop] = exts[prop];
  658. }
  659. }
  660. modeObj.name = spec.name;
  661. if (spec.helperType) { modeObj.helperType = spec.helperType; }
  662. if (spec.modeProps) { for (var prop$1 in spec.modeProps)
  663. { modeObj[prop$1] = spec.modeProps[prop$1]; } }
  664. return modeObj
  665. }
  666. // This can be used to attach properties to mode objects from
  667. // outside the actual mode definition.
  668. var modeExtensions = {};
  669. function extendMode(mode, properties) {
  670. var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {});
  671. copyObj(properties, exts);
  672. }
  673. function copyState(mode, state) {
  674. if (state === true) { return state }
  675. if (mode.copyState) { return mode.copyState(state) }
  676. var nstate = {};
  677. for (var n in state) {
  678. var val = state[n];
  679. if (val instanceof Array) { val = val.concat([]); }
  680. nstate[n] = val;
  681. }
  682. return nstate
  683. }
  684. // Given a mode and a state (for that mode), find the inner mode and
  685. // state at the position that the state refers to.
  686. function innerMode(mode, state) {
  687. var info;
  688. while (mode.innerMode) {
  689. info = mode.innerMode(state);
  690. if (!info || info.mode == mode) { break }
  691. state = info.state;
  692. mode = info.mode;
  693. }
  694. return info || {mode: mode, state: state}
  695. }
  696. function startState(mode, a1, a2) {
  697. return mode.startState ? mode.startState(a1, a2) : true
  698. }
  699. // STRING STREAM
  700. // Fed to the mode parsers, provides helper functions to make
  701. // parsers more succinct.
  702. var StringStream = function(string, tabSize, lineOracle) {
  703. this.pos = this.start = 0;
  704. this.string = string;
  705. this.tabSize = tabSize || 8;
  706. this.lastColumnPos = this.lastColumnValue = 0;
  707. this.lineStart = 0;
  708. this.lineOracle = lineOracle;
  709. };
  710. StringStream.prototype.eol = function () {return this.pos >= this.string.length};
  711. StringStream.prototype.sol = function () {return this.pos == this.lineStart};
  712. StringStream.prototype.peek = function () {return this.string.charAt(this.pos) || undefined};
  713. StringStream.prototype.next = function () {
  714. if (this.pos < this.string.length)
  715. { return this.string.charAt(this.pos++) }
  716. };
  717. StringStream.prototype.eat = function (match) {
  718. var ch = this.string.charAt(this.pos);
  719. var ok;
  720. if (typeof match == "string") { ok = ch == match; }
  721. else { ok = ch && (match.test ? match.test(ch) : match(ch)); }
  722. if (ok) {++this.pos; return ch}
  723. };
  724. StringStream.prototype.eatWhile = function (match) {
  725. var start = this.pos;
  726. while (this.eat(match)){}
  727. return this.pos > start
  728. };
  729. StringStream.prototype.eatSpace = function () {
  730. var this$1 = this;
  731. var start = this.pos;
  732. while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) { ++this$1.pos; }
  733. return this.pos > start
  734. };
  735. StringStream.prototype.skipToEnd = function () {this.pos = this.string.length;};
  736. StringStream.prototype.skipTo = function (ch) {
  737. var found = this.string.indexOf(ch, this.pos);
  738. if (found > -1) {this.pos = found; return true}
  739. };
  740. StringStream.prototype.backUp = function (n) {this.pos -= n;};
  741. StringStream.prototype.column = function () {
  742. if (this.lastColumnPos < this.start) {
  743. this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue);
  744. this.lastColumnPos = this.start;
  745. }
  746. return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0)
  747. };
  748. StringStream.prototype.indentation = function () {
  749. return countColumn(this.string, null, this.tabSize) -
  750. (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0)
  751. };
  752. StringStream.prototype.match = function (pattern, consume, caseInsensitive) {
  753. if (typeof pattern == "string") {
  754. var cased = function (str) { return caseInsensitive ? str.toLowerCase() : str; };
  755. var substr = this.string.substr(this.pos, pattern.length);
  756. if (cased(substr) == cased(pattern)) {
  757. if (consume !== false) { this.pos += pattern.length; }
  758. return true
  759. }
  760. } else {
  761. var match = this.string.slice(this.pos).match(pattern);
  762. if (match && match.index > 0) { return null }
  763. if (match && consume !== false) { this.pos += match[0].length; }
  764. return match
  765. }
  766. };
  767. StringStream.prototype.current = function (){return this.string.slice(this.start, this.pos)};
  768. StringStream.prototype.hideFirstChars = function (n, inner) {
  769. this.lineStart += n;
  770. try { return inner() }
  771. finally { this.lineStart -= n; }
  772. };
  773. StringStream.prototype.lookAhead = function (n) {
  774. var oracle = this.lineOracle;
  775. return oracle && oracle.lookAhead(n)
  776. };
  777. StringStream.prototype.baseToken = function () {
  778. var oracle = this.lineOracle;
  779. return oracle && oracle.baseToken(this.pos)
  780. };
  781. // Find the line object corresponding to the given line number.
  782. function getLine(doc, n) {
  783. n -= doc.first;
  784. if (n < 0 || n >= doc.size) { throw new Error("There is no line " + (n + doc.first) + " in the document.") }
  785. var chunk = doc;
  786. while (!chunk.lines) {
  787. for (var i = 0;; ++i) {
  788. var child = chunk.children[i], sz = child.chunkSize();
  789. if (n < sz) { chunk = child; break }
  790. n -= sz;
  791. }
  792. }
  793. return chunk.lines[n]
  794. }
  795. // Get the part of a document between two positions, as an array of
  796. // strings.
  797. function getBetween(doc, start, end) {
  798. var out = [], n = start.line;
  799. doc.iter(start.line, end.line + 1, function (line) {
  800. var text = line.text;
  801. if (n == end.line) { text = text.slice(0, end.ch); }
  802. if (n == start.line) { text = text.slice(start.ch); }
  803. out.push(text);
  804. ++n;
  805. });
  806. return out
  807. }
  808. // Get the lines between from and to, as array of strings.
  809. function getLines(doc, from, to) {
  810. var out = [];
  811. doc.iter(from, to, function (line) { out.push(line.text); }); // iter aborts when callback returns truthy value
  812. return out
  813. }
  814. // Update the height of a line, propagating the height change
  815. // upwards to parent nodes.
  816. function updateLineHeight(line, height) {
  817. var diff = height - line.height;
  818. if (diff) { for (var n = line; n; n = n.parent) { n.height += diff; } }
  819. }
  820. // Given a line object, find its line number by walking up through
  821. // its parent links.
  822. function lineNo(line) {
  823. if (line.parent == null) { return null }
  824. var cur = line.parent, no = indexOf(cur.lines, line);
  825. for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) {
  826. for (var i = 0;; ++i) {
  827. if (chunk.children[i] == cur) { break }
  828. no += chunk.children[i].chunkSize();
  829. }
  830. }
  831. return no + cur.first
  832. }
  833. // Find the line at the given vertical position, using the height
  834. // information in the document tree.
  835. function lineAtHeight(chunk, h) {
  836. var n = chunk.first;
  837. outer: do {
  838. for (var i$1 = 0; i$1 < chunk.children.length; ++i$1) {
  839. var child = chunk.children[i$1], ch = child.height;
  840. if (h < ch) { chunk = child; continue outer }
  841. h -= ch;
  842. n += child.chunkSize();
  843. }
  844. return n
  845. } while (!chunk.lines)
  846. var i = 0;
  847. for (; i < chunk.lines.length; ++i) {
  848. var line = chunk.lines[i], lh = line.height;
  849. if (h < lh) { break }
  850. h -= lh;
  851. }
  852. return n + i
  853. }
  854. function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size}
  855. function lineNumberFor(options, i) {
  856. return String(options.lineNumberFormatter(i + options.firstLineNumber))
  857. }
  858. // A Pos instance represents a position within the text.
  859. function Pos(line, ch, sticky) {
  860. if ( sticky === void 0 ) sticky = null;
  861. if (!(this instanceof Pos)) { return new Pos(line, ch, sticky) }
  862. this.line = line;
  863. this.ch = ch;
  864. this.sticky = sticky;
  865. }
  866. // Compare two positions, return 0 if they are the same, a negative
  867. // number when a is less, and a positive number otherwise.
  868. function cmp(a, b) { return a.line - b.line || a.ch - b.ch }
  869. function equalCursorPos(a, b) { return a.sticky == b.sticky && cmp(a, b) == 0 }
  870. function copyPos(x) {return Pos(x.line, x.ch)}
  871. function maxPos(a, b) { return cmp(a, b) < 0 ? b : a }
  872. function minPos(a, b) { return cmp(a, b) < 0 ? a : b }
  873. // Most of the external API clips given positions to make sure they
  874. // actually exist within the document.
  875. function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1))}
  876. function clipPos(doc, pos) {
  877. if (pos.line < doc.first) { return Pos(doc.first, 0) }
  878. var last = doc.first + doc.size - 1;
  879. if (pos.line > last) { return Pos(last, getLine(doc, last).text.length) }
  880. return clipToLen(pos, getLine(doc, pos.line).text.length)
  881. }
  882. function clipToLen(pos, linelen) {
  883. var ch = pos.ch;
  884. if (ch == null || ch > linelen) { return Pos(pos.line, linelen) }
  885. else if (ch < 0) { return Pos(pos.line, 0) }
  886. else { return pos }
  887. }
  888. function clipPosArray(doc, array) {
  889. var out = [];
  890. for (var i = 0; i < array.length; i++) { out[i] = clipPos(doc, array[i]); }
  891. return out
  892. }
  893. var SavedContext = function(state, lookAhead) {
  894. this.state = state;
  895. this.lookAhead = lookAhead;
  896. };
  897. var Context = function(doc, state, line, lookAhead) {
  898. this.state = state;
  899. this.doc = doc;
  900. this.line = line;
  901. this.maxLookAhead = lookAhead || 0;
  902. this.baseTokens = null;
  903. this.baseTokenPos = 1;
  904. };
  905. Context.prototype.lookAhead = function (n) {
  906. var line = this.doc.getLine(this.line + n);
  907. if (line != null && n > this.maxLookAhead) { this.maxLookAhead = n; }
  908. return line
  909. };
  910. Context.prototype.baseToken = function (n) {
  911. var this$1 = this;
  912. if (!this.baseTokens) { return null }
  913. while (this.baseTokens[this.baseTokenPos] <= n)
  914. { this$1.baseTokenPos += 2; }
  915. var type = this.baseTokens[this.baseTokenPos + 1];
  916. return {type: type && type.replace(/( |^)overlay .*/, ""),
  917. size: this.baseTokens[this.baseTokenPos] - n}
  918. };
  919. Context.prototype.nextLine = function () {
  920. this.line++;
  921. if (this.maxLookAhead > 0) { this.maxLookAhead--; }
  922. };
  923. Context.fromSaved = function (doc, saved, line) {
  924. if (saved instanceof SavedContext)
  925. { return new Context(doc, copyState(doc.mode, saved.state), line, saved.lookAhead) }
  926. else
  927. { return new Context(doc, copyState(doc.mode, saved), line) }
  928. };
  929. Context.prototype.save = function (copy) {
  930. var state = copy !== false ? copyState(this.doc.mode, this.state) : this.state;
  931. return this.maxLookAhead > 0 ? new SavedContext(state, this.maxLookAhead) : state
  932. };
  933. // Compute a style array (an array starting with a mode generation
  934. // -- for invalidation -- followed by pairs of end positions and
  935. // style strings), which is used to highlight the tokens on the
  936. // line.
  937. function highlightLine(cm, line, context, forceToEnd) {
  938. // A styles array always starts with a number identifying the
  939. // mode/overlays that it is based on (for easy invalidation).
  940. var st = [cm.state.modeGen], lineClasses = {};
  941. // Compute the base array of styles
  942. runMode(cm, line.text, cm.doc.mode, context, function (end, style) { return st.push(end, style); },
  943. lineClasses, forceToEnd);
  944. var state = context.state;
  945. // Run overlays, adjust style array.
  946. var loop = function ( o ) {
  947. context.baseTokens = st;
  948. var overlay = cm.state.overlays[o], i = 1, at = 0;
  949. context.state = true;
  950. runMode(cm, line.text, overlay.mode, context, function (end, style) {
  951. var start = i;
  952. // Ensure there's a token end at the current position, and that i points at it
  953. while (at < end) {
  954. var i_end = st[i];
  955. if (i_end > end)
  956. { st.splice(i, 1, end, st[i+1], i_end); }
  957. i += 2;
  958. at = Math.min(end, i_end);
  959. }
  960. if (!style) { return }
  961. if (overlay.opaque) {
  962. st.splice(start, i - start, end, "overlay " + style);
  963. i = start + 2;
  964. } else {
  965. for (; start < i; start += 2) {
  966. var cur = st[start+1];
  967. st[start+1] = (cur ? cur + " " : "") + "overlay " + style;
  968. }
  969. }
  970. }, lineClasses);
  971. context.state = state;
  972. context.baseTokens = null;
  973. context.baseTokenPos = 1;
  974. };
  975. for (var o = 0; o < cm.state.overlays.length; ++o) loop( o );
  976. return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null}
  977. }
  978. function getLineStyles(cm, line, updateFrontier) {
  979. if (!line.styles || line.styles[0] != cm.state.modeGen) {
  980. var context = getContextBefore(cm, lineNo(line));
  981. var resetState = line.text.length > cm.options.maxHighlightLength && copyState(cm.doc.mode, context.state);
  982. var result = highlightLine(cm, line, context);
  983. if (resetState) { context.state = resetState; }
  984. line.stateAfter = context.save(!resetState);
  985. line.styles = result.styles;
  986. if (result.classes) { line.styleClasses = result.classes; }
  987. else if (line.styleClasses) { line.styleClasses = null; }
  988. if (updateFrontier === cm.doc.highlightFrontier)
  989. { cm.doc.modeFrontier = Math.max(cm.doc.modeFrontier, ++cm.doc.highlightFrontier); }
  990. }
  991. return line.styles
  992. }
  993. function getContextBefore(cm, n, precise) {
  994. var doc = cm.doc, display = cm.display;
  995. if (!doc.mode.startState) { return new Context(doc, true, n) }
  996. var start = findStartLine(cm, n, precise);
  997. var saved = start > doc.first && getLine(doc, start - 1).stateAfter;
  998. var context = saved ? Context.fromSaved(doc, saved, start) : new Context(doc, startState(doc.mode), start);
  999. doc.iter(start, n, function (line) {
  1000. processLine(cm, line.text, context);
  1001. var pos = context.line;
  1002. line.stateAfter = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo ? context.save() : null;
  1003. context.nextLine();
  1004. });
  1005. if (precise) { doc.modeFrontier = context.line; }
  1006. return context
  1007. }
  1008. // Lightweight form of highlight -- proceed over this line and
  1009. // update state, but don't save a style array. Used for lines that
  1010. // aren't currently visible.
  1011. function processLine(cm, text, context, startAt) {
  1012. var mode = cm.doc.mode;
  1013. var stream = new StringStream(text, cm.options.tabSize, context);
  1014. stream.start = stream.pos = startAt || 0;
  1015. if (text == "") { callBlankLine(mode, context.state); }
  1016. while (!stream.eol()) {
  1017. readToken(mode, stream, context.state);
  1018. stream.start = stream.pos;
  1019. }
  1020. }
  1021. function callBlankLine(mode, state) {
  1022. if (mode.blankLine) { return mode.blankLine(state) }
  1023. if (!mode.innerMode) { return }
  1024. var inner = innerMode(mode, state);
  1025. if (inner.mode.blankLine) { return inner.mode.blankLine(inner.state) }
  1026. }
  1027. function readToken(mode, stream, state, inner) {
  1028. for (var i = 0; i < 10; i++) {
  1029. if (inner) { inner[0] = innerMode(mode, state).mode; }
  1030. var style = mode.token(stream, state);
  1031. if (stream.pos > stream.start) { return style }
  1032. }
  1033. throw new Error("Mode " + mode.name + " failed to advance stream.")
  1034. }
  1035. var Token = function(stream, type, state) {
  1036. this.start = stream.start; this.end = stream.pos;
  1037. this.string = stream.current();
  1038. this.type = type || null;
  1039. this.state = state;
  1040. };
  1041. // Utility for getTokenAt and getLineTokens
  1042. function takeToken(cm, pos, precise, asArray) {
  1043. var doc = cm.doc, mode = doc.mode, style;
  1044. pos = clipPos(doc, pos);
  1045. var line = getLine(doc, pos.line), context = getContextBefore(cm, pos.line, precise);
  1046. var stream = new StringStream(line.text, cm.options.tabSize, context), tokens;
  1047. if (asArray) { tokens = []; }
  1048. while ((asArray || stream.pos < pos.ch) && !stream.eol()) {
  1049. stream.start = stream.pos;
  1050. style = readToken(mode, stream, context.state);
  1051. if (asArray) { tokens.push(new Token(stream, style, copyState(doc.mode, context.state))); }
  1052. }
  1053. return asArray ? tokens : new Token(stream, style, context.state)
  1054. }
  1055. function extractLineClasses(type, output) {
  1056. if (type) { for (;;) {
  1057. var lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/);
  1058. if (!lineClass) { break }
  1059. type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length);
  1060. var prop = lineClass[1] ? "bgClass" : "textClass";
  1061. if (output[prop] == null)
  1062. { output[prop] = lineClass[2]; }
  1063. else if (!(new RegExp("(?:^|\s)" + lineClass[2] + "(?:$|\s)")).test(output[prop]))
  1064. { output[prop] += " " + lineClass[2]; }
  1065. } }
  1066. return type
  1067. }
  1068. // Run the given mode's parser over a line, calling f for each token.
  1069. function runMode(cm, text, mode, context, f, lineClasses, forceToEnd) {
  1070. var flattenSpans = mode.flattenSpans;
  1071. if (flattenSpans == null) { flattenSpans = cm.options.flattenSpans; }
  1072. var curStart = 0, curStyle = null;
  1073. var stream = new StringStream(text, cm.options.tabSize, context), style;
  1074. var inner = cm.options.addModeClass && [null];
  1075. if (text == "") { extractLineClasses(callBlankLine(mode, context.state), lineClasses); }
  1076. while (!stream.eol()) {
  1077. if (stream.pos > cm.options.maxHighlightLength) {
  1078. flattenSpans = false;
  1079. if (forceToEnd) { processLine(cm, text, context, stream.pos); }
  1080. stream.pos = text.length;
  1081. style = null;
  1082. } else {
  1083. style = extractLineClasses(readToken(mode, stream, context.state, inner), lineClasses);
  1084. }
  1085. if (inner) {
  1086. var mName = inner[0].name;
  1087. if (mName) { style = "m-" + (style ? mName + " " + style : mName); }
  1088. }
  1089. if (!flattenSpans || curStyle != style) {
  1090. while (curStart < stream.start) {
  1091. curStart = Math.min(stream.start, curStart + 5000);
  1092. f(curStart, curStyle);
  1093. }
  1094. curStyle = style;
  1095. }
  1096. stream.start = stream.pos;
  1097. }
  1098. while (curStart < stream.pos) {
  1099. // Webkit seems to refuse to render text nodes longer than 57444
  1100. // characters, and returns inaccurate measurements in nodes
  1101. // starting around 5000 chars.
  1102. var pos = Math.min(stream.pos, curStart + 5000);
  1103. f(pos, curStyle);
  1104. curStart = pos;
  1105. }
  1106. }
  1107. // Finds the line to start with when starting a parse. Tries to
  1108. // find a line with a stateAfter, so that it can start with a
  1109. // valid state. If that fails, it returns the line with the
  1110. // smallest indentation, which tends to need the least context to
  1111. // parse correctly.
  1112. function findStartLine(cm, n, precise) {
  1113. var minindent, minline, doc = cm.doc;
  1114. var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100);
  1115. for (var search = n; search > lim; --search) {
  1116. if (search <= doc.first) { return doc.first }
  1117. var line = getLine(doc, search - 1), after = line.stateAfter;
  1118. if (after && (!precise || search + (after instanceof SavedContext ? after.lookAhead : 0) <= doc.modeFrontier))
  1119. { return search }
  1120. var indented = countColumn(line.text, null, cm.options.tabSize);
  1121. if (minline == null || minindent > indented) {
  1122. minline = search - 1;
  1123. minindent = indented;
  1124. }
  1125. }
  1126. return minline
  1127. }
  1128. function retreatFrontier(doc, n) {
  1129. doc.modeFrontier = Math.min(doc.modeFrontier, n);
  1130. if (doc.highlightFrontier < n - 10) { return }
  1131. var start = doc.first;
  1132. for (var line = n - 1; line > start; line--) {
  1133. var saved = getLine(doc, line).stateAfter;
  1134. // change is on 3
  1135. // state on line 1 looked ahead 2 -- so saw 3
  1136. // test 1 + 2 < 3 should cover this
  1137. if (saved && (!(saved instanceof SavedContext) || line + saved.lookAhead < n)) {
  1138. start = line + 1;
  1139. break
  1140. }
  1141. }
  1142. doc.highlightFrontier = Math.min(doc.highlightFrontier, start);
  1143. }
  1144. // Optimize some code when these features are not used.
  1145. var sawReadOnlySpans = false, sawCollapsedSpans = false;
  1146. function seeReadOnlySpans() {
  1147. sawReadOnlySpans = true;
  1148. }
  1149. function seeCollapsedSpans() {
  1150. sawCollapsedSpans = true;
  1151. }
  1152. // TEXTMARKER SPANS
  1153. function MarkedSpan(marker, from, to) {
  1154. this.marker = marker;
  1155. this.from = from; this.to = to;
  1156. }
  1157. // Search an array of spans for a span matching the given marker.
  1158. function getMarkedSpanFor(spans, marker) {
  1159. if (spans) { for (var i = 0; i < spans.length; ++i) {
  1160. var span = spans[i];
  1161. if (span.marker == marker) { return span }
  1162. } }
  1163. }
  1164. // Remove a span from an array, returning undefined if no spans are
  1165. // left (we don't store arrays for lines without spans).
  1166. function removeMarkedSpan(spans, span) {
  1167. var r;
  1168. for (var i = 0; i < spans.length; ++i)
  1169. { if (spans[i] != span) { (r || (r = [])).push(spans[i]); } }
  1170. return r
  1171. }
  1172. // Add a span to a line.
  1173. function addMarkedSpan(line, span) {
  1174. line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span];
  1175. span.marker.attachLine(line);
  1176. }
  1177. // Used for the algorithm that adjusts markers for a change in the
  1178. // document. These functions cut an array of spans at a given
  1179. // character position, returning an array of remaining chunks (or
  1180. // undefined if nothing remains).
  1181. function markedSpansBefore(old, startCh, isInsert) {
  1182. var nw;
  1183. if (old) { for (var i = 0; i < old.length; ++i) {
  1184. var span = old[i], marker = span.marker;
  1185. var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh);
  1186. if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) {
  1187. var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh)
  1188. ;(nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to));
  1189. }
  1190. } }
  1191. return nw
  1192. }
  1193. function markedSpansAfter(old, endCh, isInsert) {
  1194. var nw;
  1195. if (old) { for (var i = 0; i < old.length; ++i) {
  1196. var span = old[i], marker = span.marker;
  1197. var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh);
  1198. if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) {
  1199. var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh)
  1200. ;(nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh,
  1201. span.to == null ? null : span.to - endCh));
  1202. }
  1203. } }
  1204. return nw
  1205. }
  1206. // Given a change object, compute the new set of marker spans that
  1207. // cover the line in which the change took place. Removes spans
  1208. // entirely within the change, reconnects spans belonging to the
  1209. // same marker that appear on both sides of the change, and cuts off
  1210. // spans partially within the change. Returns an array of span
  1211. // arrays with one element for each line in (after) the change.
  1212. function stretchSpansOverChange(doc, change) {
  1213. if (change.full) { return null }
  1214. var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans;
  1215. var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans;
  1216. if (!oldFirst && !oldLast) { return null }
  1217. var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0;
  1218. // Get the spans that 'stick out' on both sides
  1219. var first = markedSpansBefore(oldFirst, startCh, isInsert);
  1220. var last = markedSpansAfter(oldLast, endCh, isInsert);
  1221. // Next, merge those two ends
  1222. var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0);
  1223. if (first) {
  1224. // Fix up .to properties of first
  1225. for (var i = 0; i < first.length; ++i) {
  1226. var span = first[i];
  1227. if (span.to == null) {
  1228. var found = getMarkedSpanFor(last, span.marker);
  1229. if (!found) { span.to = startCh; }
  1230. else if (sameLine) { span.to = found.to == null ? null : found.to + offset; }
  1231. }
  1232. }
  1233. }
  1234. if (last) {
  1235. // Fix up .from in last (or move them into first in case of sameLine)
  1236. for (var i$1 = 0; i$1 < last.length; ++i$1) {
  1237. var span$1 = last[i$1];
  1238. if (span$1.to != null) { span$1.to += offset; }
  1239. if (span$1.from == null) {
  1240. var found$1 = getMarkedSpanFor(first, span$1.marker);
  1241. if (!found$1) {
  1242. span$1.from = offset;
  1243. if (sameLine) { (first || (first = [])).push(span$1); }
  1244. }
  1245. } else {
  1246. span$1.from += offset;
  1247. if (sameLine) { (first || (first = [])).push(span$1); }
  1248. }
  1249. }
  1250. }
  1251. // Make sure we didn't create any zero-length spans
  1252. if (first) { first = clearEmptySpans(first); }
  1253. if (last && last != first) { last = clearEmptySpans(last); }
  1254. var newMarkers = [first];
  1255. if (!sameLine) {
  1256. // Fill gap with whole-line-spans
  1257. var gap = change.text.length - 2, gapMarkers;
  1258. if (gap > 0 && first)
  1259. { for (var i$2 = 0; i$2 < first.length; ++i$2)
  1260. { if (first[i$2].to == null)
  1261. { (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i$2].marker, null, null)); } } }
  1262. for (var i$3 = 0; i$3 < gap; ++i$3)
  1263. { newMarkers.push(gapMarkers); }
  1264. newMarkers.push(last);
  1265. }
  1266. return newMarkers
  1267. }
  1268. // Remove spans that are empty and don't have a clearWhenEmpty
  1269. // option of false.
  1270. function clearEmptySpans(spans) {
  1271. for (var i = 0; i < spans.length; ++i) {
  1272. var span = spans[i];
  1273. if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false)
  1274. { spans.splice(i--, 1); }
  1275. }
  1276. if (!spans.length) { return null }
  1277. return spans
  1278. }
  1279. // Used to 'clip' out readOnly ranges when making a change.
  1280. function removeReadOnlyRanges(doc, from, to) {
  1281. var markers = null;
  1282. doc.iter(from.line, to.line + 1, function (line) {
  1283. if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) {
  1284. var mark = line.markedSpans[i].marker;
  1285. if (mark.readOnly && (!markers || indexOf(markers, mark) == -1))
  1286. { (markers || (markers = [])).push(mark); }
  1287. } }
  1288. });
  1289. if (!markers) { return null }
  1290. var parts = [{from: from, to: to}];
  1291. for (var i = 0; i < markers.length; ++i) {
  1292. var mk = markers[i], m = mk.find(0);
  1293. for (var j = 0; j < parts.length; ++j) {
  1294. var p = parts[j];
  1295. if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) { continue }
  1296. var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to);
  1297. if (dfrom < 0 || !mk.inclusiveLeft && !dfrom)
  1298. { newParts.push({from: p.from, to: m.from}); }
  1299. if (dto > 0 || !mk.inclusiveRight && !dto)
  1300. { newParts.push({from: m.to, to: p.to}); }
  1301. parts.splice.apply(parts, newParts);
  1302. j += newParts.length - 3;
  1303. }
  1304. }
  1305. return parts
  1306. }
  1307. // Connect or disconnect spans from a line.
  1308. function detachMarkedSpans(line) {
  1309. var spans = line.markedSpans;
  1310. if (!spans) { return }
  1311. for (var i = 0; i < spans.length; ++i)
  1312. { spans[i].marker.detachLine(line); }
  1313. line.markedSpans = null;
  1314. }
  1315. function attachMarkedSpans(line, spans) {
  1316. if (!spans) { return }
  1317. for (var i = 0; i < spans.length; ++i)
  1318. { spans[i].marker.attachLine(line); }
  1319. line.markedSpans = spans;
  1320. }
  1321. // Helpers used when computing which overlapping collapsed span
  1322. // counts as the larger one.
  1323. function extraLeft(marker) { return marker.inclusiveLeft ? -1 : 0 }
  1324. function extraRight(marker) { return marker.inclusiveRight ? 1 : 0 }
  1325. // Returns a number indicating which of two overlapping collapsed
  1326. // spans is larger (and thus includes the other). Falls back to
  1327. // comparing ids when the spans cover exactly the same range.
  1328. function compareCollapsedMarkers(a, b) {
  1329. var lenDiff = a.lines.length - b.lines.length;
  1330. if (lenDiff != 0) { return lenDiff }
  1331. var aPos = a.find(), bPos = b.find();
  1332. var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b);
  1333. if (fromCmp) { return -fromCmp }
  1334. var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b);
  1335. if (toCmp) { return toCmp }
  1336. return b.id - a.id
  1337. }
  1338. // Find out whether a line ends or starts in a collapsed span. If
  1339. // so, return the marker for that span.
  1340. function collapsedSpanAtSide(line, start) {
  1341. var sps = sawCollapsedSpans && line.markedSpans, found;
  1342. if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) {
  1343. sp = sps[i];
  1344. if (sp.marker.collapsed && (start ? sp.from : sp.to) == null &&
  1345. (!found || compareCollapsedMarkers(found, sp.marker) < 0))
  1346. { found = sp.marker; }
  1347. } }
  1348. return found
  1349. }
  1350. function collapsedSpanAtStart(line) { return collapsedSpanAtSide(line, true) }
  1351. function collapsedSpanAtEnd(line) { return collapsedSpanAtSide(line, false) }
  1352. function collapsedSpanAround(line, ch) {
  1353. var sps = sawCollapsedSpans && line.markedSpans, found;
  1354. if (sps) { for (var i = 0; i < sps.length; ++i) {
  1355. var sp = sps[i];
  1356. if (sp.marker.collapsed && (sp.from == null || sp.from < ch) && (sp.to == null || sp.to > ch) &&
  1357. (!found || compareCollapsedMarkers(found, sp.marker) < 0)) { found = sp.marker; }
  1358. } }
  1359. return found
  1360. }
  1361. // Test whether there exists a collapsed span that partially
  1362. // overlaps (covers the start or end, but not both) of a new span.
  1363. // Such overlap is not allowed.
  1364. function conflictingCollapsedRange(doc, lineNo$$1, from, to, marker) {
  1365. var line = getLine(doc, lineNo$$1);
  1366. var sps = sawCollapsedSpans && line.markedSpans;
  1367. if (sps) { for (var i = 0; i < sps.length; ++i) {
  1368. var sp = sps[i];
  1369. if (!sp.marker.collapsed) { continue }
  1370. var found = sp.marker.find(0);
  1371. var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker);
  1372. var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker);
  1373. if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) { continue }
  1374. if (fromCmp <= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.to, from) >= 0 : cmp(found.to, from) > 0) ||
  1375. fromCmp >= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.from, to) <= 0 : cmp(found.from, to) < 0))
  1376. { return true }
  1377. } }
  1378. }
  1379. // A visual line is a line as drawn on the screen. Folding, for
  1380. // example, can cause multiple logical lines to appear on the same
  1381. // visual line. This finds the start of the visual line that the
  1382. // given line is part of (usually that is the line itself).
  1383. function visualLine(line) {
  1384. var merged;
  1385. while (merged = collapsedSpanAtStart(line))
  1386. { line = merged.find(-1, true).line; }
  1387. return line
  1388. }
  1389. function visualLineEnd(line) {
  1390. var merged;
  1391. while (merged = collapsedSpanAtEnd(line))
  1392. { line = merged.find(1, true).line; }
  1393. return line
  1394. }
  1395. // Returns an array of logical lines that continue the visual line
  1396. // started by the argument, or undefined if there are no such lines.
  1397. function visualLineContinued(line) {
  1398. var merged, lines;
  1399. while (merged = collapsedSpanAtEnd(line)) {
  1400. line = merged.find(1, true).line
  1401. ;(lines || (lines = [])).push(line);
  1402. }
  1403. return lines
  1404. }
  1405. // Get the line number of the start of the visual line that the
  1406. // given line number is part of.
  1407. function visualLineNo(doc, lineN) {
  1408. var line = getLine(doc, lineN), vis = visualLine(line);
  1409. if (line == vis) { return lineN }
  1410. return lineNo(vis)
  1411. }
  1412. // Get the line number of the start of the next visual line after
  1413. // the given line.
  1414. function visualLineEndNo(doc, lineN) {
  1415. if (lineN > doc.lastLine()) { return lineN }
  1416. var line = getLine(doc, lineN), merged;
  1417. if (!lineIsHidden(doc, line)) { return lineN }
  1418. while (merged = collapsedSpanAtEnd(line))
  1419. { line = merged.find(1, true).line; }
  1420. return lineNo(line) + 1
  1421. }
  1422. // Compute whether a line is hidden. Lines count as hidden when they
  1423. // are part of a visual line that starts with another line, or when
  1424. // they are entirely covered by collapsed, non-widget span.
  1425. function lineIsHidden(doc, line) {
  1426. var sps = sawCollapsedSpans && line.markedSpans;
  1427. if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) {
  1428. sp = sps[i];
  1429. if (!sp.marker.collapsed) { continue }
  1430. if (sp.from == null) { return true }
  1431. if (sp.marker.widgetNode) { continue }
  1432. if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp))
  1433. { return true }
  1434. } }
  1435. }
  1436. function lineIsHiddenInner(doc, line, span) {
  1437. if (span.to == null) {
  1438. var end = span.marker.find(1, true);
  1439. return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker))
  1440. }
  1441. if (span.marker.inclusiveRight && span.to == line.text.length)
  1442. { return true }
  1443. for (var sp = (void 0), i = 0; i < line.markedSpans.length; ++i) {
  1444. sp = line.markedSpans[i];
  1445. if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to &&
  1446. (sp.to == null || sp.to != span.from) &&
  1447. (sp.marker.inclusiveLeft || span.marker.inclusiveRight) &&
  1448. lineIsHiddenInner(doc, line, sp)) { return true }
  1449. }
  1450. }
  1451. // Find the height above the given line.
  1452. function heightAtLine(lineObj) {
  1453. lineObj = visualLine(lineObj);
  1454. var h = 0, chunk = lineObj.parent;
  1455. for (var i = 0; i < chunk.lines.length; ++i) {
  1456. var line = chunk.lines[i];
  1457. if (line == lineObj) { break }
  1458. else { h += line.height; }
  1459. }
  1460. for (var p = chunk.parent; p; chunk = p, p = chunk.parent) {
  1461. for (var i$1 = 0; i$1 < p.children.length; ++i$1) {
  1462. var cur = p.children[i$1];
  1463. if (cur == chunk) { break }
  1464. else { h += cur.height; }
  1465. }
  1466. }
  1467. return h
  1468. }
  1469. // Compute the character length of a line, taking into account
  1470. // collapsed ranges (see markText) that might hide parts, and join
  1471. // other lines onto it.
  1472. function lineLength(line) {
  1473. if (line.height == 0) { return 0 }
  1474. var len = line.text.length, merged, cur = line;
  1475. while (merged = collapsedSpanAtStart(cur)) {
  1476. var found = merged.find(0, true);
  1477. cur = found.from.line;
  1478. len += found.from.ch - found.to.ch;
  1479. }
  1480. cur = line;
  1481. while (merged = collapsedSpanAtEnd(cur)) {
  1482. var found$1 = merged.find(0, true);
  1483. len -= cur.text.length - found$1.from.ch;
  1484. cur = found$1.to.line;
  1485. len += cur.text.length - found$1.to.ch;
  1486. }
  1487. return len
  1488. }
  1489. // Find the longest line in the document.
  1490. function findMaxLine(cm) {
  1491. var d = cm.display, doc = cm.doc;
  1492. d.maxLine = getLine(doc, doc.first);
  1493. d.maxLineLength = lineLength(d.maxLine);
  1494. d.maxLineChanged = true;
  1495. doc.iter(function (line) {
  1496. var len = lineLength(line);
  1497. if (len > d.maxLineLength) {
  1498. d.maxLineLength = len;
  1499. d.maxLine = line;
  1500. }
  1501. });
  1502. }
  1503. // LINE DATA STRUCTURE
  1504. // Line objects. These hold state related to a line, including
  1505. // highlighting info (the styles array).
  1506. var Line = function(text, markedSpans, estimateHeight) {
  1507. this.text = text;
  1508. attachMarkedSpans(this, markedSpans);
  1509. this.height = estimateHeight ? estimateHeight(this) : 1;
  1510. };
  1511. Line.prototype.lineNo = function () { return lineNo(this) };
  1512. eventMixin(Line);
  1513. // Change the content (text, markers) of a line. Automatically
  1514. // invalidates cached information and tries to re-estimate the
  1515. // line's height.
  1516. function updateLine(line, text, markedSpans, estimateHeight) {
  1517. line.text = text;
  1518. if (line.stateAfter) { line.stateAfter = null; }
  1519. if (line.styles) { line.styles = null; }
  1520. if (line.order != null) { line.order = null; }
  1521. detachMarkedSpans(line);
  1522. attachMarkedSpans(line, markedSpans);
  1523. var estHeight = estimateHeight ? estimateHeight(line) : 1;
  1524. if (estHeight != line.height) { updateLineHeight(line, estHeight); }
  1525. }
  1526. // Detach a line from the document tree and its markers.
  1527. function cleanUpLine(line) {
  1528. line.parent = null;
  1529. detachMarkedSpans(line);
  1530. }
  1531. // Convert a style as returned by a mode (either null, or a string
  1532. // containing one or more styles) to a CSS style. This is cached,
  1533. // and also looks for line-wide styles.
  1534. var styleToClassCache = {}, styleToClassCacheWithMode = {};
  1535. function interpretTokenStyle(style, options) {
  1536. if (!style || /^\s*$/.test(style)) { return null }
  1537. var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache;
  1538. return cache[style] ||
  1539. (cache[style] = style.replace(/\S+/g, "cm-$&"))
  1540. }
  1541. // Render the DOM representation of the text of a line. Also builds
  1542. // up a 'line map', which points at the DOM nodes that represent
  1543. // specific stretches of text, and is used by the measuring code.
  1544. // The returned object contains the DOM node, this map, and
  1545. // information about line-wide styles that were set by the mode.
  1546. function buildLineContent(cm, lineView) {
  1547. // The padding-right forces the element to have a 'border', which
  1548. // is needed on Webkit to be able to get line-level bounding
  1549. // rectangles for it (in measureChar).
  1550. var content = eltP("span", null, null, webkit ? "padding-right: .1px" : null);
  1551. var builder = {pre: eltP("pre", [content], "CodeMirror-line"), content: content,
  1552. col: 0, pos: 0, cm: cm,
  1553. trailingSpace: false,
  1554. splitSpaces: cm.getOption("lineWrapping")};
  1555. lineView.measure = {};
  1556. // Iterate over the logical lines that make up this visual line.
  1557. for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) {
  1558. var line = i ? lineView.rest[i - 1] : lineView.line, order = (void 0);
  1559. builder.pos = 0;
  1560. builder.addToken = buildToken;
  1561. // Optionally wire in some hacks into the token-rendering
  1562. // algorithm, to deal with browser quirks.
  1563. if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line, cm.doc.direction)))
  1564. { builder.addToken = buildTokenBadBidi(builder.addToken, order); }
  1565. builder.map = [];
  1566. var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line);
  1567. insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate));
  1568. if (line.styleClasses) {
  1569. if (line.styleClasses.bgClass)
  1570. { builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || ""); }
  1571. if (line.styleClasses.textClass)
  1572. { builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || ""); }
  1573. }
  1574. // Ensure at least a single node is present, for measuring.
  1575. if (builder.map.length == 0)
  1576. { builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure))); }
  1577. // Store the map and a cache object for the current logical line
  1578. if (i == 0) {
  1579. lineView.measure.map = builder.map;
  1580. lineView.measure.cache = {};
  1581. } else {
  1582. (lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map)
  1583. ;(lineView.measure.caches || (lineView.measure.caches = [])).push({});
  1584. }
  1585. }
  1586. // See issue #2901
  1587. if (webkit) {
  1588. var last = builder.content.lastChild;
  1589. if (/\bcm-tab\b/.test(last.className) || (last.querySelector && last.querySelector(".cm-tab")))
  1590. { builder.content.className = "cm-tab-wrap-hack"; }
  1591. }
  1592. signal(cm, "renderLine", cm, lineView.line, builder.pre);
  1593. if (builder.pre.className)
  1594. { builder.textClass = joinClasses(builder.pre.className, builder.textClass || ""); }
  1595. return builder
  1596. }
  1597. function defaultSpecialCharPlaceholder(ch) {
  1598. var token = elt("span", "\u2022", "cm-invalidchar");
  1599. token.title = "\\u" + ch.charCodeAt(0).toString(16);
  1600. token.setAttribute("aria-label", token.title);
  1601. return token
  1602. }
  1603. // Build up the DOM representation for a single token, and add it to
  1604. // the line map. Takes care to render special characters separately.
  1605. function buildToken(builder, text, style, startStyle, endStyle, css, attributes) {
  1606. if (!text) { return }
  1607. var displayText = builder.splitSpaces ? splitSpaces(text, builder.trailingSpace) : text;
  1608. var special = builder.cm.state.specialChars, mustWrap = false;
  1609. var content;
  1610. if (!special.test(text)) {
  1611. builder.col += text.length;
  1612. content = document.createTextNode(displayText);
  1613. builder.map.push(builder.pos, builder.pos + text.length, content);
  1614. if (ie && ie_version < 9) { mustWrap = true; }
  1615. builder.pos += text.length;
  1616. } else {
  1617. content = document.createDocumentFragment();
  1618. var pos = 0;
  1619. while (true) {
  1620. special.lastIndex = pos;
  1621. var m = special.exec(text);
  1622. var skipped = m ? m.index - pos : text.length - pos;
  1623. if (skipped) {
  1624. var txt = document.createTextNode(displayText.slice(pos, pos + skipped));
  1625. if (ie && ie_version < 9) { content.appendChild(elt("span", [txt])); }
  1626. else { content.appendChild(txt); }
  1627. builder.map.push(builder.pos, builder.pos + skipped, txt);
  1628. builder.col += skipped;
  1629. builder.pos += skipped;
  1630. }
  1631. if (!m) { break }
  1632. pos += skipped + 1;
  1633. var txt$1 = (void 0);
  1634. if (m[0] == "\t") {
  1635. var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize;
  1636. txt$1 = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab"));
  1637. txt$1.setAttribute("role", "presentation");
  1638. txt$1.setAttribute("cm-text", "\t");
  1639. builder.col += tabWidth;
  1640. } else if (m[0] == "\r" || m[0] == "\n") {
  1641. txt$1 = content.appendChild(elt("span", m[0] == "\r" ? "\u240d" : "\u2424", "cm-invalidchar"));
  1642. txt$1.setAttribute("cm-text", m[0]);
  1643. builder.col += 1;
  1644. } else {
  1645. txt$1 = builder.cm.options.specialCharPlaceholder(m[0]);
  1646. txt$1.setAttribute("cm-text", m[0]);
  1647. if (ie && ie_version < 9) { content.appendChild(elt("span", [txt$1])); }
  1648. else { content.appendChild(txt$1); }
  1649. builder.col += 1;
  1650. }
  1651. builder.map.push(builder.pos, builder.pos + 1, txt$1);
  1652. builder.pos++;
  1653. }
  1654. }
  1655. builder.trailingSpace = displayText.charCodeAt(text.length - 1) == 32;
  1656. if (style || startStyle || endStyle || mustWrap || css) {
  1657. var fullStyle = style || "";
  1658. if (startStyle) { fullStyle += startStyle; }
  1659. if (endStyle) { fullStyle += endStyle; }
  1660. var token = elt("span", [content], fullStyle, css);
  1661. if (attributes) {
  1662. for (var attr in attributes) { if (attributes.hasOwnProperty(attr) && attr != "style" && attr != "class")
  1663. { token.setAttribute(attr, attributes[attr]); } }
  1664. }
  1665. return builder.content.appendChild(token)
  1666. }
  1667. builder.content.appendChild(content);
  1668. }
  1669. // Change some spaces to NBSP to prevent the browser from collapsing
  1670. // trailing spaces at the end of a line when rendering text (issue #1362).
  1671. function splitSpaces(text, trailingBefore) {
  1672. if (text.length > 1 && !/ /.test(text)) { return text }
  1673. var spaceBefore = trailingBefore, result = "";
  1674. for (var i = 0; i < text.length; i++) {
  1675. var ch = text.charAt(i);
  1676. if (ch == " " && spaceBefore && (i == text.length - 1 || text.charCodeAt(i + 1) == 32))
  1677. { ch = "\u00a0"; }
  1678. result += ch;
  1679. spaceBefore = ch == " ";
  1680. }
  1681. return result
  1682. }
  1683. // Work around nonsense dimensions being reported for stretches of
  1684. // right-to-left text.
  1685. function buildTokenBadBidi(inner, order) {
  1686. return function (builder, text, style, startStyle, endStyle, css, attributes) {
  1687. style = style ? style + " cm-force-border" : "cm-force-border";
  1688. var start = builder.pos, end = start + text.length;
  1689. for (;;) {
  1690. // Find the part that overlaps with the start of this text
  1691. var part = (void 0);
  1692. for (var i = 0; i < order.length; i++) {
  1693. part = order[i];
  1694. if (part.to > start && part.from <= start) { break }
  1695. }
  1696. if (part.to >= end) { return inner(builder, text, style, startStyle, endStyle, css, attributes) }
  1697. inner(builder, text.slice(0, part.to - start), style, startStyle, null, css, attributes);
  1698. startStyle = null;
  1699. text = text.slice(part.to - start);
  1700. start = part.to;
  1701. }
  1702. }
  1703. }
  1704. function buildCollapsedSpan(builder, size, marker, ignoreWidget) {
  1705. var widget = !ignoreWidget && marker.widgetNode;
  1706. if (widget) { builder.map.push(builder.pos, builder.pos + size, widget); }
  1707. if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) {
  1708. if (!widget)
  1709. { widget = builder.content.appendChild(document.createElement("span")); }
  1710. widget.setAttribute("cm-marker", marker.id);
  1711. }
  1712. if (widget) {
  1713. builder.cm.display.input.setUneditable(widget);
  1714. builder.content.appendChild(widget);
  1715. }
  1716. builder.pos += size;
  1717. builder.trailingSpace = false;
  1718. }
  1719. // Outputs a number of spans to make up a line, taking highlighting
  1720. // and marked text into account.
  1721. function insertLineContent(line, builder, styles) {
  1722. var spans = line.markedSpans, allText = line.text, at = 0;
  1723. if (!spans) {
  1724. for (var i$1 = 1; i$1 < styles.length; i$1+=2)
  1725. { builder.addToken(builder, allText.slice(at, at = styles[i$1]), interpretTokenStyle(styles[i$1+1], builder.cm.options)); }
  1726. return
  1727. }
  1728. var len = allText.length, pos = 0, i = 1, text = "", style, css;
  1729. var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, collapsed, attributes;
  1730. for (;;) {
  1731. if (nextChange == pos) { // Update current marker set
  1732. spanStyle = spanEndStyle = spanStartStyle = css = "";
  1733. attributes = null;
  1734. collapsed = null; nextChange = Infinity;
  1735. var foundBookmarks = [], endStyles = (void 0);
  1736. for (var j = 0; j < spans.length; ++j) {
  1737. var sp = spans[j], m = sp.marker;
  1738. if (m.type == "bookmark" && sp.from == pos && m.widgetNode) {
  1739. foundBookmarks.push(m);
  1740. } else if (sp.from <= pos && (sp.to == null || sp.to > pos || m.collapsed && sp.to == pos && sp.from == pos)) {
  1741. if (sp.to != null && sp.to != pos && nextChange > sp.to) {
  1742. nextChange = sp.to;
  1743. spanEndStyle = "";
  1744. }
  1745. if (m.className) { spanStyle += " " + m.className; }
  1746. if (m.css) { css = (css ? css + ";" : "") + m.css; }
  1747. if (m.startStyle && sp.from == pos) { spanStartStyle += " " + m.startStyle; }
  1748. if (m.endStyle && sp.to == nextChange) { (endStyles || (endStyles = [])).push(m.endStyle, sp.to); }
  1749. // support for the old title property
  1750. // https://github.com/codemirror/CodeMirror/pull/5673
  1751. if (m.title) { (attributes || (attributes = {})).title = m.title; }
  1752. if (m.attributes) {
  1753. for (var attr in m.attributes)
  1754. { (attributes || (attributes = {}))[attr] = m.attributes[attr]; }
  1755. }
  1756. if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0))
  1757. { collapsed = sp; }
  1758. } else if (sp.from > pos && nextChange > sp.from) {
  1759. nextChange = sp.from;
  1760. }
  1761. }
  1762. if (endStyles) { for (var j$1 = 0; j$1 < endStyles.length; j$1 += 2)
  1763. { if (endStyles[j$1 + 1] == nextChange) { spanEndStyle += " " + endStyles[j$1]; } } }
  1764. if (!collapsed || collapsed.from == pos) { for (var j$2 = 0; j$2 < foundBookmarks.length; ++j$2)
  1765. { buildCollapsedSpan(builder, 0, foundBookmarks[j$2]); } }
  1766. if (collapsed && (collapsed.from || 0) == pos) {
  1767. buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos,
  1768. collapsed.marker, collapsed.from == null);
  1769. if (collapsed.to == null) { return }
  1770. if (collapsed.to == pos) { collapsed = false; }
  1771. }
  1772. }
  1773. if (pos >= len) { break }
  1774. var upto = Math.min(len, nextChange);
  1775. while (true) {
  1776. if (text) {
  1777. var end = pos + text.length;
  1778. if (!collapsed) {
  1779. var tokenText = end > upto ? text.slice(0, upto - pos) : text;
  1780. builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle,
  1781. spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", css, attributes);
  1782. }
  1783. if (end >= upto) {text = text.slice(upto - pos); pos = upto; break}
  1784. pos = end;
  1785. spanStartStyle = "";
  1786. }
  1787. text = allText.slice(at, at = styles[i++]);
  1788. style = interpretTokenStyle(styles[i++], builder.cm.options);
  1789. }
  1790. }
  1791. }
  1792. // These objects are used to represent the visible (currently drawn)
  1793. // part of the document. A LineView may correspond to multiple
  1794. // logical lines, if those are connected by collapsed ranges.
  1795. function LineView(doc, line, lineN) {
  1796. // The starting line
  1797. this.line = line;
  1798. // Continuing lines, if any
  1799. this.rest = visualLineContinued(line);
  1800. // Number of logical lines in this visual line
  1801. this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1;
  1802. this.node = this.text = null;
  1803. this.hidden = lineIsHidden(doc, line);
  1804. }
  1805. // Create a range of LineView objects for the given lines.
  1806. function buildViewArray(cm, from, to) {
  1807. var array = [], nextPos;
  1808. for (var pos = from; pos < to; pos = nextPos) {
  1809. var view = new LineView(cm.doc, getLine(cm.doc, pos), pos);
  1810. nextPos = pos + view.size;
  1811. array.push(view);
  1812. }
  1813. return array
  1814. }
  1815. var operationGroup = null;
  1816. function pushOperation(op) {
  1817. if (operationGroup) {
  1818. operationGroup.ops.push(op);
  1819. } else {
  1820. op.ownsGroup = operationGroup = {
  1821. ops: [op],
  1822. delayedCallbacks: []
  1823. };
  1824. }
  1825. }
  1826. function fireCallbacksForOps(group) {
  1827. // Calls delayed callbacks and cursorActivity handlers until no
  1828. // new ones appear
  1829. var callbacks = group.delayedCallbacks, i = 0;
  1830. do {
  1831. for (; i < callbacks.length; i++)
  1832. { callbacks[i].call(null); }
  1833. for (var j = 0; j < group.ops.length; j++) {
  1834. var op = group.ops[j];
  1835. if (op.cursorActivityHandlers)
  1836. { while (op.cursorActivityCalled < op.cursorActivityHandlers.length)
  1837. { op.cursorActivityHandlers[op.cursorActivityCalled++].call(null, op.cm); } }
  1838. }
  1839. } while (i < callbacks.length)
  1840. }
  1841. function finishOperation(op, endCb) {
  1842. var group = op.ownsGroup;
  1843. if (!group) { return }
  1844. try { fireCallbacksForOps(group); }
  1845. finally {
  1846. operationGroup = null;
  1847. endCb(group);
  1848. }
  1849. }
  1850. var orphanDelayedCallbacks = null;
  1851. // Often, we want to signal events at a point where we are in the
  1852. // middle of some work, but don't want the handler to start calling
  1853. // other methods on the editor, which might be in an inconsistent
  1854. // state or simply not expect any other events to happen.
  1855. // signalLater looks whether there are any handlers, and schedules
  1856. // them to be executed when the last operation ends, or, if no
  1857. // operation is active, when a timeout fires.
  1858. function signalLater(emitter, type /*, values...*/) {
  1859. var arr = getHandlers(emitter, type);
  1860. if (!arr.length) { return }
  1861. var args = Array.prototype.slice.call(arguments, 2), list;
  1862. if (operationGroup) {
  1863. list = operationGroup.delayedCallbacks;
  1864. } else if (orphanDelayedCallbacks) {
  1865. list = orphanDelayedCallbacks;
  1866. } else {
  1867. list = orphanDelayedCallbacks = [];
  1868. setTimeout(fireOrphanDelayed, 0);
  1869. }
  1870. var loop = function ( i ) {
  1871. list.push(function () { return arr[i].apply(null, args); });
  1872. };
  1873. for (var i = 0; i < arr.length; ++i)
  1874. loop( i );
  1875. }
  1876. function fireOrphanDelayed() {
  1877. var delayed = orphanDelayedCallbacks;
  1878. orphanDelayedCallbacks = null;
  1879. for (var i = 0; i < delayed.length; ++i) { delayed[i](); }
  1880. }
  1881. // When an aspect of a line changes, a string is added to
  1882. // lineView.changes. This updates the relevant part of the line's
  1883. // DOM structure.
  1884. function updateLineForChanges(cm, lineView, lineN, dims) {
  1885. for (var j = 0; j < lineView.changes.length; j++) {
  1886. var type = lineView.changes[j];
  1887. if (type == "text") { updateLineText(cm, lineView); }
  1888. else if (type == "gutter") { updateLineGutter(cm, lineView, lineN, dims); }
  1889. else if (type == "class") { updateLineClasses(cm, lineView); }
  1890. else if (type == "widget") { updateLineWidgets(cm, lineView, dims); }
  1891. }
  1892. lineView.changes = null;
  1893. }
  1894. // Lines with gutter elements, widgets or a background class need to
  1895. // be wrapped, and have the extra elements added to the wrapper div
  1896. function ensureLineWrapped(lineView) {
  1897. if (lineView.node == lineView.text) {
  1898. lineView.node = elt("div", null, null, "position: relative");
  1899. if (lineView.text.parentNode)
  1900. { lineView.text.parentNode.replaceChild(lineView.node, lineView.text); }
  1901. lineView.node.appendChild(lineView.text);
  1902. if (ie && ie_version < 8) { lineView.node.style.zIndex = 2; }
  1903. }
  1904. return lineView.node
  1905. }
  1906. function updateLineBackground(cm, lineView) {
  1907. var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass;
  1908. if (cls) { cls += " CodeMirror-linebackground"; }
  1909. if (lineView.background) {
  1910. if (cls) { lineView.background.className = cls; }
  1911. else { lineView.background.parentNode.removeChild(lineView.background); lineView.background = null; }
  1912. } else if (cls) {
  1913. var wrap = ensureLineWrapped(lineView);
  1914. lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild);
  1915. cm.display.input.setUneditable(lineView.background);
  1916. }
  1917. }
  1918. // Wrapper around buildLineContent which will reuse the structure
  1919. // in display.externalMeasured when possible.
  1920. function getLineContent(cm, lineView) {
  1921. var ext = cm.display.externalMeasured;
  1922. if (ext && ext.line == lineView.line) {
  1923. cm.display.externalMeasured = null;
  1924. lineView.measure = ext.measure;
  1925. return ext.built
  1926. }
  1927. return buildLineContent(cm, lineView)
  1928. }
  1929. // Redraw the line's text. Interacts with the background and text
  1930. // classes because the mode may output tokens that influence these
  1931. // classes.
  1932. function updateLineText(cm, lineView) {
  1933. var cls = lineView.text.className;
  1934. var built = getLineContent(cm, lineView);
  1935. if (lineView.text == lineView.node) { lineView.node = built.pre; }
  1936. lineView.text.parentNode.replaceChild(built.pre, lineView.text);
  1937. lineView.text = built.pre;
  1938. if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) {
  1939. lineView.bgClass = built.bgClass;
  1940. lineView.textClass = built.textClass;
  1941. updateLineClasses(cm, lineView);
  1942. } else if (cls) {
  1943. lineView.text.className = cls;
  1944. }
  1945. }
  1946. function updateLineClasses(cm, lineView) {
  1947. updateLineBackground(cm, lineView);
  1948. if (lineView.line.wrapClass)
  1949. { ensureLineWrapped(lineView).className = lineView.line.wrapClass; }
  1950. else if (lineView.node != lineView.text)
  1951. { lineView.node.className = ""; }
  1952. var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass;
  1953. lineView.text.className = textClass || "";
  1954. }
  1955. function updateLineGutter(cm, lineView, lineN, dims) {
  1956. if (lineView.gutter) {
  1957. lineView.node.removeChild(lineView.gutter);
  1958. lineView.gutter = null;
  1959. }
  1960. if (lineView.gutterBackground) {
  1961. lineView.node.removeChild(lineView.gutterBackground);
  1962. lineView.gutterBackground = null;
  1963. }
  1964. if (lineView.line.gutterClass) {
  1965. var wrap = ensureLineWrapped(lineView);
  1966. lineView.gutterBackground = elt("div", null, "CodeMirror-gutter-background " + lineView.line.gutterClass,
  1967. ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px; width: " + (dims.gutterTotalWidth) + "px"));
  1968. cm.display.input.setUneditable(lineView.gutterBackground);
  1969. wrap.insertBefore(lineView.gutterBackground, lineView.text);
  1970. }
  1971. var markers = lineView.line.gutterMarkers;
  1972. if (cm.options.lineNumbers || markers) {
  1973. var wrap$1 = ensureLineWrapped(lineView);
  1974. var gutterWrap = lineView.gutter = elt("div", null, "CodeMirror-gutter-wrapper", ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px"));
  1975. cm.display.input.setUneditable(gutterWrap);
  1976. wrap$1.insertBefore(gutterWrap, lineView.text);
  1977. if (lineView.line.gutterClass)
  1978. { gutterWrap.className += " " + lineView.line.gutterClass; }
  1979. if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"]))
  1980. { lineView.lineNumber = gutterWrap.appendChild(
  1981. elt("div", lineNumberFor(cm.options, lineN),
  1982. "CodeMirror-linenumber CodeMirror-gutter-elt",
  1983. ("left: " + (dims.gutterLeft["CodeMirror-linenumbers"]) + "px; width: " + (cm.display.lineNumInnerWidth) + "px"))); }
  1984. if (markers) { for (var k = 0; k < cm.display.gutterSpecs.length; ++k) {
  1985. var id = cm.display.gutterSpecs[k].className, found = markers.hasOwnProperty(id) && markers[id];
  1986. if (found)
  1987. { gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt",
  1988. ("left: " + (dims.gutterLeft[id]) + "px; width: " + (dims.gutterWidth[id]) + "px"))); }
  1989. } }
  1990. }
  1991. }
  1992. function updateLineWidgets(cm, lineView, dims) {
  1993. if (lineView.alignable) { lineView.alignable = null; }
  1994. for (var node = lineView.node.firstChild, next = (void 0); node; node = next) {
  1995. next = node.nextSibling;
  1996. if (node.className == "CodeMirror-linewidget")
  1997. { lineView.node.removeChild(node); }
  1998. }
  1999. insertLineWidgets(cm, lineView, dims);
  2000. }
  2001. // Build a line's DOM representation from scratch
  2002. function buildLineElement(cm, lineView, lineN, dims) {
  2003. var built = getLineContent(cm, lineView);
  2004. lineView.text = lineView.node = built.pre;
  2005. if (built.bgClass) { lineView.bgClass = built.bgClass; }
  2006. if (built.textClass) { lineView.textClass = built.textClass; }
  2007. updateLineClasses(cm, lineView);
  2008. updateLineGutter(cm, lineView, lineN, dims);
  2009. insertLineWidgets(cm, lineView, dims);
  2010. return lineView.node
  2011. }
  2012. // A lineView may contain multiple logical lines (when merged by
  2013. // collapsed spans). The widgets for all of them need to be drawn.
  2014. function insertLineWidgets(cm, lineView, dims) {
  2015. insertLineWidgetsFor(cm, lineView.line, lineView, dims, true);
  2016. if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++)
  2017. { insertLineWidgetsFor(cm, lineView.rest[i], lineView, dims, false); } }
  2018. }
  2019. function insertLineWidgetsFor(cm, line, lineView, dims, allowAbove) {
  2020. if (!line.widgets) { return }
  2021. var wrap = ensureLineWrapped(lineView);
  2022. for (var i = 0, ws = line.widgets; i < ws.length; ++i) {
  2023. var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget");
  2024. if (!widget.handleMouseEvents) { node.setAttribute("cm-ignore-events", "true"); }
  2025. positionLineWidget(widget, node, lineView, dims);
  2026. cm.display.input.setUneditable(node);
  2027. if (allowAbove && widget.above)
  2028. { wrap.insertBefore(node, lineView.gutter || lineView.text); }
  2029. else
  2030. { wrap.appendChild(node); }
  2031. signalLater(widget, "redraw");
  2032. }
  2033. }
  2034. function positionLineWidget(widget, node, lineView, dims) {
  2035. if (widget.noHScroll) {
  2036. (lineView.alignable || (lineView.alignable = [])).push(node);
  2037. var width = dims.wrapperWidth;
  2038. node.style.left = dims.fixedPos + "px";
  2039. if (!widget.coverGutter) {
  2040. width -= dims.gutterTotalWidth;
  2041. node.style.paddingLeft = dims.gutterTotalWidth + "px";
  2042. }
  2043. node.style.width = width + "px";
  2044. }
  2045. if (widget.coverGutter) {
  2046. node.style.zIndex = 5;
  2047. node.style.position = "relative";
  2048. if (!widget.noHScroll) { node.style.marginLeft = -dims.gutterTotalWidth + "px"; }
  2049. }
  2050. }
  2051. function widgetHeight(widget) {
  2052. if (widget.height != null) { return widget.height }
  2053. var cm = widget.doc.cm;
  2054. if (!cm) { return 0 }
  2055. if (!contains(document.body, widget.node)) {
  2056. var parentStyle = "position: relative;";
  2057. if (widget.coverGutter)
  2058. { parentStyle += "margin-left: -" + cm.display.gutters.offsetWidth + "px;"; }
  2059. if (widget.noHScroll)
  2060. { parentStyle += "width: " + cm.display.wrapper.clientWidth + "px;"; }
  2061. removeChildrenAndAdd(cm.display.measure, elt("div", [widget.node], null, parentStyle));
  2062. }
  2063. return widget.height = widget.node.parentNode.offsetHeight
  2064. }
  2065. // Return true when the given mouse event happened in a widget
  2066. function eventInWidget(display, e) {
  2067. for (var n = e_target(e); n != display.wrapper; n = n.parentNode) {
  2068. if (!n || (n.nodeType == 1 && n.getAttribute("cm-ignore-events") == "true") ||
  2069. (n.parentNode == display.sizer && n != display.mover))
  2070. { return true }
  2071. }
  2072. }
  2073. // POSITION MEASUREMENT
  2074. function paddingTop(display) {return display.lineSpace.offsetTop}
  2075. function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight}
  2076. function paddingH(display) {
  2077. if (display.cachedPaddingH) { return display.cachedPaddingH }
  2078. var e = removeChildrenAndAdd(display.measure, elt("pre", "x", "CodeMirror-line-like"));
  2079. var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle;
  2080. var data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)};
  2081. if (!isNaN(data.left) && !isNaN(data.right)) { display.cachedPaddingH = data; }
  2082. return data
  2083. }
  2084. function scrollGap(cm) { return scrollerGap - cm.display.nativeBarWidth }
  2085. function displayWidth(cm) {
  2086. return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth
  2087. }
  2088. function displayHeight(cm) {
  2089. return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight
  2090. }
  2091. // Ensure the lineView.wrapping.heights array is populated. This is
  2092. // an array of bottom offsets for the lines that make up a drawn
  2093. // line. When lineWrapping is on, there might be more than one
  2094. // height.
  2095. function ensureLineHeights(cm, lineView, rect) {
  2096. var wrapping = cm.options.lineWrapping;
  2097. var curWidth = wrapping && displayWidth(cm);
  2098. if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) {
  2099. var heights = lineView.measure.heights = [];
  2100. if (wrapping) {
  2101. lineView.measure.width = curWidth;
  2102. var rects = lineView.text.firstChild.getClientRects();
  2103. for (var i = 0; i < rects.length - 1; i++) {
  2104. var cur = rects[i], next = rects[i + 1];
  2105. if (Math.abs(cur.bottom - next.bottom) > 2)
  2106. { heights.push((cur.bottom + next.top) / 2 - rect.top); }
  2107. }
  2108. }
  2109. heights.push(rect.bottom - rect.top);
  2110. }
  2111. }
  2112. // Find a line map (mapping character offsets to text nodes) and a
  2113. // measurement cache for the given line number. (A line view might
  2114. // contain multiple lines when collapsed ranges are present.)
  2115. function mapFromLineView(lineView, line, lineN) {
  2116. if (lineView.line == line)
  2117. { return {map: lineView.measure.map, cache: lineView.measure.cache} }
  2118. for (var i = 0; i < lineView.rest.length; i++)
  2119. { if (lineView.rest[i] == line)
  2120. { return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i]} } }
  2121. for (var i$1 = 0; i$1 < lineView.rest.length; i$1++)
  2122. { if (lineNo(lineView.rest[i$1]) > lineN)
  2123. { return {map: lineView.measure.maps[i$1], cache: lineView.measure.caches[i$1], before: true} } }
  2124. }
  2125. // Render a line into the hidden node display.externalMeasured. Used
  2126. // when measurement is needed for a line that's not in the viewport.
  2127. function updateExternalMeasurement(cm, line) {
  2128. line = visualLine(line);
  2129. var lineN = lineNo(line);
  2130. var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN);
  2131. view.lineN = lineN;
  2132. var built = view.built = buildLineContent(cm, view);
  2133. view.text = built.pre;
  2134. removeChildrenAndAdd(cm.display.lineMeasure, built.pre);
  2135. return view
  2136. }
  2137. // Get a {top, bottom, left, right} box (in line-local coordinates)
  2138. // for a given character.
  2139. function measureChar(cm, line, ch, bias) {
  2140. return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias)
  2141. }
  2142. // Find a line view that corresponds to the given line number.
  2143. function findViewForLine(cm, lineN) {
  2144. if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo)
  2145. { return cm.display.view[findViewIndex(cm, lineN)] }
  2146. var ext = cm.display.externalMeasured;
  2147. if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size)
  2148. { return ext }
  2149. }
  2150. // Measurement can be split in two steps, the set-up work that
  2151. // applies to the whole line, and the measurement of the actual
  2152. // character. Functions like coordsChar, that need to do a lot of
  2153. // measurements in a row, can thus ensure that the set-up work is
  2154. // only done once.
  2155. function prepareMeasureForLine(cm, line) {
  2156. var lineN = lineNo(line);
  2157. var view = findViewForLine(cm, lineN);
  2158. if (view && !view.text) {
  2159. view = null;
  2160. } else if (view && view.changes) {
  2161. updateLineForChanges(cm, view, lineN, getDimensions(cm));
  2162. cm.curOp.forceUpdate = true;
  2163. }
  2164. if (!view)
  2165. { view = updateExternalMeasurement(cm, line); }
  2166. var info = mapFromLineView(view, line, lineN);
  2167. return {
  2168. line: line, view: view, rect: null,
  2169. map: info.map, cache: info.cache, before: info.before,
  2170. hasHeights: false
  2171. }
  2172. }
  2173. // Given a prepared measurement object, measures the position of an
  2174. // actual character (or fetches it from the cache).
  2175. function measureCharPrepared(cm, prepared, ch, bias, varHeight) {
  2176. if (prepared.before) { ch = -1; }
  2177. var key = ch + (bias || ""), found;
  2178. if (prepared.cache.hasOwnProperty(key)) {
  2179. found = prepared.cache[key];
  2180. } else {
  2181. if (!prepared.rect)
  2182. { prepared.rect = prepared.view.text.getBoundingClientRect(); }
  2183. if (!prepared.hasHeights) {
  2184. ensureLineHeights(cm, prepared.view, prepared.rect);
  2185. prepared.hasHeights = true;
  2186. }
  2187. found = measureCharInner(cm, prepared, ch, bias);
  2188. if (!found.bogus) { prepared.cache[key] = found; }
  2189. }
  2190. return {left: found.left, right: found.right,
  2191. top: varHeight ? found.rtop : found.top,
  2192. bottom: varHeight ? found.rbottom : found.bottom}
  2193. }
  2194. var nullRect = {left: 0, right: 0, top: 0, bottom: 0};
  2195. function nodeAndOffsetInLineMap(map$$1, ch, bias) {
  2196. var node, start, end, collapse, mStart, mEnd;
  2197. // First, search the line map for the text node corresponding to,
  2198. // or closest to, the target character.
  2199. for (var i = 0; i < map$$1.length; i += 3) {
  2200. mStart = map$$1[i];
  2201. mEnd = map$$1[i + 1];
  2202. if (ch < mStart) {
  2203. start = 0; end = 1;
  2204. collapse = "left";
  2205. } else if (ch < mEnd) {
  2206. start = ch - mStart;
  2207. end = start + 1;
  2208. } else if (i == map$$1.length - 3 || ch == mEnd && map$$1[i + 3] > ch) {
  2209. end = mEnd - mStart;
  2210. start = end - 1;
  2211. if (ch >= mEnd) { collapse = "right"; }
  2212. }
  2213. if (start != null) {
  2214. node = map$$1[i + 2];
  2215. if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right"))
  2216. { collapse = bias; }
  2217. if (bias == "left" && start == 0)
  2218. { while (i && map$$1[i - 2] == map$$1[i - 3] && map$$1[i - 1].insertLeft) {
  2219. node = map$$1[(i -= 3) + 2];
  2220. collapse = "left";
  2221. } }
  2222. if (bias == "right" && start == mEnd - mStart)
  2223. { while (i < map$$1.length - 3 && map$$1[i + 3] == map$$1[i + 4] && !map$$1[i + 5].insertLeft) {
  2224. node = map$$1[(i += 3) + 2];
  2225. collapse = "right";
  2226. } }
  2227. break
  2228. }
  2229. }
  2230. return {node: node, start: start, end: end, collapse: collapse, coverStart: mStart, coverEnd: mEnd}
  2231. }
  2232. function getUsefulRect(rects, bias) {
  2233. var rect = nullRect;
  2234. if (bias == "left") { for (var i = 0; i < rects.length; i++) {
  2235. if ((rect = rects[i]).left != rect.right) { break }
  2236. } } else { for (var i$1 = rects.length - 1; i$1 >= 0; i$1--) {
  2237. if ((rect = rects[i$1]).left != rect.right) { break }
  2238. } }
  2239. return rect
  2240. }
  2241. function measureCharInner(cm, prepared, ch, bias) {
  2242. var place = nodeAndOffsetInLineMap(prepared.map, ch, bias);
  2243. var node = place.node, start = place.start, end = place.end, collapse = place.collapse;
  2244. var rect;
  2245. if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates.
  2246. for (var i$1 = 0; i$1 < 4; i$1++) { // Retry a maximum of 4 times when nonsense rectangles are returned
  2247. while (start && isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) { --start; }
  2248. while (place.coverStart + end < place.coverEnd && isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) { ++end; }
  2249. if (ie && ie_version < 9 && start == 0 && end == place.coverEnd - place.coverStart)
  2250. { rect = node.parentNode.getBoundingClientRect(); }
  2251. else
  2252. { rect = getUsefulRect(range(node, start, end).getClientRects(), bias); }
  2253. if (rect.left || rect.right || start == 0) { break }
  2254. end = start;
  2255. start = start - 1;
  2256. collapse = "right";
  2257. }
  2258. if (ie && ie_version < 11) { rect = maybeUpdateRectForZooming(cm.display.measure, rect); }
  2259. } else { // If it is a widget, simply get the box for the whole widget.
  2260. if (start > 0) { collapse = bias = "right"; }
  2261. var rects;
  2262. if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1)
  2263. { rect = rects[bias == "right" ? rects.length - 1 : 0]; }
  2264. else
  2265. { rect = node.getBoundingClientRect(); }
  2266. }
  2267. if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) {
  2268. var rSpan = node.parentNode.getClientRects()[0];
  2269. if (rSpan)
  2270. { rect = {left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom}; }
  2271. else
  2272. { rect = nullRect; }
  2273. }
  2274. var rtop = rect.top - prepared.rect.top, rbot = rect.bottom - prepared.rect.top;
  2275. var mid = (rtop + rbot) / 2;
  2276. var heights = prepared.view.measure.heights;
  2277. var i = 0;
  2278. for (; i < heights.length - 1; i++)
  2279. { if (mid < heights[i]) { break } }
  2280. var top = i ? heights[i - 1] : 0, bot = heights[i];
  2281. var result = {left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left,
  2282. right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left,
  2283. top: top, bottom: bot};
  2284. if (!rect.left && !rect.right) { result.bogus = true; }
  2285. if (!cm.options.singleCursorHeightPerLine) { result.rtop = rtop; result.rbottom = rbot; }
  2286. return result
  2287. }
  2288. // Work around problem with bounding client rects on ranges being
  2289. // returned incorrectly when zoomed on IE10 and below.
  2290. function maybeUpdateRectForZooming(measure, rect) {
  2291. if (!window.screen || screen.logicalXDPI == null ||
  2292. screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure))
  2293. { return rect }
  2294. var scaleX = screen.logicalXDPI / screen.deviceXDPI;
  2295. var scaleY = screen.logicalYDPI / screen.deviceYDPI;
  2296. return {left: rect.left * scaleX, right: rect.right * scaleX,
  2297. top: rect.top * scaleY, bottom: rect.bottom * scaleY}
  2298. }
  2299. function clearLineMeasurementCacheFor(lineView) {
  2300. if (lineView.measure) {
  2301. lineView.measure.cache = {};
  2302. lineView.measure.heights = null;
  2303. if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++)
  2304. { lineView.measure.caches[i] = {}; } }
  2305. }
  2306. }
  2307. function clearLineMeasurementCache(cm) {
  2308. cm.display.externalMeasure = null;
  2309. removeChildren(cm.display.lineMeasure);
  2310. for (var i = 0; i < cm.display.view.length; i++)
  2311. { clearLineMeasurementCacheFor(cm.display.view[i]); }
  2312. }
  2313. function clearCaches(cm) {
  2314. clearLineMeasurementCache(cm);
  2315. cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null;
  2316. if (!cm.options.lineWrapping) { cm.display.maxLineChanged = true; }
  2317. cm.display.lineNumChars = null;
  2318. }
  2319. function pageScrollX() {
  2320. // Work around https://bugs.chromium.org/p/chromium/issues/detail?id=489206
  2321. // which causes page_Offset and bounding client rects to use
  2322. // different reference viewports and invalidate our calculations.
  2323. if (chrome && android) { return -(document.body.getBoundingClientRect().left - parseInt(getComputedStyle(document.body).marginLeft)) }
  2324. return window.pageXOffset || (document.documentElement || document.body).scrollLeft
  2325. }
  2326. function pageScrollY() {
  2327. if (chrome && android) { return -(document.body.getBoundingClientRect().top - parseInt(getComputedStyle(document.body).marginTop)) }
  2328. return window.pageYOffset || (document.documentElement || document.body).scrollTop
  2329. }
  2330. function widgetTopHeight(lineObj) {
  2331. var height = 0;
  2332. if (lineObj.widgets) { for (var i = 0; i < lineObj.widgets.length; ++i) { if (lineObj.widgets[i].above)
  2333. { height += widgetHeight(lineObj.widgets[i]); } } }
  2334. return height
  2335. }
  2336. // Converts a {top, bottom, left, right} box from line-local
  2337. // coordinates into another coordinate system. Context may be one of
  2338. // "line", "div" (display.lineDiv), "local"./null (editor), "window",
  2339. // or "page".
  2340. function intoCoordSystem(cm, lineObj, rect, context, includeWidgets) {
  2341. if (!includeWidgets) {
  2342. var height = widgetTopHeight(lineObj);
  2343. rect.top += height; rect.bottom += height;
  2344. }
  2345. if (context == "line") { return rect }
  2346. if (!context) { context = "local"; }
  2347. var yOff = heightAtLine(lineObj);
  2348. if (context == "local") { yOff += paddingTop(cm.display); }
  2349. else { yOff -= cm.display.viewOffset; }
  2350. if (context == "page" || context == "window") {
  2351. var lOff = cm.display.lineSpace.getBoundingClientRect();
  2352. yOff += lOff.top + (context == "window" ? 0 : pageScrollY());
  2353. var xOff = lOff.left + (context == "window" ? 0 : pageScrollX());
  2354. rect.left += xOff; rect.right += xOff;
  2355. }
  2356. rect.top += yOff; rect.bottom += yOff;
  2357. return rect
  2358. }
  2359. // Coverts a box from "div" coords to another coordinate system.
  2360. // Context may be "window", "page", "div", or "local"./null.
  2361. function fromCoordSystem(cm, coords, context) {
  2362. if (context == "div") { return coords }
  2363. var left = coords.left, top = coords.top;
  2364. // First move into "page" coordinate system
  2365. if (context == "page") {
  2366. left -= pageScrollX();
  2367. top -= pageScrollY();
  2368. } else if (context == "local" || !context) {
  2369. var localBox = cm.display.sizer.getBoundingClientRect();
  2370. left += localBox.left;
  2371. top += localBox.top;
  2372. }
  2373. var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect();
  2374. return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top}
  2375. }
  2376. function charCoords(cm, pos, context, lineObj, bias) {
  2377. if (!lineObj) { lineObj = getLine(cm.doc, pos.line); }
  2378. return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context)
  2379. }
  2380. // Returns a box for a given cursor position, which may have an
  2381. // 'other' property containing the position of the secondary cursor
  2382. // on a bidi boundary.
  2383. // A cursor Pos(line, char, "before") is on the same visual line as `char - 1`
  2384. // and after `char - 1` in writing order of `char - 1`
  2385. // A cursor Pos(line, char, "after") is on the same visual line as `char`
  2386. // and before `char` in writing order of `char`
  2387. // Examples (upper-case letters are RTL, lower-case are LTR):
  2388. // Pos(0, 1, ...)
  2389. // before after
  2390. // ab a|b a|b
  2391. // aB a|B aB|
  2392. // Ab |Ab A|b
  2393. // AB B|A B|A
  2394. // Every position after the last character on a line is considered to stick
  2395. // to the last character on the line.
  2396. function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) {
  2397. lineObj = lineObj || getLine(cm.doc, pos.line);
  2398. if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj); }
  2399. function get(ch, right) {
  2400. var m = measureCharPrepared(cm, preparedMeasure, ch, right ? "right" : "left", varHeight);
  2401. if (right) { m.left = m.right; } else { m.right = m.left; }
  2402. return intoCoordSystem(cm, lineObj, m, context)
  2403. }
  2404. var order = getOrder(lineObj, cm.doc.direction), ch = pos.ch, sticky = pos.sticky;
  2405. if (ch >= lineObj.text.length) {
  2406. ch = lineObj.text.length;
  2407. sticky = "before";
  2408. } else if (ch <= 0) {
  2409. ch = 0;
  2410. sticky = "after";
  2411. }
  2412. if (!order) { return get(sticky == "before" ? ch - 1 : ch, sticky == "before") }
  2413. function getBidi(ch, partPos, invert) {
  2414. var part = order[partPos], right = part.level == 1;
  2415. return get(invert ? ch - 1 : ch, right != invert)
  2416. }
  2417. var partPos = getBidiPartAt(order, ch, sticky);
  2418. var other = bidiOther;
  2419. var val = getBidi(ch, partPos, sticky == "before");
  2420. if (other != null) { val.other = getBidi(ch, other, sticky != "before"); }
  2421. return val
  2422. }
  2423. // Used to cheaply estimate the coordinates for a position. Used for
  2424. // intermediate scroll updates.
  2425. function estimateCoords(cm, pos) {
  2426. var left = 0;
  2427. pos = clipPos(cm.doc, pos);
  2428. if (!cm.options.lineWrapping) { left = charWidth(cm.display) * pos.ch; }
  2429. var lineObj = getLine(cm.doc, pos.line);
  2430. var top = heightAtLine(lineObj) + paddingTop(cm.display);
  2431. return {left: left, right: left, top: top, bottom: top + lineObj.height}
  2432. }
  2433. // Positions returned by coordsChar contain some extra information.
  2434. // xRel is the relative x position of the input coordinates compared
  2435. // to the found position (so xRel > 0 means the coordinates are to
  2436. // the right of the character position, for example). When outside
  2437. // is true, that means the coordinates lie outside the line's
  2438. // vertical range.
  2439. function PosWithInfo(line, ch, sticky, outside, xRel) {
  2440. var pos = Pos(line, ch, sticky);
  2441. pos.xRel = xRel;
  2442. if (outside) { pos.outside = outside; }
  2443. return pos
  2444. }
  2445. // Compute the character position closest to the given coordinates.
  2446. // Input must be lineSpace-local ("div" coordinate system).
  2447. function coordsChar(cm, x, y) {
  2448. var doc = cm.doc;
  2449. y += cm.display.viewOffset;
  2450. if (y < 0) { return PosWithInfo(doc.first, 0, null, -1, -1) }
  2451. var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1;
  2452. if (lineN > last)
  2453. { return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, null, 1, 1) }
  2454. if (x < 0) { x = 0; }
  2455. var lineObj = getLine(doc, lineN);
  2456. for (;;) {
  2457. var found = coordsCharInner(cm, lineObj, lineN, x, y);
  2458. var collapsed = collapsedSpanAround(lineObj, found.ch + (found.xRel > 0 || found.outside > 0 ? 1 : 0));
  2459. if (!collapsed) { return found }
  2460. var rangeEnd = collapsed.find(1);
  2461. if (rangeEnd.line == lineN) { return rangeEnd }
  2462. lineObj = getLine(doc, lineN = rangeEnd.line);
  2463. }
  2464. }
  2465. function wrappedLineExtent(cm, lineObj, preparedMeasure, y) {
  2466. y -= widgetTopHeight(lineObj);
  2467. var end = lineObj.text.length;
  2468. var begin = findFirst(function (ch) { return measureCharPrepared(cm, preparedMeasure, ch - 1).bottom <= y; }, end, 0);
  2469. end = findFirst(function (ch) { return measureCharPrepared(cm, preparedMeasure, ch).top > y; }, begin, end);
  2470. return {begin: begin, end: end}
  2471. }
  2472. function wrappedLineExtentChar(cm, lineObj, preparedMeasure, target) {
  2473. if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj); }
  2474. var targetTop = intoCoordSystem(cm, lineObj, measureCharPrepared(cm, preparedMeasure, target), "line").top;
  2475. return wrappedLineExtent(cm, lineObj, preparedMeasure, targetTop)
  2476. }
  2477. // Returns true if the given side of a box is after the given
  2478. // coordinates, in top-to-bottom, left-to-right order.
  2479. function boxIsAfter(box, x, y, left) {
  2480. return box.bottom <= y ? false : box.top > y ? true : (left ? box.left : box.right) > x
  2481. }
  2482. function coordsCharInner(cm, lineObj, lineNo$$1, x, y) {
  2483. // Move y into line-local coordinate space
  2484. y -= heightAtLine(lineObj);
  2485. var preparedMeasure = prepareMeasureForLine(cm, lineObj);
  2486. // When directly calling `measureCharPrepared`, we have to adjust
  2487. // for the widgets at this line.
  2488. var widgetHeight$$1 = widgetTopHeight(lineObj);
  2489. var begin = 0, end = lineObj.text.length, ltr = true;
  2490. var order = getOrder(lineObj, cm.doc.direction);
  2491. // If the line isn't plain left-to-right text, first figure out
  2492. // which bidi section the coordinates fall into.
  2493. if (order) {
  2494. var part = (cm.options.lineWrapping ? coordsBidiPartWrapped : coordsBidiPart)
  2495. (cm, lineObj, lineNo$$1, preparedMeasure, order, x, y);
  2496. ltr = part.level != 1;
  2497. // The awkward -1 offsets are needed because findFirst (called
  2498. // on these below) will treat its first bound as inclusive,
  2499. // second as exclusive, but we want to actually address the
  2500. // characters in the part's range
  2501. begin = ltr ? part.from : part.to - 1;
  2502. end = ltr ? part.to : part.from - 1;
  2503. }
  2504. // A binary search to find the first character whose bounding box
  2505. // starts after the coordinates. If we run across any whose box wrap
  2506. // the coordinates, store that.
  2507. var chAround = null, boxAround = null;
  2508. var ch = findFirst(function (ch) {
  2509. var box = measureCharPrepared(cm, preparedMeasure, ch);
  2510. box.top += widgetHeight$$1; box.bottom += widgetHeight$$1;
  2511. if (!boxIsAfter(box, x, y, false)) { return false }
  2512. if (box.top <= y && box.left <= x) {
  2513. chAround = ch;
  2514. boxAround = box;
  2515. }
  2516. return true
  2517. }, begin, end);
  2518. var baseX, sticky, outside = false;
  2519. // If a box around the coordinates was found, use that
  2520. if (boxAround) {
  2521. // Distinguish coordinates nearer to the left or right side of the box
  2522. var atLeft = x - boxAround.left < boxAround.right - x, atStart = atLeft == ltr;
  2523. ch = chAround + (atStart ? 0 : 1);
  2524. sticky = atStart ? "after" : "before";
  2525. baseX = atLeft ? boxAround.left : boxAround.right;
  2526. } else {
  2527. // (Adjust for extended bound, if necessary.)
  2528. if (!ltr && (ch == end || ch == begin)) { ch++; }
  2529. // To determine which side to associate with, get the box to the
  2530. // left of the character and compare it's vertical position to the
  2531. // coordinates
  2532. sticky = ch == 0 ? "after" : ch == lineObj.text.length ? "before" :
  2533. (measureCharPrepared(cm, preparedMeasure, ch - (ltr ? 1 : 0)).bottom + widgetHeight$$1 <= y) == ltr ?
  2534. "after" : "before";
  2535. // Now get accurate coordinates for this place, in order to get a
  2536. // base X position
  2537. var coords = cursorCoords(cm, Pos(lineNo$$1, ch, sticky), "line", lineObj, preparedMeasure);
  2538. baseX = coords.left;
  2539. outside = y < coords.top ? -1 : y >= coords.bottom ? 1 : 0;
  2540. }
  2541. ch = skipExtendingChars(lineObj.text, ch, 1);
  2542. return PosWithInfo(lineNo$$1, ch, sticky, outside, x - baseX)
  2543. }
  2544. function coordsBidiPart(cm, lineObj, lineNo$$1, preparedMeasure, order, x, y) {
  2545. // Bidi parts are sorted left-to-right, and in a non-line-wrapping
  2546. // situation, we can take this ordering to correspond to the visual
  2547. // ordering. This finds the first part whose end is after the given
  2548. // coordinates.
  2549. var index = findFirst(function (i) {
  2550. var part = order[i], ltr = part.level != 1;
  2551. return boxIsAfter(cursorCoords(cm, Pos(lineNo$$1, ltr ? part.to : part.from, ltr ? "before" : "after"),
  2552. "line", lineObj, preparedMeasure), x, y, true)
  2553. }, 0, order.length - 1);
  2554. var part = order[index];
  2555. // If this isn't the first part, the part's start is also after
  2556. // the coordinates, and the coordinates aren't on the same line as
  2557. // that start, move one part back.
  2558. if (index > 0) {
  2559. var ltr = part.level != 1;
  2560. var start = cursorCoords(cm, Pos(lineNo$$1, ltr ? part.from : part.to, ltr ? "after" : "before"),
  2561. "line", lineObj, preparedMeasure);
  2562. if (boxIsAfter(start, x, y, true) && start.top > y)
  2563. { part = order[index - 1]; }
  2564. }
  2565. return part
  2566. }
  2567. function coordsBidiPartWrapped(cm, lineObj, _lineNo, preparedMeasure, order, x, y) {
  2568. // In a wrapped line, rtl text on wrapping boundaries can do things
  2569. // that don't correspond to the ordering in our `order` array at
  2570. // all, so a binary search doesn't work, and we want to return a
  2571. // part that only spans one line so that the binary search in
  2572. // coordsCharInner is safe. As such, we first find the extent of the
  2573. // wrapped line, and then do a flat search in which we discard any
  2574. // spans that aren't on the line.
  2575. var ref = wrappedLineExtent(cm, lineObj, preparedMeasure, y);
  2576. var begin = ref.begin;
  2577. var end = ref.end;
  2578. if (/\s/.test(lineObj.text.charAt(end - 1))) { end--; }
  2579. var part = null, closestDist = null;
  2580. for (var i = 0; i < order.length; i++) {
  2581. var p = order[i];
  2582. if (p.from >= end || p.to <= begin) { continue }
  2583. var ltr = p.level != 1;
  2584. var endX = measureCharPrepared(cm, preparedMeasure, ltr ? Math.min(end, p.to) - 1 : Math.max(begin, p.from)).right;
  2585. // Weigh against spans ending before this, so that they are only
  2586. // picked if nothing ends after
  2587. var dist = endX < x ? x - endX + 1e9 : endX - x;
  2588. if (!part || closestDist > dist) {
  2589. part = p;
  2590. closestDist = dist;
  2591. }
  2592. }
  2593. if (!part) { part = order[order.length - 1]; }
  2594. // Clip the part to the wrapped line.
  2595. if (part.from < begin) { part = {from: begin, to: part.to, level: part.level}; }
  2596. if (part.to > end) { part = {from: part.from, to: end, level: part.level}; }
  2597. return part
  2598. }
  2599. var measureText;
  2600. // Compute the default text height.
  2601. function textHeight(display) {
  2602. if (display.cachedTextHeight != null) { return display.cachedTextHeight }
  2603. if (measureText == null) {
  2604. measureText = elt("pre", null, "CodeMirror-line-like");
  2605. // Measure a bunch of lines, for browsers that compute
  2606. // fractional heights.
  2607. for (var i = 0; i < 49; ++i) {
  2608. measureText.appendChild(document.createTextNode("x"));
  2609. measureText.appendChild(elt("br"));
  2610. }
  2611. measureText.appendChild(document.createTextNode("x"));
  2612. }
  2613. removeChildrenAndAdd(display.measure, measureText);
  2614. var height = measureText.offsetHeight / 50;
  2615. if (height > 3) { display.cachedTextHeight = height; }
  2616. removeChildren(display.measure);
  2617. return height || 1
  2618. }
  2619. // Compute the default character width.
  2620. function charWidth(display) {
  2621. if (display.cachedCharWidth != null) { return display.cachedCharWidth }
  2622. var anchor = elt("span", "xxxxxxxxxx");
  2623. var pre = elt("pre", [anchor], "CodeMirror-line-like");
  2624. removeChildrenAndAdd(display.measure, pre);
  2625. var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10;
  2626. if (width > 2) { display.cachedCharWidth = width; }
  2627. return width || 10
  2628. }
  2629. // Do a bulk-read of the DOM positions and sizes needed to draw the
  2630. // view, so that we don't interleave reading and writing to the DOM.
  2631. function getDimensions(cm) {
  2632. var d = cm.display, left = {}, width = {};
  2633. var gutterLeft = d.gutters.clientLeft;
  2634. for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) {
  2635. var id = cm.display.gutterSpecs[i].className;
  2636. left[id] = n.offsetLeft + n.clientLeft + gutterLeft;
  2637. width[id] = n.clientWidth;
  2638. }
  2639. return {fixedPos: compensateForHScroll(d),
  2640. gutterTotalWidth: d.gutters.offsetWidth,
  2641. gutterLeft: left,
  2642. gutterWidth: width,
  2643. wrapperWidth: d.wrapper.clientWidth}
  2644. }
  2645. // Computes display.scroller.scrollLeft + display.gutters.offsetWidth,
  2646. // but using getBoundingClientRect to get a sub-pixel-accurate
  2647. // result.
  2648. function compensateForHScroll(display) {
  2649. return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left
  2650. }
  2651. // Returns a function that estimates the height of a line, to use as
  2652. // first approximation until the line becomes visible (and is thus
  2653. // properly measurable).
  2654. function estimateHeight(cm) {
  2655. var th = textHeight(cm.display), wrapping = cm.options.lineWrapping;
  2656. var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3);
  2657. return function (line) {
  2658. if (lineIsHidden(cm.doc, line)) { return 0 }
  2659. var widgetsHeight = 0;
  2660. if (line.widgets) { for (var i = 0; i < line.widgets.length; i++) {
  2661. if (line.widgets[i].height) { widgetsHeight += line.widgets[i].height; }
  2662. } }
  2663. if (wrapping)
  2664. { return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th }
  2665. else
  2666. { return widgetsHeight + th }
  2667. }
  2668. }
  2669. function estimateLineHeights(cm) {
  2670. var doc = cm.doc, est = estimateHeight(cm);
  2671. doc.iter(function (line) {
  2672. var estHeight = est(line);
  2673. if (estHeight != line.height) { updateLineHeight(line, estHeight); }
  2674. });
  2675. }
  2676. // Given a mouse event, find the corresponding position. If liberal
  2677. // is false, it checks whether a gutter or scrollbar was clicked,
  2678. // and returns null if it was. forRect is used by rectangular
  2679. // selections, and tries to estimate a character position even for
  2680. // coordinates beyond the right of the text.
  2681. function posFromMouse(cm, e, liberal, forRect) {
  2682. var display = cm.display;
  2683. if (!liberal && e_target(e).getAttribute("cm-not-content") == "true") { return null }
  2684. var x, y, space = display.lineSpace.getBoundingClientRect();
  2685. // Fails unpredictably on IE[67] when mouse is dragged around quickly.
  2686. try { x = e.clientX - space.left; y = e.clientY - space.top; }
  2687. catch (e) { return null }
  2688. var coords = coordsChar(cm, x, y), line;
  2689. if (forRect && coords.xRel == 1 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) {
  2690. var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length;
  2691. coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff));
  2692. }
  2693. return coords
  2694. }
  2695. // Find the view element corresponding to a given line. Return null
  2696. // when the line isn't visible.
  2697. function findViewIndex(cm, n) {
  2698. if (n >= cm.display.viewTo) { return null }
  2699. n -= cm.display.viewFrom;
  2700. if (n < 0) { return null }
  2701. var view = cm.display.view;
  2702. for (var i = 0; i < view.length; i++) {
  2703. n -= view[i].size;
  2704. if (n < 0) { return i }
  2705. }
  2706. }
  2707. // Updates the display.view data structure for a given change to the
  2708. // document. From and to are in pre-change coordinates. Lendiff is
  2709. // the amount of lines added or subtracted by the change. This is
  2710. // used for changes that span multiple lines, or change the way
  2711. // lines are divided into visual lines. regLineChange (below)
  2712. // registers single-line changes.
  2713. function regChange(cm, from, to, lendiff) {
  2714. if (from == null) { from = cm.doc.first; }
  2715. if (to == null) { to = cm.doc.first + cm.doc.size; }
  2716. if (!lendiff) { lendiff = 0; }
  2717. var display = cm.display;
  2718. if (lendiff && to < display.viewTo &&
  2719. (display.updateLineNumbers == null || display.updateLineNumbers > from))
  2720. { display.updateLineNumbers = from; }
  2721. cm.curOp.viewChanged = true;
  2722. if (from >= display.viewTo) { // Change after
  2723. if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo)
  2724. { resetView(cm); }
  2725. } else if (to <= display.viewFrom) { // Change before
  2726. if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) {
  2727. resetView(cm);
  2728. } else {
  2729. display.viewFrom += lendiff;
  2730. display.viewTo += lendiff;
  2731. }
  2732. } else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap
  2733. resetView(cm);
  2734. } else if (from <= display.viewFrom) { // Top overlap
  2735. var cut = viewCuttingPoint(cm, to, to + lendiff, 1);
  2736. if (cut) {
  2737. display.view = display.view.slice(cut.index);
  2738. display.viewFrom = cut.lineN;
  2739. display.viewTo += lendiff;
  2740. } else {
  2741. resetView(cm);
  2742. }
  2743. } else if (to >= display.viewTo) { // Bottom overlap
  2744. var cut$1 = viewCuttingPoint(cm, from, from, -1);
  2745. if (cut$1) {
  2746. display.view = display.view.slice(0, cut$1.index);
  2747. display.viewTo = cut$1.lineN;
  2748. } else {
  2749. resetView(cm);
  2750. }
  2751. } else { // Gap in the middle
  2752. var cutTop = viewCuttingPoint(cm, from, from, -1);
  2753. var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1);
  2754. if (cutTop && cutBot) {
  2755. display.view = display.view.slice(0, cutTop.index)
  2756. .concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN))
  2757. .concat(display.view.slice(cutBot.index));
  2758. display.viewTo += lendiff;
  2759. } else {
  2760. resetView(cm);
  2761. }
  2762. }
  2763. var ext = display.externalMeasured;
  2764. if (ext) {
  2765. if (to < ext.lineN)
  2766. { ext.lineN += lendiff; }
  2767. else if (from < ext.lineN + ext.size)
  2768. { display.externalMeasured = null; }
  2769. }
  2770. }
  2771. // Register a change to a single line. Type must be one of "text",
  2772. // "gutter", "class", "widget"
  2773. function regLineChange(cm, line, type) {
  2774. cm.curOp.viewChanged = true;
  2775. var display = cm.display, ext = cm.display.externalMeasured;
  2776. if (ext && line >= ext.lineN && line < ext.lineN + ext.size)
  2777. { display.externalMeasured = null; }
  2778. if (line < display.viewFrom || line >= display.viewTo) { return }
  2779. var lineView = display.view[findViewIndex(cm, line)];
  2780. if (lineView.node == null) { return }
  2781. var arr = lineView.changes || (lineView.changes = []);
  2782. if (indexOf(arr, type) == -1) { arr.push(type); }
  2783. }
  2784. // Clear the view.
  2785. function resetView(cm) {
  2786. cm.display.viewFrom = cm.display.viewTo = cm.doc.first;
  2787. cm.display.view = [];
  2788. cm.display.viewOffset = 0;
  2789. }
  2790. function viewCuttingPoint(cm, oldN, newN, dir) {
  2791. var index = findViewIndex(cm, oldN), diff, view = cm.display.view;
  2792. if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size)
  2793. { return {index: index, lineN: newN} }
  2794. var n = cm.display.viewFrom;
  2795. for (var i = 0; i < index; i++)
  2796. { n += view[i].size; }
  2797. if (n != oldN) {
  2798. if (dir > 0) {
  2799. if (index == view.length - 1) { return null }
  2800. diff = (n + view[index].size) - oldN;
  2801. index++;
  2802. } else {
  2803. diff = n - oldN;
  2804. }
  2805. oldN += diff; newN += diff;
  2806. }
  2807. while (visualLineNo(cm.doc, newN) != newN) {
  2808. if (index == (dir < 0 ? 0 : view.length - 1)) { return null }
  2809. newN += dir * view[index - (dir < 0 ? 1 : 0)].size;
  2810. index += dir;
  2811. }
  2812. return {index: index, lineN: newN}
  2813. }
  2814. // Force the view to cover a given range, adding empty view element
  2815. // or clipping off existing ones as needed.
  2816. function adjustView(cm, from, to) {
  2817. var display = cm.display, view = display.view;
  2818. if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) {
  2819. display.view = buildViewArray(cm, from, to);
  2820. display.viewFrom = from;
  2821. } else {
  2822. if (display.viewFrom > from)
  2823. { display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view); }
  2824. else if (display.viewFrom < from)
  2825. { display.view = display.view.slice(findViewIndex(cm, from)); }
  2826. display.viewFrom = from;
  2827. if (display.viewTo < to)
  2828. { display.view = display.view.concat(buildViewArray(cm, display.viewTo, to)); }
  2829. else if (display.viewTo > to)
  2830. { display.view = display.view.slice(0, findViewIndex(cm, to)); }
  2831. }
  2832. display.viewTo = to;
  2833. }
  2834. // Count the number of lines in the view whose DOM representation is
  2835. // out of date (or nonexistent).
  2836. function countDirtyView(cm) {
  2837. var view = cm.display.view, dirty = 0;
  2838. for (var i = 0; i < view.length; i++) {
  2839. var lineView = view[i];
  2840. if (!lineView.hidden && (!lineView.node || lineView.changes)) { ++dirty; }
  2841. }
  2842. return dirty
  2843. }
  2844. function updateSelection(cm) {
  2845. cm.display.input.showSelection(cm.display.input.prepareSelection());
  2846. }
  2847. function prepareSelection(cm, primary) {
  2848. if ( primary === void 0 ) primary = true;
  2849. var doc = cm.doc, result = {};
  2850. var curFragment = result.cursors = document.createDocumentFragment();
  2851. var selFragment = result.selection = document.createDocumentFragment();
  2852. for (var i = 0; i < doc.sel.ranges.length; i++) {
  2853. if (!primary && i == doc.sel.primIndex) { continue }
  2854. var range$$1 = doc.sel.ranges[i];
  2855. if (range$$1.from().line >= cm.display.viewTo || range$$1.to().line < cm.display.viewFrom) { continue }
  2856. var collapsed = range$$1.empty();
  2857. if (collapsed || cm.options.showCursorWhenSelecting)
  2858. { drawSelectionCursor(cm, range$$1.head, curFragment); }
  2859. if (!collapsed)
  2860. { drawSelectionRange(cm, range$$1, selFragment); }
  2861. }
  2862. return result
  2863. }
  2864. // Draws a cursor for the given range
  2865. function drawSelectionCursor(cm, head, output) {
  2866. var pos = cursorCoords(cm, head, "div", null, null, !cm.options.singleCursorHeightPerLine);
  2867. var cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor"));
  2868. cursor.style.left = pos.left + "px";
  2869. cursor.style.top = pos.top + "px";
  2870. cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px";
  2871. if (pos.other) {
  2872. // Secondary cursor, shown when on a 'jump' in bi-directional text
  2873. var otherCursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor"));
  2874. otherCursor.style.display = "";
  2875. otherCursor.style.left = pos.other.left + "px";
  2876. otherCursor.style.top = pos.other.top + "px";
  2877. otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px";
  2878. }
  2879. }
  2880. function cmpCoords(a, b) { return a.top - b.top || a.left - b.left }
  2881. // Draws the given range as a highlighted selection
  2882. function drawSelectionRange(cm, range$$1, output) {
  2883. var display = cm.display, doc = cm.doc;
  2884. var fragment = document.createDocumentFragment();
  2885. var padding = paddingH(cm.display), leftSide = padding.left;
  2886. var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right;
  2887. var docLTR = doc.direction == "ltr";
  2888. function add(left, top, width, bottom) {
  2889. if (top < 0) { top = 0; }
  2890. top = Math.round(top);
  2891. bottom = Math.round(bottom);
  2892. fragment.appendChild(elt("div", null, "CodeMirror-selected", ("position: absolute; left: " + left + "px;\n top: " + top + "px; width: " + (width == null ? rightSide - left : width) + "px;\n height: " + (bottom - top) + "px")));
  2893. }
  2894. function drawForLine(line, fromArg, toArg) {
  2895. var lineObj = getLine(doc, line);
  2896. var lineLen = lineObj.text.length;
  2897. var start, end;
  2898. function coords(ch, bias) {
  2899. return charCoords(cm, Pos(line, ch), "div", lineObj, bias)
  2900. }
  2901. function wrapX(pos, dir, side) {
  2902. var extent = wrappedLineExtentChar(cm, lineObj, null, pos);
  2903. var prop = (dir == "ltr") == (side == "after") ? "left" : "right";
  2904. var ch = side == "after" ? extent.begin : extent.end - (/\s/.test(lineObj.text.charAt(extent.end - 1)) ? 2 : 1);
  2905. return coords(ch, prop)[prop]
  2906. }
  2907. var order = getOrder(lineObj, doc.direction);
  2908. iterateBidiSections(order, fromArg || 0, toArg == null ? lineLen : toArg, function (from, to, dir, i) {
  2909. var ltr = dir == "ltr";
  2910. var fromPos = coords(from, ltr ? "left" : "right");
  2911. var toPos = coords(to - 1, ltr ? "right" : "left");
  2912. var openStart = fromArg == null && from == 0, openEnd = toArg == null && to == lineLen;
  2913. var first = i == 0, last = !order || i == order.length - 1;
  2914. if (toPos.top - fromPos.top <= 3) { // Single line
  2915. var openLeft = (docLTR ? openStart : openEnd) && first;
  2916. var openRight = (docLTR ? openEnd : openStart) && last;
  2917. var left = openLeft ? leftSide : (ltr ? fromPos : toPos).left;
  2918. var right = openRight ? rightSide : (ltr ? toPos : fromPos).right;
  2919. add(left, fromPos.top, right - left, fromPos.bottom);
  2920. } else { // Multiple lines
  2921. var topLeft, topRight, botLeft, botRight;
  2922. if (ltr) {
  2923. topLeft = docLTR && openStart && first ? leftSide : fromPos.left;
  2924. topRight = docLTR ? rightSide : wrapX(from, dir, "before");
  2925. botLeft = docLTR ? leftSide : wrapX(to, dir, "after");
  2926. botRight = docLTR && openEnd && last ? rightSide : toPos.right;
  2927. } else {
  2928. topLeft = !docLTR ? leftSide : wrapX(from, dir, "before");
  2929. topRight = !docLTR && openStart && first ? rightSide : fromPos.right;
  2930. botLeft = !docLTR && openEnd && last ? leftSide : toPos.left;
  2931. botRight = !docLTR ? rightSide : wrapX(to, dir, "after");
  2932. }
  2933. add(topLeft, fromPos.top, topRight - topLeft, fromPos.bottom);
  2934. if (fromPos.bottom < toPos.top) { add(leftSide, fromPos.bottom, null, toPos.top); }
  2935. add(botLeft, toPos.top, botRight - botLeft, toPos.bottom);
  2936. }
  2937. if (!start || cmpCoords(fromPos, start) < 0) { start = fromPos; }
  2938. if (cmpCoords(toPos, start) < 0) { start = toPos; }
  2939. if (!end || cmpCoords(fromPos, end) < 0) { end = fromPos; }
  2940. if (cmpCoords(toPos, end) < 0) { end = toPos; }
  2941. });
  2942. return {start: start, end: end}
  2943. }
  2944. var sFrom = range$$1.from(), sTo = range$$1.to();
  2945. if (sFrom.line == sTo.line) {
  2946. drawForLine(sFrom.line, sFrom.ch, sTo.ch);
  2947. } else {
  2948. var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line);
  2949. var singleVLine = visualLine(fromLine) == visualLine(toLine);
  2950. var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end;
  2951. var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start;
  2952. if (singleVLine) {
  2953. if (leftEnd.top < rightStart.top - 2) {
  2954. add(leftEnd.right, leftEnd.top, null, leftEnd.bottom);
  2955. add(leftSide, rightStart.top, rightStart.left, rightStart.bottom);
  2956. } else {
  2957. add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom);
  2958. }
  2959. }
  2960. if (leftEnd.bottom < rightStart.top)
  2961. { add(leftSide, leftEnd.bottom, null, rightStart.top); }
  2962. }
  2963. output.appendChild(fragment);
  2964. }
  2965. // Cursor-blinking
  2966. function restartBlink(cm) {
  2967. if (!cm.state.focused) { return }
  2968. var display = cm.display;
  2969. clearInterval(display.blinker);
  2970. var on = true;
  2971. display.cursorDiv.style.visibility = "";
  2972. if (cm.options.cursorBlinkRate > 0)
  2973. { display.blinker = setInterval(function () { return display.cursorDiv.style.visibility = (on = !on) ? "" : "hidden"; },
  2974. cm.options.cursorBlinkRate); }
  2975. else if (cm.options.cursorBlinkRate < 0)
  2976. { display.cursorDiv.style.visibility = "hidden"; }
  2977. }
  2978. function ensureFocus(cm) {
  2979. if (!cm.state.focused) { cm.display.input.focus(); onFocus(cm); }
  2980. }
  2981. function delayBlurEvent(cm) {
  2982. cm.state.delayingBlurEvent = true;
  2983. setTimeout(function () { if (cm.state.delayingBlurEvent) {
  2984. cm.state.delayingBlurEvent = false;
  2985. onBlur(cm);
  2986. } }, 100);
  2987. }
  2988. function onFocus(cm, e) {
  2989. if (cm.state.delayingBlurEvent) { cm.state.delayingBlurEvent = false; }
  2990. if (cm.options.readOnly == "nocursor") { return }
  2991. if (!cm.state.focused) {
  2992. signal(cm, "focus", cm, e);
  2993. cm.state.focused = true;
  2994. addClass(cm.display.wrapper, "CodeMirror-focused");
  2995. // This test prevents this from firing when a context
  2996. // menu is closed (since the input reset would kill the
  2997. // select-all detection hack)
  2998. if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) {
  2999. cm.display.input.reset();
  3000. if (webkit) { setTimeout(function () { return cm.display.input.reset(true); }, 20); } // Issue #1730
  3001. }
  3002. cm.display.input.receivedFocus();
  3003. }
  3004. restartBlink(cm);
  3005. }
  3006. function onBlur(cm, e) {
  3007. if (cm.state.delayingBlurEvent) { return }
  3008. if (cm.state.focused) {
  3009. signal(cm, "blur", cm, e);
  3010. cm.state.focused = false;
  3011. rmClass(cm.display.wrapper, "CodeMirror-focused");
  3012. }
  3013. clearInterval(cm.display.blinker);
  3014. setTimeout(function () { if (!cm.state.focused) { cm.display.shift = false; } }, 150);
  3015. }
  3016. // Read the actual heights of the rendered lines, and update their
  3017. // stored heights to match.
  3018. function updateHeightsInViewport(cm) {
  3019. var display = cm.display;
  3020. var prevBottom = display.lineDiv.offsetTop;
  3021. for (var i = 0; i < display.view.length; i++) {
  3022. var cur = display.view[i], wrapping = cm.options.lineWrapping;
  3023. var height = (void 0), width = 0;
  3024. if (cur.hidden) { continue }
  3025. if (ie && ie_version < 8) {
  3026. var bot = cur.node.offsetTop + cur.node.offsetHeight;
  3027. height = bot - prevBottom;
  3028. prevBottom = bot;
  3029. } else {
  3030. var box = cur.node.getBoundingClientRect();
  3031. height = box.bottom - box.top;
  3032. // Check that lines don't extend past the right of the current
  3033. // editor width
  3034. if (!wrapping && cur.text.firstChild)
  3035. { width = cur.text.firstChild.getBoundingClientRect().right - box.left - 1; }
  3036. }
  3037. var diff = cur.line.height - height;
  3038. if (diff > .005 || diff < -.005) {
  3039. updateLineHeight(cur.line, height);
  3040. updateWidgetHeight(cur.line);
  3041. if (cur.rest) { for (var j = 0; j < cur.rest.length; j++)
  3042. { updateWidgetHeight(cur.rest[j]); } }
  3043. }
  3044. if (width > cm.display.sizerWidth) {
  3045. var chWidth = Math.ceil(width / charWidth(cm.display));
  3046. if (chWidth > cm.display.maxLineLength) {
  3047. cm.display.maxLineLength = chWidth;
  3048. cm.display.maxLine = cur.line;
  3049. cm.display.maxLineChanged = true;
  3050. }
  3051. }
  3052. }
  3053. }
  3054. // Read and store the height of line widgets associated with the
  3055. // given line.
  3056. function updateWidgetHeight(line) {
  3057. if (line.widgets) { for (var i = 0; i < line.widgets.length; ++i) {
  3058. var w = line.widgets[i], parent = w.node.parentNode;
  3059. if (parent) { w.height = parent.offsetHeight; }
  3060. } }
  3061. }
  3062. // Compute the lines that are visible in a given viewport (defaults
  3063. // the the current scroll position). viewport may contain top,
  3064. // height, and ensure (see op.scrollToPos) properties.
  3065. function visibleLines(display, doc, viewport) {
  3066. var top = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop;
  3067. top = Math.floor(top - paddingTop(display));
  3068. var bottom = viewport && viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight;
  3069. var from = lineAtHeight(doc, top), to = lineAtHeight(doc, bottom);
  3070. // Ensure is a {from: {line, ch}, to: {line, ch}} object, and
  3071. // forces those lines into the viewport (if possible).
  3072. if (viewport && viewport.ensure) {
  3073. var ensureFrom = viewport.ensure.from.line, ensureTo = viewport.ensure.to.line;
  3074. if (ensureFrom < from) {
  3075. from = ensureFrom;
  3076. to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight);
  3077. } else if (Math.min(ensureTo, doc.lastLine()) >= to) {
  3078. from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight);
  3079. to = ensureTo;
  3080. }
  3081. }
  3082. return {from: from, to: Math.max(to, from + 1)}
  3083. }
  3084. // SCROLLING THINGS INTO VIEW
  3085. // If an editor sits on the top or bottom of the window, partially
  3086. // scrolled out of view, this ensures that the cursor is visible.
  3087. function maybeScrollWindow(cm, rect) {
  3088. if (signalDOMEvent(cm, "scrollCursorIntoView")) { return }
  3089. var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null;
  3090. if (rect.top + box.top < 0) { doScroll = true; }
  3091. else if (rect.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) { doScroll = false; }
  3092. if (doScroll != null && !phantom) {
  3093. var scrollNode = elt("div", "\u200b", null, ("position: absolute;\n top: " + (rect.top - display.viewOffset - paddingTop(cm.display)) + "px;\n height: " + (rect.bottom - rect.top + scrollGap(cm) + display.barHeight) + "px;\n left: " + (rect.left) + "px; width: " + (Math.max(2, rect.right - rect.left)) + "px;"));
  3094. cm.display.lineSpace.appendChild(scrollNode);
  3095. scrollNode.scrollIntoView(doScroll);
  3096. cm.display.lineSpace.removeChild(scrollNode);
  3097. }
  3098. }
  3099. // Scroll a given position into view (immediately), verifying that
  3100. // it actually became visible (as line heights are accurately
  3101. // measured, the position of something may 'drift' during drawing).
  3102. function scrollPosIntoView(cm, pos, end, margin) {
  3103. if (margin == null) { margin = 0; }
  3104. var rect;
  3105. if (!cm.options.lineWrapping && pos == end) {
  3106. // Set pos and end to the cursor positions around the character pos sticks to
  3107. // If pos.sticky == "before", that is around pos.ch - 1, otherwise around pos.ch
  3108. // If pos == Pos(_, 0, "before"), pos and end are unchanged
  3109. pos = pos.ch ? Pos(pos.line, pos.sticky == "before" ? pos.ch - 1 : pos.ch, "after") : pos;
  3110. end = pos.sticky == "before" ? Pos(pos.line, pos.ch + 1, "before") : pos;
  3111. }
  3112. for (var limit = 0; limit < 5; limit++) {
  3113. var changed = false;
  3114. var coords = cursorCoords(cm, pos);
  3115. var endCoords = !end || end == pos ? coords : cursorCoords(cm, end);
  3116. rect = {left: Math.min(coords.left, endCoords.left),
  3117. top: Math.min(coords.top, endCoords.top) - margin,
  3118. right: Math.max(coords.left, endCoords.left),
  3119. bottom: Math.max(coords.bottom, endCoords.bottom) + margin};
  3120. var scrollPos = calculateScrollPos(cm, rect);
  3121. var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft;
  3122. if (scrollPos.scrollTop != null) {
  3123. updateScrollTop(cm, scrollPos.scrollTop);
  3124. if (Math.abs(cm.doc.scrollTop - startTop) > 1) { changed = true; }
  3125. }
  3126. if (scrollPos.scrollLeft != null) {
  3127. setScrollLeft(cm, scrollPos.scrollLeft);
  3128. if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) { changed = true; }
  3129. }
  3130. if (!changed) { break }
  3131. }
  3132. return rect
  3133. }
  3134. // Scroll a given set of coordinates into view (immediately).
  3135. function scrollIntoView(cm, rect) {
  3136. var scrollPos = calculateScrollPos(cm, rect);
  3137. if (scrollPos.scrollTop != null) { updateScrollTop(cm, scrollPos.scrollTop); }
  3138. if (scrollPos.scrollLeft != null) { setScrollLeft(cm, scrollPos.scrollLeft); }
  3139. }
  3140. // Calculate a new scroll position needed to scroll the given
  3141. // rectangle into view. Returns an object with scrollTop and
  3142. // scrollLeft properties. When these are undefined, the
  3143. // vertical/horizontal position does not need to be adjusted.
  3144. function calculateScrollPos(cm, rect) {
  3145. var display = cm.display, snapMargin = textHeight(cm.display);
  3146. if (rect.top < 0) { rect.top = 0; }
  3147. var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop;
  3148. var screen = displayHeight(cm), result = {};
  3149. if (rect.bottom - rect.top > screen) { rect.bottom = rect.top + screen; }
  3150. var docBottom = cm.doc.height + paddingVert(display);
  3151. var atTop = rect.top < snapMargin, atBottom = rect.bottom > docBottom - snapMargin;
  3152. if (rect.top < screentop) {
  3153. result.scrollTop = atTop ? 0 : rect.top;
  3154. } else if (rect.bottom > screentop + screen) {
  3155. var newTop = Math.min(rect.top, (atBottom ? docBottom : rect.bottom) - screen);
  3156. if (newTop != screentop) { result.scrollTop = newTop; }
  3157. }
  3158. var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft;
  3159. var screenw = displayWidth(cm) - (cm.options.fixedGutter ? display.gutters.offsetWidth : 0);
  3160. var tooWide = rect.right - rect.left > screenw;
  3161. if (tooWide) { rect.right = rect.left + screenw; }
  3162. if (rect.left < 10)
  3163. { result.scrollLeft = 0; }
  3164. else if (rect.left < screenleft)
  3165. { result.scrollLeft = Math.max(0, rect.left - (tooWide ? 0 : 10)); }
  3166. else if (rect.right > screenw + screenleft - 3)
  3167. { result.scrollLeft = rect.right + (tooWide ? 0 : 10) - screenw; }
  3168. return result
  3169. }
  3170. // Store a relative adjustment to the scroll position in the current
  3171. // operation (to be applied when the operation finishes).
  3172. function addToScrollTop(cm, top) {
  3173. if (top == null) { return }
  3174. resolveScrollToPos(cm);
  3175. cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top;
  3176. }
  3177. // Make sure that at the end of the operation the current cursor is
  3178. // shown.
  3179. function ensureCursorVisible(cm) {
  3180. resolveScrollToPos(cm);
  3181. var cur = cm.getCursor();
  3182. cm.curOp.scrollToPos = {from: cur, to: cur, margin: cm.options.cursorScrollMargin};
  3183. }
  3184. function scrollToCoords(cm, x, y) {
  3185. if (x != null || y != null) { resolveScrollToPos(cm); }
  3186. if (x != null) { cm.curOp.scrollLeft = x; }
  3187. if (y != null) { cm.curOp.scrollTop = y; }
  3188. }
  3189. function scrollToRange(cm, range$$1) {
  3190. resolveScrollToPos(cm);
  3191. cm.curOp.scrollToPos = range$$1;
  3192. }
  3193. // When an operation has its scrollToPos property set, and another
  3194. // scroll action is applied before the end of the operation, this
  3195. // 'simulates' scrolling that position into view in a cheap way, so
  3196. // that the effect of intermediate scroll commands is not ignored.
  3197. function resolveScrollToPos(cm) {
  3198. var range$$1 = cm.curOp.scrollToPos;
  3199. if (range$$1) {
  3200. cm.curOp.scrollToPos = null;
  3201. var from = estimateCoords(cm, range$$1.from), to = estimateCoords(cm, range$$1.to);
  3202. scrollToCoordsRange(cm, from, to, range$$1.margin);
  3203. }
  3204. }
  3205. function scrollToCoordsRange(cm, from, to, margin) {
  3206. var sPos = calculateScrollPos(cm, {
  3207. left: Math.min(from.left, to.left),
  3208. top: Math.min(from.top, to.top) - margin,
  3209. right: Math.max(from.right, to.right),
  3210. bottom: Math.max(from.bottom, to.bottom) + margin
  3211. });
  3212. scrollToCoords(cm, sPos.scrollLeft, sPos.scrollTop);
  3213. }
  3214. // Sync the scrollable area and scrollbars, ensure the viewport
  3215. // covers the visible area.
  3216. function updateScrollTop(cm, val) {
  3217. if (Math.abs(cm.doc.scrollTop - val) < 2) { return }
  3218. if (!gecko) { updateDisplaySimple(cm, {top: val}); }
  3219. setScrollTop(cm, val, true);
  3220. if (gecko) { updateDisplaySimple(cm); }
  3221. startWorker(cm, 100);
  3222. }
  3223. function setScrollTop(cm, val, forceScroll) {
  3224. val = Math.min(cm.display.scroller.scrollHeight - cm.display.scroller.clientHeight, val);
  3225. if (cm.display.scroller.scrollTop == val && !forceScroll) { return }
  3226. cm.doc.scrollTop = val;
  3227. cm.display.scrollbars.setScrollTop(val);
  3228. if (cm.display.scroller.scrollTop != val) { cm.display.scroller.scrollTop = val; }
  3229. }
  3230. // Sync scroller and scrollbar, ensure the gutter elements are
  3231. // aligned.
  3232. function setScrollLeft(cm, val, isScroller, forceScroll) {
  3233. val = Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth);
  3234. if ((isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) && !forceScroll) { return }
  3235. cm.doc.scrollLeft = val;
  3236. alignHorizontally(cm);
  3237. if (cm.display.scroller.scrollLeft != val) { cm.display.scroller.scrollLeft = val; }
  3238. cm.display.scrollbars.setScrollLeft(val);
  3239. }
  3240. // SCROLLBARS
  3241. // Prepare DOM reads needed to update the scrollbars. Done in one
  3242. // shot to minimize update/measure roundtrips.
  3243. function measureForScrollbars(cm) {
  3244. var d = cm.display, gutterW = d.gutters.offsetWidth;
  3245. var docH = Math.round(cm.doc.height + paddingVert(cm.display));
  3246. return {
  3247. clientHeight: d.scroller.clientHeight,
  3248. viewHeight: d.wrapper.clientHeight,
  3249. scrollWidth: d.scroller.scrollWidth, clientWidth: d.scroller.clientWidth,
  3250. viewWidth: d.wrapper.clientWidth,
  3251. barLeft: cm.options.fixedGutter ? gutterW : 0,
  3252. docHeight: docH,
  3253. scrollHeight: docH + scrollGap(cm) + d.barHeight,
  3254. nativeBarWidth: d.nativeBarWidth,
  3255. gutterWidth: gutterW
  3256. }
  3257. }
  3258. var NativeScrollbars = function(place, scroll, cm) {
  3259. this.cm = cm;
  3260. var vert = this.vert = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar");
  3261. var horiz = this.horiz = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar");
  3262. vert.tabIndex = horiz.tabIndex = -1;
  3263. place(vert); place(horiz);
  3264. on(vert, "scroll", function () {
  3265. if (vert.clientHeight) { scroll(vert.scrollTop, "vertical"); }
  3266. });
  3267. on(horiz, "scroll", function () {
  3268. if (horiz.clientWidth) { scroll(horiz.scrollLeft, "horizontal"); }
  3269. });
  3270. this.checkedZeroWidth = false;
  3271. // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8).
  3272. if (ie && ie_version < 8) { this.horiz.style.minHeight = this.vert.style.minWidth = "18px"; }
  3273. };
  3274. NativeScrollbars.prototype.update = function (measure) {
  3275. var needsH = measure.scrollWidth > measure.clientWidth + 1;
  3276. var needsV = measure.scrollHeight > measure.clientHeight + 1;
  3277. var sWidth = measure.nativeBarWidth;
  3278. if (needsV) {
  3279. this.vert.style.display = "block";
  3280. this.vert.style.bottom = needsH ? sWidth + "px" : "0";
  3281. var totalHeight = measure.viewHeight - (needsH ? sWidth : 0);
  3282. // A bug in IE8 can cause this value to be negative, so guard it.
  3283. this.vert.firstChild.style.height =
  3284. Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + "px";
  3285. } else {
  3286. this.vert.style.display = "";
  3287. this.vert.firstChild.style.height = "0";
  3288. }
  3289. if (needsH) {
  3290. this.horiz.style.display = "block";
  3291. this.horiz.style.right = needsV ? sWidth + "px" : "0";
  3292. this.horiz.style.left = measure.barLeft + "px";
  3293. var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0);
  3294. this.horiz.firstChild.style.width =
  3295. Math.max(0, measure.scrollWidth - measure.clientWidth + totalWidth) + "px";
  3296. } else {
  3297. this.horiz.style.display = "";
  3298. this.horiz.firstChild.style.width = "0";
  3299. }
  3300. if (!this.checkedZeroWidth && measure.clientHeight > 0) {
  3301. if (sWidth == 0) { this.zeroWidthHack(); }
  3302. this.checkedZeroWidth = true;
  3303. }
  3304. return {right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0}
  3305. };
  3306. NativeScrollbars.prototype.setScrollLeft = function (pos) {
  3307. if (this.horiz.scrollLeft != pos) { this.horiz.scrollLeft = pos; }
  3308. if (this.disableHoriz) { this.enableZeroWidthBar(this.horiz, this.disableHoriz, "horiz"); }
  3309. };
  3310. NativeScrollbars.prototype.setScrollTop = function (pos) {
  3311. if (this.vert.scrollTop != pos) { this.vert.scrollTop = pos; }
  3312. if (this.disableVert) { this.enableZeroWidthBar(this.vert, this.disableVert, "vert"); }
  3313. };
  3314. NativeScrollbars.prototype.zeroWidthHack = function () {
  3315. var w = mac && !mac_geMountainLion ? "12px" : "18px";
  3316. this.horiz.style.height = this.vert.style.width = w;
  3317. this.horiz.style.pointerEvents = this.vert.style.pointerEvents = "none";
  3318. this.disableHoriz = new Delayed;
  3319. this.disableVert = new Delayed;
  3320. };
  3321. NativeScrollbars.prototype.enableZeroWidthBar = function (bar, delay, type) {
  3322. bar.style.pointerEvents = "auto";
  3323. function maybeDisable() {
  3324. // To find out whether the scrollbar is still visible, we
  3325. // check whether the element under the pixel in the bottom
  3326. // right corner of the scrollbar box is the scrollbar box
  3327. // itself (when the bar is still visible) or its filler child
  3328. // (when the bar is hidden). If it is still visible, we keep
  3329. // it enabled, if it's hidden, we disable pointer events.
  3330. var box = bar.getBoundingClientRect();
  3331. var elt$$1 = type == "vert" ? document.elementFromPoint(box.right - 1, (box.top + box.bottom) / 2)
  3332. : document.elementFromPoint((box.right + box.left) / 2, box.bottom - 1);
  3333. if (elt$$1 != bar) { bar.style.pointerEvents = "none"; }
  3334. else { delay.set(1000, maybeDisable); }
  3335. }
  3336. delay.set(1000, maybeDisable);
  3337. };
  3338. NativeScrollbars.prototype.clear = function () {
  3339. var parent = this.horiz.parentNode;
  3340. parent.removeChild(this.horiz);
  3341. parent.removeChild(this.vert);
  3342. };
  3343. var NullScrollbars = function () {};
  3344. NullScrollbars.prototype.update = function () { return {bottom: 0, right: 0} };
  3345. NullScrollbars.prototype.setScrollLeft = function () {};
  3346. NullScrollbars.prototype.setScrollTop = function () {};
  3347. NullScrollbars.prototype.clear = function () {};
  3348. function updateScrollbars(cm, measure) {
  3349. if (!measure) { measure = measureForScrollbars(cm); }
  3350. var startWidth = cm.display.barWidth, startHeight = cm.display.barHeight;
  3351. updateScrollbarsInner(cm, measure);
  3352. for (var i = 0; i < 4 && startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i++) {
  3353. if (startWidth != cm.display.barWidth && cm.options.lineWrapping)
  3354. { updateHeightsInViewport(cm); }
  3355. updateScrollbarsInner(cm, measureForScrollbars(cm));
  3356. startWidth = cm.display.barWidth; startHeight = cm.display.barHeight;
  3357. }
  3358. }
  3359. // Re-synchronize the fake scrollbars with the actual size of the
  3360. // content.
  3361. function updateScrollbarsInner(cm, measure) {
  3362. var d = cm.display;
  3363. var sizes = d.scrollbars.update(measure);
  3364. d.sizer.style.paddingRight = (d.barWidth = sizes.right) + "px";
  3365. d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + "px";
  3366. d.heightForcer.style.borderBottom = sizes.bottom + "px solid transparent";
  3367. if (sizes.right && sizes.bottom) {
  3368. d.scrollbarFiller.style.display = "block";
  3369. d.scrollbarFiller.style.height = sizes.bottom + "px";
  3370. d.scrollbarFiller.style.width = sizes.right + "px";
  3371. } else { d.scrollbarFiller.style.display = ""; }
  3372. if (sizes.bottom && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) {
  3373. d.gutterFiller.style.display = "block";
  3374. d.gutterFiller.style.height = sizes.bottom + "px";
  3375. d.gutterFiller.style.width = measure.gutterWidth + "px";
  3376. } else { d.gutterFiller.style.display = ""; }
  3377. }
  3378. var scrollbarModel = {"native": NativeScrollbars, "null": NullScrollbars};
  3379. function initScrollbars(cm) {
  3380. if (cm.display.scrollbars) {
  3381. cm.display.scrollbars.clear();
  3382. if (cm.display.scrollbars.addClass)
  3383. { rmClass(cm.display.wrapper, cm.display.scrollbars.addClass); }
  3384. }
  3385. cm.display.scrollbars = new scrollbarModel[cm.options.scrollbarStyle](function (node) {
  3386. cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller);
  3387. // Prevent clicks in the scrollbars from killing focus
  3388. on(node, "mousedown", function () {
  3389. if (cm.state.focused) { setTimeout(function () { return cm.display.input.focus(); }, 0); }
  3390. });
  3391. node.setAttribute("cm-not-content", "true");
  3392. }, function (pos, axis) {
  3393. if (axis == "horizontal") { setScrollLeft(cm, pos); }
  3394. else { updateScrollTop(cm, pos); }
  3395. }, cm);
  3396. if (cm.display.scrollbars.addClass)
  3397. { addClass(cm.display.wrapper, cm.display.scrollbars.addClass); }
  3398. }
  3399. // Operations are used to wrap a series of changes to the editor
  3400. // state in such a way that each change won't have to update the
  3401. // cursor and display (which would be awkward, slow, and
  3402. // error-prone). Instead, display updates are batched and then all
  3403. // combined and executed at once.
  3404. var nextOpId = 0;
  3405. // Start a new operation.
  3406. function startOperation(cm) {
  3407. cm.curOp = {
  3408. cm: cm,
  3409. viewChanged: false, // Flag that indicates that lines might need to be redrawn
  3410. startHeight: cm.doc.height, // Used to detect need to update scrollbar
  3411. forceUpdate: false, // Used to force a redraw
  3412. updateInput: 0, // Whether to reset the input textarea
  3413. typing: false, // Whether this reset should be careful to leave existing text (for compositing)
  3414. changeObjs: null, // Accumulated changes, for firing change events
  3415. cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on
  3416. cursorActivityCalled: 0, // Tracks which cursorActivity handlers have been called already
  3417. selectionChanged: false, // Whether the selection needs to be redrawn
  3418. updateMaxLine: false, // Set when the widest line needs to be determined anew
  3419. scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet
  3420. scrollToPos: null, // Used to scroll to a specific position
  3421. focus: false,
  3422. id: ++nextOpId // Unique ID
  3423. };
  3424. pushOperation(cm.curOp);
  3425. }
  3426. // Finish an operation, updating the display and signalling delayed events
  3427. function endOperation(cm) {
  3428. var op = cm.curOp;
  3429. if (op) { finishOperation(op, function (group) {
  3430. for (var i = 0; i < group.ops.length; i++)
  3431. { group.ops[i].cm.curOp = null; }
  3432. endOperations(group);
  3433. }); }
  3434. }
  3435. // The DOM updates done when an operation finishes are batched so
  3436. // that the minimum number of relayouts are required.
  3437. function endOperations(group) {
  3438. var ops = group.ops;
  3439. for (var i = 0; i < ops.length; i++) // Read DOM
  3440. { endOperation_R1(ops[i]); }
  3441. for (var i$1 = 0; i$1 < ops.length; i$1++) // Write DOM (maybe)
  3442. { endOperation_W1(ops[i$1]); }
  3443. for (var i$2 = 0; i$2 < ops.length; i$2++) // Read DOM
  3444. { endOperation_R2(ops[i$2]); }
  3445. for (var i$3 = 0; i$3 < ops.length; i$3++) // Write DOM (maybe)
  3446. { endOperation_W2(ops[i$3]); }
  3447. for (var i$4 = 0; i$4 < ops.length; i$4++) // Read DOM
  3448. { endOperation_finish(ops[i$4]); }
  3449. }
  3450. function endOperation_R1(op) {
  3451. var cm = op.cm, display = cm.display;
  3452. maybeClipScrollbars(cm);
  3453. if (op.updateMaxLine) { findMaxLine(cm); }
  3454. op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null ||
  3455. op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom ||
  3456. op.scrollToPos.to.line >= display.viewTo) ||
  3457. display.maxLineChanged && cm.options.lineWrapping;
  3458. op.update = op.mustUpdate &&
  3459. new DisplayUpdate(cm, op.mustUpdate && {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate);
  3460. }
  3461. function endOperation_W1(op) {
  3462. op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update);
  3463. }
  3464. function endOperation_R2(op) {
  3465. var cm = op.cm, display = cm.display;
  3466. if (op.updatedDisplay) { updateHeightsInViewport(cm); }
  3467. op.barMeasure = measureForScrollbars(cm);
  3468. // If the max line changed since it was last measured, measure it,
  3469. // and ensure the document's width matches it.
  3470. // updateDisplay_W2 will use these properties to do the actual resizing
  3471. if (display.maxLineChanged && !cm.options.lineWrapping) {
  3472. op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3;
  3473. cm.display.sizerWidth = op.adjustWidthTo;
  3474. op.barMeasure.scrollWidth =
  3475. Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth);
  3476. op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm));
  3477. }
  3478. if (op.updatedDisplay || op.selectionChanged)
  3479. { op.preparedSelection = display.input.prepareSelection(); }
  3480. }
  3481. function endOperation_W2(op) {
  3482. var cm = op.cm;
  3483. if (op.adjustWidthTo != null) {
  3484. cm.display.sizer.style.minWidth = op.adjustWidthTo + "px";
  3485. if (op.maxScrollLeft < cm.doc.scrollLeft)
  3486. { setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true); }
  3487. cm.display.maxLineChanged = false;
  3488. }
  3489. var takeFocus = op.focus && op.focus == activeElt();
  3490. if (op.preparedSelection)
  3491. { cm.display.input.showSelection(op.preparedSelection, takeFocus); }
  3492. if (op.updatedDisplay || op.startHeight != cm.doc.height)
  3493. { updateScrollbars(cm, op.barMeasure); }
  3494. if (op.updatedDisplay)
  3495. { setDocumentHeight(cm, op.barMeasure); }
  3496. if (op.selectionChanged) { restartBlink(cm); }
  3497. if (cm.state.focused && op.updateInput)
  3498. { cm.display.input.reset(op.typing); }
  3499. if (takeFocus) { ensureFocus(op.cm); }
  3500. }
  3501. function endOperation_finish(op) {
  3502. var cm = op.cm, display = cm.display, doc = cm.doc;
  3503. if (op.updatedDisplay) { postUpdateDisplay(cm, op.update); }
  3504. // Abort mouse wheel delta measurement, when scrolling explicitly
  3505. if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos))
  3506. { display.wheelStartX = display.wheelStartY = null; }
  3507. // Propagate the scroll position to the actual DOM scroller
  3508. if (op.scrollTop != null) { setScrollTop(cm, op.scrollTop, op.forceScroll); }
  3509. if (op.scrollLeft != null) { setScrollLeft(cm, op.scrollLeft, true, true); }
  3510. // If we need to scroll a specific position into view, do so.
  3511. if (op.scrollToPos) {
  3512. var rect = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from),
  3513. clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin);
  3514. maybeScrollWindow(cm, rect);
  3515. }
  3516. // Fire events for markers that are hidden/unidden by editing or
  3517. // undoing
  3518. var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers;
  3519. if (hidden) { for (var i = 0; i < hidden.length; ++i)
  3520. { if (!hidden[i].lines.length) { signal(hidden[i], "hide"); } } }
  3521. if (unhidden) { for (var i$1 = 0; i$1 < unhidden.length; ++i$1)
  3522. { if (unhidden[i$1].lines.length) { signal(unhidden[i$1], "unhide"); } } }
  3523. if (display.wrapper.offsetHeight)
  3524. { doc.scrollTop = cm.display.scroller.scrollTop; }
  3525. // Fire change events, and delayed event handlers
  3526. if (op.changeObjs)
  3527. { signal(cm, "changes", cm, op.changeObjs); }
  3528. if (op.update)
  3529. { op.update.finish(); }
  3530. }
  3531. // Run the given function in an operation
  3532. function runInOp(cm, f) {
  3533. if (cm.curOp) { return f() }
  3534. startOperation(cm);
  3535. try { return f() }
  3536. finally { endOperation(cm); }
  3537. }
  3538. // Wraps a function in an operation. Returns the wrapped function.
  3539. function operation(cm, f) {
  3540. return function() {
  3541. if (cm.curOp) { return f.apply(cm, arguments) }
  3542. startOperation(cm);
  3543. try { return f.apply(cm, arguments) }
  3544. finally { endOperation(cm); }
  3545. }
  3546. }
  3547. // Used to add methods to editor and doc instances, wrapping them in
  3548. // operations.
  3549. function methodOp(f) {
  3550. return function() {
  3551. if (this.curOp) { return f.apply(this, arguments) }
  3552. startOperation(this);
  3553. try { return f.apply(this, arguments) }
  3554. finally { endOperation(this); }
  3555. }
  3556. }
  3557. function docMethodOp(f) {
  3558. return function() {
  3559. var cm = this.cm;
  3560. if (!cm || cm.curOp) { return f.apply(this, arguments) }
  3561. startOperation(cm);
  3562. try { return f.apply(this, arguments) }
  3563. finally { endOperation(cm); }
  3564. }
  3565. }
  3566. // HIGHLIGHT WORKER
  3567. function startWorker(cm, time) {
  3568. if (cm.doc.highlightFrontier < cm.display.viewTo)
  3569. { cm.state.highlight.set(time, bind(highlightWorker, cm)); }
  3570. }
  3571. function highlightWorker(cm) {
  3572. var doc = cm.doc;
  3573. if (doc.highlightFrontier >= cm.display.viewTo) { return }
  3574. var end = +new Date + cm.options.workTime;
  3575. var context = getContextBefore(cm, doc.highlightFrontier);
  3576. var changedLines = [];
  3577. doc.iter(context.line, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function (line) {
  3578. if (context.line >= cm.display.viewFrom) { // Visible
  3579. var oldStyles = line.styles;
  3580. var resetState = line.text.length > cm.options.maxHighlightLength ? copyState(doc.mode, context.state) : null;
  3581. var highlighted = highlightLine(cm, line, context, true);
  3582. if (resetState) { context.state = resetState; }
  3583. line.styles = highlighted.styles;
  3584. var oldCls = line.styleClasses, newCls = highlighted.classes;
  3585. if (newCls) { line.styleClasses = newCls; }
  3586. else if (oldCls) { line.styleClasses = null; }
  3587. var ischange = !oldStyles || oldStyles.length != line.styles.length ||
  3588. oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass);
  3589. for (var i = 0; !ischange && i < oldStyles.length; ++i) { ischange = oldStyles[i] != line.styles[i]; }
  3590. if (ischange) { changedLines.push(context.line); }
  3591. line.stateAfter = context.save();
  3592. context.nextLine();
  3593. } else {
  3594. if (line.text.length <= cm.options.maxHighlightLength)
  3595. { processLine(cm, line.text, context); }
  3596. line.stateAfter = context.line % 5 == 0 ? context.save() : null;
  3597. context.nextLine();
  3598. }
  3599. if (+new Date > end) {
  3600. startWorker(cm, cm.options.workDelay);
  3601. return true
  3602. }
  3603. });
  3604. doc.highlightFrontier = context.line;
  3605. doc.modeFrontier = Math.max(doc.modeFrontier, context.line);
  3606. if (changedLines.length) { runInOp(cm, function () {
  3607. for (var i = 0; i < changedLines.length; i++)
  3608. { regLineChange(cm, changedLines[i], "text"); }
  3609. }); }
  3610. }
  3611. // DISPLAY DRAWING
  3612. var DisplayUpdate = function(cm, viewport, force) {
  3613. var display = cm.display;
  3614. this.viewport = viewport;
  3615. // Store some values that we'll need later (but don't want to force a relayout for)
  3616. this.visible = visibleLines(display, cm.doc, viewport);
  3617. this.editorIsHidden = !display.wrapper.offsetWidth;
  3618. this.wrapperHeight = display.wrapper.clientHeight;
  3619. this.wrapperWidth = display.wrapper.clientWidth;
  3620. this.oldDisplayWidth = displayWidth(cm);
  3621. this.force = force;
  3622. this.dims = getDimensions(cm);
  3623. this.events = [];
  3624. };
  3625. DisplayUpdate.prototype.signal = function (emitter, type) {
  3626. if (hasHandler(emitter, type))
  3627. { this.events.push(arguments); }
  3628. };
  3629. DisplayUpdate.prototype.finish = function () {
  3630. var this$1 = this;
  3631. for (var i = 0; i < this.events.length; i++)
  3632. { signal.apply(null, this$1.events[i]); }
  3633. };
  3634. function maybeClipScrollbars(cm) {
  3635. var display = cm.display;
  3636. if (!display.scrollbarsClipped && display.scroller.offsetWidth) {
  3637. display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth;
  3638. display.heightForcer.style.height = scrollGap(cm) + "px";
  3639. display.sizer.style.marginBottom = -display.nativeBarWidth + "px";
  3640. display.sizer.style.borderRightWidth = scrollGap(cm) + "px";
  3641. display.scrollbarsClipped = true;
  3642. }
  3643. }
  3644. function selectionSnapshot(cm) {
  3645. if (cm.hasFocus()) { return null }
  3646. var active = activeElt();
  3647. if (!active || !contains(cm.display.lineDiv, active)) { return null }
  3648. var result = {activeElt: active};
  3649. if (window.getSelection) {
  3650. var sel = window.getSelection();
  3651. if (sel.anchorNode && sel.extend && contains(cm.display.lineDiv, sel.anchorNode)) {
  3652. result.anchorNode = sel.anchorNode;
  3653. result.anchorOffset = sel.anchorOffset;
  3654. result.focusNode = sel.focusNode;
  3655. result.focusOffset = sel.focusOffset;
  3656. }
  3657. }
  3658. return result
  3659. }
  3660. function restoreSelection(snapshot) {
  3661. if (!snapshot || !snapshot.activeElt || snapshot.activeElt == activeElt()) { return }
  3662. snapshot.activeElt.focus();
  3663. if (snapshot.anchorNode && contains(document.body, snapshot.anchorNode) && contains(document.body, snapshot.focusNode)) {
  3664. var sel = window.getSelection(), range$$1 = document.createRange();
  3665. range$$1.setEnd(snapshot.anchorNode, snapshot.anchorOffset);
  3666. range$$1.collapse(false);
  3667. sel.removeAllRanges();
  3668. sel.addRange(range$$1);
  3669. sel.extend(snapshot.focusNode, snapshot.focusOffset);
  3670. }
  3671. }
  3672. // Does the actual updating of the line display. Bails out
  3673. // (returning false) when there is nothing to be done and forced is
  3674. // false.
  3675. function updateDisplayIfNeeded(cm, update) {
  3676. var display = cm.display, doc = cm.doc;
  3677. if (update.editorIsHidden) {
  3678. resetView(cm);
  3679. return false
  3680. }
  3681. // Bail out if the visible area is already rendered and nothing changed.
  3682. if (!update.force &&
  3683. update.visible.from >= display.viewFrom && update.visible.to <= display.viewTo &&
  3684. (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) &&
  3685. display.renderedView == display.view && countDirtyView(cm) == 0)
  3686. { return false }
  3687. if (maybeUpdateLineNumberWidth(cm)) {
  3688. resetView(cm);
  3689. update.dims = getDimensions(cm);
  3690. }
  3691. // Compute a suitable new viewport (from & to)
  3692. var end = doc.first + doc.size;
  3693. var from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first);
  3694. var to = Math.min(end, update.visible.to + cm.options.viewportMargin);
  3695. if (display.viewFrom < from && from - display.viewFrom < 20) { from = Math.max(doc.first, display.viewFrom); }
  3696. if (display.viewTo > to && display.viewTo - to < 20) { to = Math.min(end, display.viewTo); }
  3697. if (sawCollapsedSpans) {
  3698. from = visualLineNo(cm.doc, from);
  3699. to = visualLineEndNo(cm.doc, to);
  3700. }
  3701. var different = from != display.viewFrom || to != display.viewTo ||
  3702. display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth;
  3703. adjustView(cm, from, to);
  3704. display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom));
  3705. // Position the mover div to align with the current scroll position
  3706. cm.display.mover.style.top = display.viewOffset + "px";
  3707. var toUpdate = countDirtyView(cm);
  3708. if (!different && toUpdate == 0 && !update.force && display.renderedView == display.view &&
  3709. (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo))
  3710. { return false }
  3711. // For big changes, we hide the enclosing element during the
  3712. // update, since that speeds up the operations on most browsers.
  3713. var selSnapshot = selectionSnapshot(cm);
  3714. if (toUpdate > 4) { display.lineDiv.style.display = "none"; }
  3715. patchDisplay(cm, display.updateLineNumbers, update.dims);
  3716. if (toUpdate > 4) { display.lineDiv.style.display = ""; }
  3717. display.renderedView = display.view;
  3718. // There might have been a widget with a focused element that got
  3719. // hidden or updated, if so re-focus it.
  3720. restoreSelection(selSnapshot);
  3721. // Prevent selection and cursors from interfering with the scroll
  3722. // width and height.
  3723. removeChildren(display.cursorDiv);
  3724. removeChildren(display.selectionDiv);
  3725. display.gutters.style.height = display.sizer.style.minHeight = 0;
  3726. if (different) {
  3727. display.lastWrapHeight = update.wrapperHeight;
  3728. display.lastWrapWidth = update.wrapperWidth;
  3729. startWorker(cm, 400);
  3730. }
  3731. display.updateLineNumbers = null;
  3732. return true
  3733. }
  3734. function postUpdateDisplay(cm, update) {
  3735. var viewport = update.viewport;
  3736. for (var first = true;; first = false) {
  3737. if (!first || !cm.options.lineWrapping || update.oldDisplayWidth == displayWidth(cm)) {
  3738. // Clip forced viewport to actual scrollable area.
  3739. if (viewport && viewport.top != null)
  3740. { viewport = {top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top)}; }
  3741. // Updated line heights might result in the drawn area not
  3742. // actually covering the viewport. Keep looping until it does.
  3743. update.visible = visibleLines(cm.display, cm.doc, viewport);
  3744. if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo)
  3745. { break }
  3746. }
  3747. if (!updateDisplayIfNeeded(cm, update)) { break }
  3748. updateHeightsInViewport(cm);
  3749. var barMeasure = measureForScrollbars(cm);
  3750. updateSelection(cm);
  3751. updateScrollbars(cm, barMeasure);
  3752. setDocumentHeight(cm, barMeasure);
  3753. update.force = false;
  3754. }
  3755. update.signal(cm, "update", cm);
  3756. if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) {
  3757. update.signal(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo);
  3758. cm.display.reportedViewFrom = cm.display.viewFrom; cm.display.reportedViewTo = cm.display.viewTo;
  3759. }
  3760. }
  3761. function updateDisplaySimple(cm, viewport) {
  3762. var update = new DisplayUpdate(cm, viewport);
  3763. if (updateDisplayIfNeeded(cm, update)) {
  3764. updateHeightsInViewport(cm);
  3765. postUpdateDisplay(cm, update);
  3766. var barMeasure = measureForScrollbars(cm);
  3767. updateSelection(cm);
  3768. updateScrollbars(cm, barMeasure);
  3769. setDocumentHeight(cm, barMeasure);
  3770. update.finish();
  3771. }
  3772. }
  3773. // Sync the actual display DOM structure with display.view, removing
  3774. // nodes for lines that are no longer in view, and creating the ones
  3775. // that are not there yet, and updating the ones that are out of
  3776. // date.
  3777. function patchDisplay(cm, updateNumbersFrom, dims) {
  3778. var display = cm.display, lineNumbers = cm.options.lineNumbers;
  3779. var container = display.lineDiv, cur = container.firstChild;
  3780. function rm(node) {
  3781. var next = node.nextSibling;
  3782. // Works around a throw-scroll bug in OS X Webkit
  3783. if (webkit && mac && cm.display.currentWheelTarget == node)
  3784. { node.style.display = "none"; }
  3785. else
  3786. { node.parentNode.removeChild(node); }
  3787. return next
  3788. }
  3789. var view = display.view, lineN = display.viewFrom;
  3790. // Loop over the elements in the view, syncing cur (the DOM nodes
  3791. // in display.lineDiv) with the view as we go.
  3792. for (var i = 0; i < view.length; i++) {
  3793. var lineView = view[i];
  3794. if (lineView.hidden) ; else if (!lineView.node || lineView.node.parentNode != container) { // Not drawn yet
  3795. var node = buildLineElement(cm, lineView, lineN, dims);
  3796. container.insertBefore(node, cur);
  3797. } else { // Already drawn
  3798. while (cur != lineView.node) { cur = rm(cur); }
  3799. var updateNumber = lineNumbers && updateNumbersFrom != null &&
  3800. updateNumbersFrom <= lineN && lineView.lineNumber;
  3801. if (lineView.changes) {
  3802. if (indexOf(lineView.changes, "gutter") > -1) { updateNumber = false; }
  3803. updateLineForChanges(cm, lineView, lineN, dims);
  3804. }
  3805. if (updateNumber) {
  3806. removeChildren(lineView.lineNumber);
  3807. lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN)));
  3808. }
  3809. cur = lineView.node.nextSibling;
  3810. }
  3811. lineN += lineView.size;
  3812. }
  3813. while (cur) { cur = rm(cur); }
  3814. }
  3815. function updateGutterSpace(display) {
  3816. var width = display.gutters.offsetWidth;
  3817. display.sizer.style.marginLeft = width + "px";
  3818. }
  3819. function setDocumentHeight(cm, measure) {
  3820. cm.display.sizer.style.minHeight = measure.docHeight + "px";
  3821. cm.display.heightForcer.style.top = measure.docHeight + "px";
  3822. cm.display.gutters.style.height = (measure.docHeight + cm.display.barHeight + scrollGap(cm)) + "px";
  3823. }
  3824. // Re-align line numbers and gutter marks to compensate for
  3825. // horizontal scrolling.
  3826. function alignHorizontally(cm) {
  3827. var display = cm.display, view = display.view;
  3828. if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) { return }
  3829. var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft;
  3830. var gutterW = display.gutters.offsetWidth, left = comp + "px";
  3831. for (var i = 0; i < view.length; i++) { if (!view[i].hidden) {
  3832. if (cm.options.fixedGutter) {
  3833. if (view[i].gutter)
  3834. { view[i].gutter.style.left = left; }
  3835. if (view[i].gutterBackground)
  3836. { view[i].gutterBackground.style.left = left; }
  3837. }
  3838. var align = view[i].alignable;
  3839. if (align) { for (var j = 0; j < align.length; j++)
  3840. { align[j].style.left = left; } }
  3841. } }
  3842. if (cm.options.fixedGutter)
  3843. { display.gutters.style.left = (comp + gutterW) + "px"; }
  3844. }
  3845. // Used to ensure that the line number gutter is still the right
  3846. // size for the current document size. Returns true when an update
  3847. // is needed.
  3848. function maybeUpdateLineNumberWidth(cm) {
  3849. if (!cm.options.lineNumbers) { return false }
  3850. var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display;
  3851. if (last.length != display.lineNumChars) {
  3852. var test = display.measure.appendChild(elt("div", [elt("div", last)],
  3853. "CodeMirror-linenumber CodeMirror-gutter-elt"));
  3854. var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW;
  3855. display.lineGutter.style.width = "";
  3856. display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding) + 1;
  3857. display.lineNumWidth = display.lineNumInnerWidth + padding;
  3858. display.lineNumChars = display.lineNumInnerWidth ? last.length : -1;
  3859. display.lineGutter.style.width = display.lineNumWidth + "px";
  3860. updateGutterSpace(cm.display);
  3861. return true
  3862. }
  3863. return false
  3864. }
  3865. function getGutters(gutters, lineNumbers) {
  3866. var result = [], sawLineNumbers = false;
  3867. for (var i = 0; i < gutters.length; i++) {
  3868. var name = gutters[i], style = null;
  3869. if (typeof name != "string") { style = name.style; name = name.className; }
  3870. if (name == "CodeMirror-linenumbers") {
  3871. if (!lineNumbers) { continue }
  3872. else { sawLineNumbers = true; }
  3873. }
  3874. result.push({className: name, style: style});
  3875. }
  3876. if (lineNumbers && !sawLineNumbers) { result.push({className: "CodeMirror-linenumbers", style: null}); }
  3877. return result
  3878. }
  3879. // Rebuild the gutter elements, ensure the margin to the left of the
  3880. // code matches their width.
  3881. function renderGutters(display) {
  3882. var gutters = display.gutters, specs = display.gutterSpecs;
  3883. removeChildren(gutters);
  3884. display.lineGutter = null;
  3885. for (var i = 0; i < specs.length; ++i) {
  3886. var ref = specs[i];
  3887. var className = ref.className;
  3888. var style = ref.style;
  3889. var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + className));
  3890. if (style) { gElt.style.cssText = style; }
  3891. if (className == "CodeMirror-linenumbers") {
  3892. display.lineGutter = gElt;
  3893. gElt.style.width = (display.lineNumWidth || 1) + "px";
  3894. }
  3895. }
  3896. gutters.style.display = specs.length ? "" : "none";
  3897. updateGutterSpace(display);
  3898. }
  3899. function updateGutters(cm) {
  3900. renderGutters(cm.display);
  3901. regChange(cm);
  3902. alignHorizontally(cm);
  3903. }
  3904. // The display handles the DOM integration, both for input reading
  3905. // and content drawing. It holds references to DOM nodes and
  3906. // display-related state.
  3907. function Display(place, doc, input, options) {
  3908. var d = this;
  3909. this.input = input;
  3910. // Covers bottom-right square when both scrollbars are present.
  3911. d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler");
  3912. d.scrollbarFiller.setAttribute("cm-not-content", "true");
  3913. // Covers bottom of gutter when coverGutterNextToScrollbar is on
  3914. // and h scrollbar is present.
  3915. d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler");
  3916. d.gutterFiller.setAttribute("cm-not-content", "true");
  3917. // Will contain the actual code, positioned to cover the viewport.
  3918. d.lineDiv = eltP("div", null, "CodeMirror-code");
  3919. // Elements are added to these to represent selection and cursors.
  3920. d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1");
  3921. d.cursorDiv = elt("div", null, "CodeMirror-cursors");
  3922. // A visibility: hidden element used to find the size of things.
  3923. d.measure = elt("div", null, "CodeMirror-measure");
  3924. // When lines outside of the viewport are measured, they are drawn in this.
  3925. d.lineMeasure = elt("div", null, "CodeMirror-measure");
  3926. // Wraps everything that needs to exist inside the vertically-padded coordinate system
  3927. d.lineSpace = eltP("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv],
  3928. null, "position: relative; outline: none");
  3929. var lines = eltP("div", [d.lineSpace], "CodeMirror-lines");
  3930. // Moved around its parent to cover visible view.
  3931. d.mover = elt("div", [lines], null, "position: relative");
  3932. // Set to the height of the document, allowing scrolling.
  3933. d.sizer = elt("div", [d.mover], "CodeMirror-sizer");
  3934. d.sizerWidth = null;
  3935. // Behavior of elts with overflow: auto and padding is
  3936. // inconsistent across browsers. This is used to ensure the
  3937. // scrollable area is big enough.
  3938. d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerGap + "px; width: 1px;");
  3939. // Will contain the gutters, if any.
  3940. d.gutters = elt("div", null, "CodeMirror-gutters");
  3941. d.lineGutter = null;
  3942. // Actual scrollable element.
  3943. d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll");
  3944. d.scroller.setAttribute("tabIndex", "-1");
  3945. // The element in which the editor lives.
  3946. d.wrapper = elt("div", [d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror");
  3947. // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported)
  3948. if (ie && ie_version < 8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; }
  3949. if (!webkit && !(gecko && mobile)) { d.scroller.draggable = true; }
  3950. if (place) {
  3951. if (place.appendChild) { place.appendChild(d.wrapper); }
  3952. else { place(d.wrapper); }
  3953. }
  3954. // Current rendered range (may be bigger than the view window).
  3955. d.viewFrom = d.viewTo = doc.first;
  3956. d.reportedViewFrom = d.reportedViewTo = doc.first;
  3957. // Information about the rendered lines.
  3958. d.view = [];
  3959. d.renderedView = null;
  3960. // Holds info about a single rendered line when it was rendered
  3961. // for measurement, while not in view.
  3962. d.externalMeasured = null;
  3963. // Empty space (in pixels) above the view
  3964. d.viewOffset = 0;
  3965. d.lastWrapHeight = d.lastWrapWidth = 0;
  3966. d.updateLineNumbers = null;
  3967. d.nativeBarWidth = d.barHeight = d.barWidth = 0;
  3968. d.scrollbarsClipped = false;
  3969. // Used to only resize the line number gutter when necessary (when
  3970. // the amount of lines crosses a boundary that makes its width change)
  3971. d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null;
  3972. // Set to true when a non-horizontal-scrolling line widget is
  3973. // added. As an optimization, line widget aligning is skipped when
  3974. // this is false.
  3975. d.alignWidgets = false;
  3976. d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
  3977. // Tracks the maximum line length so that the horizontal scrollbar
  3978. // can be kept static when scrolling.
  3979. d.maxLine = null;
  3980. d.maxLineLength = 0;
  3981. d.maxLineChanged = false;
  3982. // Used for measuring wheel scrolling granularity
  3983. d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null;
  3984. // True when shift is held down.
  3985. d.shift = false;
  3986. // Used to track whether anything happened since the context menu
  3987. // was opened.
  3988. d.selForContextMenu = null;
  3989. d.activeTouch = null;
  3990. d.gutterSpecs = getGutters(options.gutters, options.lineNumbers);
  3991. renderGutters(d);
  3992. input.init(d);
  3993. }
  3994. // Since the delta values reported on mouse wheel events are
  3995. // unstandardized between browsers and even browser versions, and
  3996. // generally horribly unpredictable, this code starts by measuring
  3997. // the scroll effect that the first few mouse wheel events have,
  3998. // and, from that, detects the way it can convert deltas to pixel
  3999. // offsets afterwards.
  4000. //
  4001. // The reason we want to know the amount a wheel event will scroll
  4002. // is that it gives us a chance to update the display before the
  4003. // actual scrolling happens, reducing flickering.
  4004. var wheelSamples = 0, wheelPixelsPerUnit = null;
  4005. // Fill in a browser-detected starting value on browsers where we
  4006. // know one. These don't have to be accurate -- the result of them
  4007. // being wrong would just be a slight flicker on the first wheel
  4008. // scroll (if it is large enough).
  4009. if (ie) { wheelPixelsPerUnit = -.53; }
  4010. else if (gecko) { wheelPixelsPerUnit = 15; }
  4011. else if (chrome) { wheelPixelsPerUnit = -.7; }
  4012. else if (safari) { wheelPixelsPerUnit = -1/3; }
  4013. function wheelEventDelta(e) {
  4014. var dx = e.wheelDeltaX, dy = e.wheelDeltaY;
  4015. if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) { dx = e.detail; }
  4016. if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) { dy = e.detail; }
  4017. else if (dy == null) { dy = e.wheelDelta; }
  4018. return {x: dx, y: dy}
  4019. }
  4020. function wheelEventPixels(e) {
  4021. var delta = wheelEventDelta(e);
  4022. delta.x *= wheelPixelsPerUnit;
  4023. delta.y *= wheelPixelsPerUnit;
  4024. return delta
  4025. }
  4026. function onScrollWheel(cm, e) {
  4027. var delta = wheelEventDelta(e), dx = delta.x, dy = delta.y;
  4028. var display = cm.display, scroll = display.scroller;
  4029. // Quit if there's nothing to scroll here
  4030. var canScrollX = scroll.scrollWidth > scroll.clientWidth;
  4031. var canScrollY = scroll.scrollHeight > scroll.clientHeight;
  4032. if (!(dx && canScrollX || dy && canScrollY)) { return }
  4033. // Webkit browsers on OS X abort momentum scrolls when the target
  4034. // of the scroll event is removed from the scrollable element.
  4035. // This hack (see related code in patchDisplay) makes sure the
  4036. // element is kept around.
  4037. if (dy && mac && webkit) {
  4038. outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) {
  4039. for (var i = 0; i < view.length; i++) {
  4040. if (view[i].node == cur) {
  4041. cm.display.currentWheelTarget = cur;
  4042. break outer
  4043. }
  4044. }
  4045. }
  4046. }
  4047. // On some browsers, horizontal scrolling will cause redraws to
  4048. // happen before the gutter has been realigned, causing it to
  4049. // wriggle around in a most unseemly way. When we have an
  4050. // estimated pixels/delta value, we just handle horizontal
  4051. // scrolling entirely here. It'll be slightly off from native, but
  4052. // better than glitching out.
  4053. if (dx && !gecko && !presto && wheelPixelsPerUnit != null) {
  4054. if (dy && canScrollY)
  4055. { updateScrollTop(cm, Math.max(0, scroll.scrollTop + dy * wheelPixelsPerUnit)); }
  4056. setScrollLeft(cm, Math.max(0, scroll.scrollLeft + dx * wheelPixelsPerUnit));
  4057. // Only prevent default scrolling if vertical scrolling is
  4058. // actually possible. Otherwise, it causes vertical scroll
  4059. // jitter on OSX trackpads when deltaX is small and deltaY
  4060. // is large (issue #3579)
  4061. if (!dy || (dy && canScrollY))
  4062. { e_preventDefault(e); }
  4063. display.wheelStartX = null; // Abort measurement, if in progress
  4064. return
  4065. }
  4066. // 'Project' the visible viewport to cover the area that is being
  4067. // scrolled into view (if we know enough to estimate it).
  4068. if (dy && wheelPixelsPerUnit != null) {
  4069. var pixels = dy * wheelPixelsPerUnit;
  4070. var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight;
  4071. if (pixels < 0) { top = Math.max(0, top + pixels - 50); }
  4072. else { bot = Math.min(cm.doc.height, bot + pixels + 50); }
  4073. updateDisplaySimple(cm, {top: top, bottom: bot});
  4074. }
  4075. if (wheelSamples < 20) {
  4076. if (display.wheelStartX == null) {
  4077. display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop;
  4078. display.wheelDX = dx; display.wheelDY = dy;
  4079. setTimeout(function () {
  4080. if (display.wheelStartX == null) { return }
  4081. var movedX = scroll.scrollLeft - display.wheelStartX;
  4082. var movedY = scroll.scrollTop - display.wheelStartY;
  4083. var sample = (movedY && display.wheelDY && movedY / display.wheelDY) ||
  4084. (movedX && display.wheelDX && movedX / display.wheelDX);
  4085. display.wheelStartX = display.wheelStartY = null;
  4086. if (!sample) { return }
  4087. wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1);
  4088. ++wheelSamples;
  4089. }, 200);
  4090. } else {
  4091. display.wheelDX += dx; display.wheelDY += dy;
  4092. }
  4093. }
  4094. }
  4095. // Selection objects are immutable. A new one is created every time
  4096. // the selection changes. A selection is one or more non-overlapping
  4097. // (and non-touching) ranges, sorted, and an integer that indicates
  4098. // which one is the primary selection (the one that's scrolled into
  4099. // view, that getCursor returns, etc).
  4100. var Selection = function(ranges, primIndex) {
  4101. this.ranges = ranges;
  4102. this.primIndex = primIndex;
  4103. };
  4104. Selection.prototype.primary = function () { return this.ranges[this.primIndex] };
  4105. Selection.prototype.equals = function (other) {
  4106. var this$1 = this;
  4107. if (other == this) { return true }
  4108. if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) { return false }
  4109. for (var i = 0; i < this.ranges.length; i++) {
  4110. var here = this$1.ranges[i], there = other.ranges[i];
  4111. if (!equalCursorPos(here.anchor, there.anchor) || !equalCursorPos(here.head, there.head)) { return false }
  4112. }
  4113. return true
  4114. };
  4115. Selection.prototype.deepCopy = function () {
  4116. var this$1 = this;
  4117. var out = [];
  4118. for (var i = 0; i < this.ranges.length; i++)
  4119. { out[i] = new Range(copyPos(this$1.ranges[i].anchor), copyPos(this$1.ranges[i].head)); }
  4120. return new Selection(out, this.primIndex)
  4121. };
  4122. Selection.prototype.somethingSelected = function () {
  4123. var this$1 = this;
  4124. for (var i = 0; i < this.ranges.length; i++)
  4125. { if (!this$1.ranges[i].empty()) { return true } }
  4126. return false
  4127. };
  4128. Selection.prototype.contains = function (pos, end) {
  4129. var this$1 = this;
  4130. if (!end) { end = pos; }
  4131. for (var i = 0; i < this.ranges.length; i++) {
  4132. var range = this$1.ranges[i];
  4133. if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0)
  4134. { return i }
  4135. }
  4136. return -1
  4137. };
  4138. var Range = function(anchor, head) {
  4139. this.anchor = anchor; this.head = head;
  4140. };
  4141. Range.prototype.from = function () { return minPos(this.anchor, this.head) };
  4142. Range.prototype.to = function () { return maxPos(this.anchor, this.head) };
  4143. Range.prototype.empty = function () { return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch };
  4144. // Take an unsorted, potentially overlapping set of ranges, and
  4145. // build a selection out of it. 'Consumes' ranges array (modifying
  4146. // it).
  4147. function normalizeSelection(cm, ranges, primIndex) {
  4148. var mayTouch = cm && cm.options.selectionsMayTouch;
  4149. var prim = ranges[primIndex];
  4150. ranges.sort(function (a, b) { return cmp(a.from(), b.from()); });
  4151. primIndex = indexOf(ranges, prim);
  4152. for (var i = 1; i < ranges.length; i++) {
  4153. var cur = ranges[i], prev = ranges[i - 1];
  4154. var diff = cmp(prev.to(), cur.from());
  4155. if (mayTouch && !cur.empty() ? diff > 0 : diff >= 0) {
  4156. var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to());
  4157. var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head;
  4158. if (i <= primIndex) { --primIndex; }
  4159. ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to));
  4160. }
  4161. }
  4162. return new Selection(ranges, primIndex)
  4163. }
  4164. function simpleSelection(anchor, head) {
  4165. return new Selection([new Range(anchor, head || anchor)], 0)
  4166. }
  4167. // Compute the position of the end of a change (its 'to' property
  4168. // refers to the pre-change end).
  4169. function changeEnd(change) {
  4170. if (!change.text) { return change.to }
  4171. return Pos(change.from.line + change.text.length - 1,
  4172. lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0))
  4173. }
  4174. // Adjust a position to refer to the post-change position of the
  4175. // same text, or the end of the change if the change covers it.
  4176. function adjustForChange(pos, change) {
  4177. if (cmp(pos, change.from) < 0) { return pos }
  4178. if (cmp(pos, change.to) <= 0) { return changeEnd(change) }
  4179. var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch;
  4180. if (pos.line == change.to.line) { ch += changeEnd(change).ch - change.to.ch; }
  4181. return Pos(line, ch)
  4182. }
  4183. function computeSelAfterChange(doc, change) {
  4184. var out = [];
  4185. for (var i = 0; i < doc.sel.ranges.length; i++) {
  4186. var range = doc.sel.ranges[i];
  4187. out.push(new Range(adjustForChange(range.anchor, change),
  4188. adjustForChange(range.head, change)));
  4189. }
  4190. return normalizeSelection(doc.cm, out, doc.sel.primIndex)
  4191. }
  4192. function offsetPos(pos, old, nw) {
  4193. if (pos.line == old.line)
  4194. { return Pos(nw.line, pos.ch - old.ch + nw.ch) }
  4195. else
  4196. { return Pos(nw.line + (pos.line - old.line), pos.ch) }
  4197. }
  4198. // Used by replaceSelections to allow moving the selection to the
  4199. // start or around the replaced test. Hint may be "start" or "around".
  4200. function computeReplacedSel(doc, changes, hint) {
  4201. var out = [];
  4202. var oldPrev = Pos(doc.first, 0), newPrev = oldPrev;
  4203. for (var i = 0; i < changes.length; i++) {
  4204. var change = changes[i];
  4205. var from = offsetPos(change.from, oldPrev, newPrev);
  4206. var to = offsetPos(changeEnd(change), oldPrev, newPrev);
  4207. oldPrev = change.to;
  4208. newPrev = to;
  4209. if (hint == "around") {
  4210. var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) < 0;
  4211. out[i] = new Range(inv ? to : from, inv ? from : to);
  4212. } else {
  4213. out[i] = new Range(from, from);
  4214. }
  4215. }
  4216. return new Selection(out, doc.sel.primIndex)
  4217. }
  4218. // Used to get the editor into a consistent state again when options change.
  4219. function loadMode(cm) {
  4220. cm.doc.mode = getMode(cm.options, cm.doc.modeOption);
  4221. resetModeState(cm);
  4222. }
  4223. function resetModeState(cm) {
  4224. cm.doc.iter(function (line) {
  4225. if (line.stateAfter) { line.stateAfter = null; }
  4226. if (line.styles) { line.styles = null; }
  4227. });
  4228. cm.doc.modeFrontier = cm.doc.highlightFrontier = cm.doc.first;
  4229. startWorker(cm, 100);
  4230. cm.state.modeGen++;
  4231. if (cm.curOp) { regChange(cm); }
  4232. }
  4233. // DOCUMENT DATA STRUCTURE
  4234. // By default, updates that start and end at the beginning of a line
  4235. // are treated specially, in order to make the association of line
  4236. // widgets and marker elements with the text behave more intuitive.
  4237. function isWholeLineUpdate(doc, change) {
  4238. return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" &&
  4239. (!doc.cm || doc.cm.options.wholeLineUpdateBefore)
  4240. }
  4241. // Perform a change on the document data structure.
  4242. function updateDoc(doc, change, markedSpans, estimateHeight$$1) {
  4243. function spansFor(n) {return markedSpans ? markedSpans[n] : null}
  4244. function update(line, text, spans) {
  4245. updateLine(line, text, spans, estimateHeight$$1);
  4246. signalLater(line, "change", line, change);
  4247. }
  4248. function linesFor(start, end) {
  4249. var result = [];
  4250. for (var i = start; i < end; ++i)
  4251. { result.push(new Line(text[i], spansFor(i), estimateHeight$$1)); }
  4252. return result
  4253. }
  4254. var from = change.from, to = change.to, text = change.text;
  4255. var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line);
  4256. var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line;
  4257. // Adjust the line structure
  4258. if (change.full) {
  4259. doc.insert(0, linesFor(0, text.length));
  4260. doc.remove(text.length, doc.size - text.length);
  4261. } else if (isWholeLineUpdate(doc, change)) {
  4262. // This is a whole-line replace. Treated specially to make
  4263. // sure line objects move the way they are supposed to.
  4264. var added = linesFor(0, text.length - 1);
  4265. update(lastLine, lastLine.text, lastSpans);
  4266. if (nlines) { doc.remove(from.line, nlines); }
  4267. if (added.length) { doc.insert(from.line, added); }
  4268. } else if (firstLine == lastLine) {
  4269. if (text.length == 1) {
  4270. update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans);
  4271. } else {
  4272. var added$1 = linesFor(1, text.length - 1);
  4273. added$1.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight$$1));
  4274. update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
  4275. doc.insert(from.line + 1, added$1);
  4276. }
  4277. } else if (text.length == 1) {
  4278. update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0));
  4279. doc.remove(from.line + 1, nlines);
  4280. } else {
  4281. update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
  4282. update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans);
  4283. var added$2 = linesFor(1, text.length - 1);
  4284. if (nlines > 1) { doc.remove(from.line + 1, nlines - 1); }
  4285. doc.insert(from.line + 1, added$2);
  4286. }
  4287. signalLater(doc, "change", doc, change);
  4288. }
  4289. // Call f for all linked documents.
  4290. function linkedDocs(doc, f, sharedHistOnly) {
  4291. function propagate(doc, skip, sharedHist) {
  4292. if (doc.linked) { for (var i = 0; i < doc.linked.length; ++i) {
  4293. var rel = doc.linked[i];
  4294. if (rel.doc == skip) { continue }
  4295. var shared = sharedHist && rel.sharedHist;
  4296. if (sharedHistOnly && !shared) { continue }
  4297. f(rel.doc, shared);
  4298. propagate(rel.doc, doc, shared);
  4299. } }
  4300. }
  4301. propagate(doc, null, true);
  4302. }
  4303. // Attach a document to an editor.
  4304. function attachDoc(cm, doc) {
  4305. if (doc.cm) { throw new Error("This document is already in use.") }
  4306. cm.doc = doc;
  4307. doc.cm = cm;
  4308. estimateLineHeights(cm);
  4309. loadMode(cm);
  4310. setDirectionClass(cm);
  4311. if (!cm.options.lineWrapping) { findMaxLine(cm); }
  4312. cm.options.mode = doc.modeOption;
  4313. regChange(cm);
  4314. }
  4315. function setDirectionClass(cm) {
  4316. (cm.doc.direction == "rtl" ? addClass : rmClass)(cm.display.lineDiv, "CodeMirror-rtl");
  4317. }
  4318. function directionChanged(cm) {
  4319. runInOp(cm, function () {
  4320. setDirectionClass(cm);
  4321. regChange(cm);
  4322. });
  4323. }
  4324. function History(startGen) {
  4325. // Arrays of change events and selections. Doing something adds an
  4326. // event to done and clears undo. Undoing moves events from done
  4327. // to undone, redoing moves them in the other direction.
  4328. this.done = []; this.undone = [];
  4329. this.undoDepth = Infinity;
  4330. // Used to track when changes can be merged into a single undo
  4331. // event
  4332. this.lastModTime = this.lastSelTime = 0;
  4333. this.lastOp = this.lastSelOp = null;
  4334. this.lastOrigin = this.lastSelOrigin = null;
  4335. // Used by the isClean() method
  4336. this.generation = this.maxGeneration = startGen || 1;
  4337. }
  4338. // Create a history change event from an updateDoc-style change
  4339. // object.
  4340. function historyChangeFromChange(doc, change) {
  4341. var histChange = {from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to)};
  4342. attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);
  4343. linkedDocs(doc, function (doc) { return attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1); }, true);
  4344. return histChange
  4345. }
  4346. // Pop all selection events off the end of a history array. Stop at
  4347. // a change event.
  4348. function clearSelectionEvents(array) {
  4349. while (array.length) {
  4350. var last = lst(array);
  4351. if (last.ranges) { array.pop(); }
  4352. else { break }
  4353. }
  4354. }
  4355. // Find the top change event in the history. Pop off selection
  4356. // events that are in the way.
  4357. function lastChangeEvent(hist, force) {
  4358. if (force) {
  4359. clearSelectionEvents(hist.done);
  4360. return lst(hist.done)
  4361. } else if (hist.done.length && !lst(hist.done).ranges) {
  4362. return lst(hist.done)
  4363. } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) {
  4364. hist.done.pop();
  4365. return lst(hist.done)
  4366. }
  4367. }
  4368. // Register a change in the history. Merges changes that are within
  4369. // a single operation, or are close together with an origin that
  4370. // allows merging (starting with "+") into a single event.
  4371. function addChangeToHistory(doc, change, selAfter, opId) {
  4372. var hist = doc.history;
  4373. hist.undone.length = 0;
  4374. var time = +new Date, cur;
  4375. var last;
  4376. if ((hist.lastOp == opId ||
  4377. hist.lastOrigin == change.origin && change.origin &&
  4378. ((change.origin.charAt(0) == "+" && hist.lastModTime > time - (doc.cm ? doc.cm.options.historyEventDelay : 500)) ||
  4379. change.origin.charAt(0) == "*")) &&
  4380. (cur = lastChangeEvent(hist, hist.lastOp == opId))) {
  4381. // Merge this change into the last event
  4382. last = lst(cur.changes);
  4383. if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) {
  4384. // Optimized case for simple insertion -- don't want to add
  4385. // new changesets for every character typed
  4386. last.to = changeEnd(change);
  4387. } else {
  4388. // Add new sub-event
  4389. cur.changes.push(historyChangeFromChange(doc, change));
  4390. }
  4391. } else {
  4392. // Can not be merged, start a new event.
  4393. var before = lst(hist.done);
  4394. if (!before || !before.ranges)
  4395. { pushSelectionToHistory(doc.sel, hist.done); }
  4396. cur = {changes: [historyChangeFromChange(doc, change)],
  4397. generation: hist.generation};
  4398. hist.done.push(cur);
  4399. while (hist.done.length > hist.undoDepth) {
  4400. hist.done.shift();
  4401. if (!hist.done[0].ranges) { hist.done.shift(); }
  4402. }
  4403. }
  4404. hist.done.push(selAfter);
  4405. hist.generation = ++hist.maxGeneration;
  4406. hist.lastModTime = hist.lastSelTime = time;
  4407. hist.lastOp = hist.lastSelOp = opId;
  4408. hist.lastOrigin = hist.lastSelOrigin = change.origin;
  4409. if (!last) { signal(doc, "historyAdded"); }
  4410. }
  4411. function selectionEventCanBeMerged(doc, origin, prev, sel) {
  4412. var ch = origin.charAt(0);
  4413. return ch == "*" ||
  4414. ch == "+" &&
  4415. prev.ranges.length == sel.ranges.length &&
  4416. prev.somethingSelected() == sel.somethingSelected() &&
  4417. new Date - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500)
  4418. }
  4419. // Called whenever the selection changes, sets the new selection as
  4420. // the pending selection in the history, and pushes the old pending
  4421. // selection into the 'done' array when it was significantly
  4422. // different (in number of selected ranges, emptiness, or time).
  4423. function addSelectionToHistory(doc, sel, opId, options) {
  4424. var hist = doc.history, origin = options && options.origin;
  4425. // A new event is started when the previous origin does not match
  4426. // the current, or the origins don't allow matching. Origins
  4427. // starting with * are always merged, those starting with + are
  4428. // merged when similar and close together in time.
  4429. if (opId == hist.lastSelOp ||
  4430. (origin && hist.lastSelOrigin == origin &&
  4431. (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin ||
  4432. selectionEventCanBeMerged(doc, origin, lst(hist.done), sel))))
  4433. { hist.done[hist.done.length - 1] = sel; }
  4434. else
  4435. { pushSelectionToHistory(sel, hist.done); }
  4436. hist.lastSelTime = +new Date;
  4437. hist.lastSelOrigin = origin;
  4438. hist.lastSelOp = opId;
  4439. if (options && options.clearRedo !== false)
  4440. { clearSelectionEvents(hist.undone); }
  4441. }
  4442. function pushSelectionToHistory(sel, dest) {
  4443. var top = lst(dest);
  4444. if (!(top && top.ranges && top.equals(sel)))
  4445. { dest.push(sel); }
  4446. }
  4447. // Used to store marked span information in the history.
  4448. function attachLocalSpans(doc, change, from, to) {
  4449. var existing = change["spans_" + doc.id], n = 0;
  4450. doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function (line) {
  4451. if (line.markedSpans)
  4452. { (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans; }
  4453. ++n;
  4454. });
  4455. }
  4456. // When un/re-doing restores text containing marked spans, those
  4457. // that have been explicitly cleared should not be restored.
  4458. function removeClearedSpans(spans) {
  4459. if (!spans) { return null }
  4460. var out;
  4461. for (var i = 0; i < spans.length; ++i) {
  4462. if (spans[i].marker.explicitlyCleared) { if (!out) { out = spans.slice(0, i); } }
  4463. else if (out) { out.push(spans[i]); }
  4464. }
  4465. return !out ? spans : out.length ? out : null
  4466. }
  4467. // Retrieve and filter the old marked spans stored in a change event.
  4468. function getOldSpans(doc, change) {
  4469. var found = change["spans_" + doc.id];
  4470. if (!found) { return null }
  4471. var nw = [];
  4472. for (var i = 0; i < change.text.length; ++i)
  4473. { nw.push(removeClearedSpans(found[i])); }
  4474. return nw
  4475. }
  4476. // Used for un/re-doing changes from the history. Combines the
  4477. // result of computing the existing spans with the set of spans that
  4478. // existed in the history (so that deleting around a span and then
  4479. // undoing brings back the span).
  4480. function mergeOldSpans(doc, change) {
  4481. var old = getOldSpans(doc, change);
  4482. var stretched = stretchSpansOverChange(doc, change);
  4483. if (!old) { return stretched }
  4484. if (!stretched) { return old }
  4485. for (var i = 0; i < old.length; ++i) {
  4486. var oldCur = old[i], stretchCur = stretched[i];
  4487. if (oldCur && stretchCur) {
  4488. spans: for (var j = 0; j < stretchCur.length; ++j) {
  4489. var span = stretchCur[j];
  4490. for (var k = 0; k < oldCur.length; ++k)
  4491. { if (oldCur[k].marker == span.marker) { continue spans } }
  4492. oldCur.push(span);
  4493. }
  4494. } else if (stretchCur) {
  4495. old[i] = stretchCur;
  4496. }
  4497. }
  4498. return old
  4499. }
  4500. // Used both to provide a JSON-safe object in .getHistory, and, when
  4501. // detaching a document, to split the history in two
  4502. function copyHistoryArray(events, newGroup, instantiateSel) {
  4503. var copy = [];
  4504. for (var i = 0; i < events.length; ++i) {
  4505. var event = events[i];
  4506. if (event.ranges) {
  4507. copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event);
  4508. continue
  4509. }
  4510. var changes = event.changes, newChanges = [];
  4511. copy.push({changes: newChanges});
  4512. for (var j = 0; j < changes.length; ++j) {
  4513. var change = changes[j], m = (void 0);
  4514. newChanges.push({from: change.from, to: change.to, text: change.text});
  4515. if (newGroup) { for (var prop in change) { if (m = prop.match(/^spans_(\d+)$/)) {
  4516. if (indexOf(newGroup, Number(m[1])) > -1) {
  4517. lst(newChanges)[prop] = change[prop];
  4518. delete change[prop];
  4519. }
  4520. } } }
  4521. }
  4522. }
  4523. return copy
  4524. }
  4525. // The 'scroll' parameter given to many of these indicated whether
  4526. // the new cursor position should be scrolled into view after
  4527. // modifying the selection.
  4528. // If shift is held or the extend flag is set, extends a range to
  4529. // include a given position (and optionally a second position).
  4530. // Otherwise, simply returns the range between the given positions.
  4531. // Used for cursor motion and such.
  4532. function extendRange(range, head, other, extend) {
  4533. if (extend) {
  4534. var anchor = range.anchor;
  4535. if (other) {
  4536. var posBefore = cmp(head, anchor) < 0;
  4537. if (posBefore != (cmp(other, anchor) < 0)) {
  4538. anchor = head;
  4539. head = other;
  4540. } else if (posBefore != (cmp(head, other) < 0)) {
  4541. head = other;
  4542. }
  4543. }
  4544. return new Range(anchor, head)
  4545. } else {
  4546. return new Range(other || head, head)
  4547. }
  4548. }
  4549. // Extend the primary selection range, discard the rest.
  4550. function extendSelection(doc, head, other, options, extend) {
  4551. if (extend == null) { extend = doc.cm && (doc.cm.display.shift || doc.extend); }
  4552. setSelection(doc, new Selection([extendRange(doc.sel.primary(), head, other, extend)], 0), options);
  4553. }
  4554. // Extend all selections (pos is an array of selections with length
  4555. // equal the number of selections)
  4556. function extendSelections(doc, heads, options) {
  4557. var out = [];
  4558. var extend = doc.cm && (doc.cm.display.shift || doc.extend);
  4559. for (var i = 0; i < doc.sel.ranges.length; i++)
  4560. { out[i] = extendRange(doc.sel.ranges[i], heads[i], null, extend); }
  4561. var newSel = normalizeSelection(doc.cm, out, doc.sel.primIndex);
  4562. setSelection(doc, newSel, options);
  4563. }
  4564. // Updates a single range in the selection.
  4565. function replaceOneSelection(doc, i, range, options) {
  4566. var ranges = doc.sel.ranges.slice(0);
  4567. ranges[i] = range;
  4568. setSelection(doc, normalizeSelection(doc.cm, ranges, doc.sel.primIndex), options);
  4569. }
  4570. // Reset the selection to a single range.
  4571. function setSimpleSelection(doc, anchor, head, options) {
  4572. setSelection(doc, simpleSelection(anchor, head), options);
  4573. }
  4574. // Give beforeSelectionChange handlers a change to influence a
  4575. // selection update.
  4576. function filterSelectionChange(doc, sel, options) {
  4577. var obj = {
  4578. ranges: sel.ranges,
  4579. update: function(ranges) {
  4580. var this$1 = this;
  4581. this.ranges = [];
  4582. for (var i = 0; i < ranges.length; i++)
  4583. { this$1.ranges[i] = new Range(clipPos(doc, ranges[i].anchor),
  4584. clipPos(doc, ranges[i].head)); }
  4585. },
  4586. origin: options && options.origin
  4587. };
  4588. signal(doc, "beforeSelectionChange", doc, obj);
  4589. if (doc.cm) { signal(doc.cm, "beforeSelectionChange", doc.cm, obj); }
  4590. if (obj.ranges != sel.ranges) { return normalizeSelection(doc.cm, obj.ranges, obj.ranges.length - 1) }
  4591. else { return sel }
  4592. }
  4593. function setSelectionReplaceHistory(doc, sel, options) {
  4594. var done = doc.history.done, last = lst(done);
  4595. if (last && last.ranges) {
  4596. done[done.length - 1] = sel;
  4597. setSelectionNoUndo(doc, sel, options);
  4598. } else {
  4599. setSelection(doc, sel, options);
  4600. }
  4601. }
  4602. // Set a new selection.
  4603. function setSelection(doc, sel, options) {
  4604. setSelectionNoUndo(doc, sel, options);
  4605. addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options);
  4606. }
  4607. function setSelectionNoUndo(doc, sel, options) {
  4608. if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange"))
  4609. { sel = filterSelectionChange(doc, sel, options); }
  4610. var bias = options && options.bias ||
  4611. (cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1);
  4612. setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true));
  4613. if (!(options && options.scroll === false) && doc.cm)
  4614. { ensureCursorVisible(doc.cm); }
  4615. }
  4616. function setSelectionInner(doc, sel) {
  4617. if (sel.equals(doc.sel)) { return }
  4618. doc.sel = sel;
  4619. if (doc.cm) {
  4620. doc.cm.curOp.updateInput = 1;
  4621. doc.cm.curOp.selectionChanged = true;
  4622. signalCursorActivity(doc.cm);
  4623. }
  4624. signalLater(doc, "cursorActivity", doc);
  4625. }
  4626. // Verify that the selection does not partially select any atomic
  4627. // marked ranges.
  4628. function reCheckSelection(doc) {
  4629. setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false));
  4630. }
  4631. // Return a selection that does not partially select any atomic
  4632. // ranges.
  4633. function skipAtomicInSelection(doc, sel, bias, mayClear) {
  4634. var out;
  4635. for (var i = 0; i < sel.ranges.length; i++) {
  4636. var range = sel.ranges[i];
  4637. var old = sel.ranges.length == doc.sel.ranges.length && doc.sel.ranges[i];
  4638. var newAnchor = skipAtomic(doc, range.anchor, old && old.anchor, bias, mayClear);
  4639. var newHead = skipAtomic(doc, range.head, old && old.head, bias, mayClear);
  4640. if (out || newAnchor != range.anchor || newHead != range.head) {
  4641. if (!out) { out = sel.ranges.slice(0, i); }
  4642. out[i] = new Range(newAnchor, newHead);
  4643. }
  4644. }
  4645. return out ? normalizeSelection(doc.cm, out, sel.primIndex) : sel
  4646. }
  4647. function skipAtomicInner(doc, pos, oldPos, dir, mayClear) {
  4648. var line = getLine(doc, pos.line);
  4649. if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) {
  4650. var sp = line.markedSpans[i], m = sp.marker;
  4651. // Determine if we should prevent the cursor being placed to the left/right of an atomic marker
  4652. // Historically this was determined using the inclusiveLeft/Right option, but the new way to control it
  4653. // is with selectLeft/Right
  4654. var preventCursorLeft = ("selectLeft" in m) ? !m.selectLeft : m.inclusiveLeft;
  4655. var preventCursorRight = ("selectRight" in m) ? !m.selectRight : m.inclusiveRight;
  4656. if ((sp.from == null || (preventCursorLeft ? sp.from <= pos.ch : sp.from < pos.ch)) &&
  4657. (sp.to == null || (preventCursorRight ? sp.to >= pos.ch : sp.to > pos.ch))) {
  4658. if (mayClear) {
  4659. signal(m, "beforeCursorEnter");
  4660. if (m.explicitlyCleared) {
  4661. if (!line.markedSpans) { break }
  4662. else {--i; continue}
  4663. }
  4664. }
  4665. if (!m.atomic) { continue }
  4666. if (oldPos) {
  4667. var near = m.find(dir < 0 ? 1 : -1), diff = (void 0);
  4668. if (dir < 0 ? preventCursorRight : preventCursorLeft)
  4669. { near = movePos(doc, near, -dir, near && near.line == pos.line ? line : null); }
  4670. if (near && near.line == pos.line && (diff = cmp(near, oldPos)) && (dir < 0 ? diff < 0 : diff > 0))
  4671. { return skipAtomicInner(doc, near, pos, dir, mayClear) }
  4672. }
  4673. var far = m.find(dir < 0 ? -1 : 1);
  4674. if (dir < 0 ? preventCursorLeft : preventCursorRight)
  4675. { far = movePos(doc, far, dir, far.line == pos.line ? line : null); }
  4676. return far ? skipAtomicInner(doc, far, pos, dir, mayClear) : null
  4677. }
  4678. } }
  4679. return pos
  4680. }
  4681. // Ensure a given position is not inside an atomic range.
  4682. function skipAtomic(doc, pos, oldPos, bias, mayClear) {
  4683. var dir = bias || 1;
  4684. var found = skipAtomicInner(doc, pos, oldPos, dir, mayClear) ||
  4685. (!mayClear && skipAtomicInner(doc, pos, oldPos, dir, true)) ||
  4686. skipAtomicInner(doc, pos, oldPos, -dir, mayClear) ||
  4687. (!mayClear && skipAtomicInner(doc, pos, oldPos, -dir, true));
  4688. if (!found) {
  4689. doc.cantEdit = true;
  4690. return Pos(doc.first, 0)
  4691. }
  4692. return found
  4693. }
  4694. function movePos(doc, pos, dir, line) {
  4695. if (dir < 0 && pos.ch == 0) {
  4696. if (pos.line > doc.first) { return clipPos(doc, Pos(pos.line - 1)) }
  4697. else { return null }
  4698. } else if (dir > 0 && pos.ch == (line || getLine(doc, pos.line)).text.length) {
  4699. if (pos.line < doc.first + doc.size - 1) { return Pos(pos.line + 1, 0) }
  4700. else { return null }
  4701. } else {
  4702. return new Pos(pos.line, pos.ch + dir)
  4703. }
  4704. }
  4705. function selectAll(cm) {
  4706. cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll);
  4707. }
  4708. // UPDATING
  4709. // Allow "beforeChange" event handlers to influence a change
  4710. function filterChange(doc, change, update) {
  4711. var obj = {
  4712. canceled: false,
  4713. from: change.from,
  4714. to: change.to,
  4715. text: change.text,
  4716. origin: change.origin,
  4717. cancel: function () { return obj.canceled = true; }
  4718. };
  4719. if (update) { obj.update = function (from, to, text, origin) {
  4720. if (from) { obj.from = clipPos(doc, from); }
  4721. if (to) { obj.to = clipPos(doc, to); }
  4722. if (text) { obj.text = text; }
  4723. if (origin !== undefined) { obj.origin = origin; }
  4724. }; }
  4725. signal(doc, "beforeChange", doc, obj);
  4726. if (doc.cm) { signal(doc.cm, "beforeChange", doc.cm, obj); }
  4727. if (obj.canceled) {
  4728. if (doc.cm) { doc.cm.curOp.updateInput = 2; }
  4729. return null
  4730. }
  4731. return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin}
  4732. }
  4733. // Apply a change to a document, and add it to the document's
  4734. // history, and propagating it to all linked documents.
  4735. function makeChange(doc, change, ignoreReadOnly) {
  4736. if (doc.cm) {
  4737. if (!doc.cm.curOp) { return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly) }
  4738. if (doc.cm.state.suppressEdits) { return }
  4739. }
  4740. if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) {
  4741. change = filterChange(doc, change, true);
  4742. if (!change) { return }
  4743. }
  4744. // Possibly split or suppress the update based on the presence
  4745. // of read-only spans in its range.
  4746. var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to);
  4747. if (split) {
  4748. for (var i = split.length - 1; i >= 0; --i)
  4749. { makeChangeInner(doc, {from: split[i].from, to: split[i].to, text: i ? [""] : change.text, origin: change.origin}); }
  4750. } else {
  4751. makeChangeInner(doc, change);
  4752. }
  4753. }
  4754. function makeChangeInner(doc, change) {
  4755. if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) { return }
  4756. var selAfter = computeSelAfterChange(doc, change);
  4757. addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN);
  4758. makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change));
  4759. var rebased = [];
  4760. linkedDocs(doc, function (doc, sharedHist) {
  4761. if (!sharedHist && indexOf(rebased, doc.history) == -1) {
  4762. rebaseHist(doc.history, change);
  4763. rebased.push(doc.history);
  4764. }
  4765. makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change));
  4766. });
  4767. }
  4768. // Revert a change stored in a document's history.
  4769. function makeChangeFromHistory(doc, type, allowSelectionOnly) {
  4770. var suppress = doc.cm && doc.cm.state.suppressEdits;
  4771. if (suppress && !allowSelectionOnly) { return }
  4772. var hist = doc.history, event, selAfter = doc.sel;
  4773. var source = type == "undo" ? hist.done : hist.undone, dest = type == "undo" ? hist.undone : hist.done;
  4774. // Verify that there is a useable event (so that ctrl-z won't
  4775. // needlessly clear selection events)
  4776. var i = 0;
  4777. for (; i < source.length; i++) {
  4778. event = source[i];
  4779. if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges)
  4780. { break }
  4781. }
  4782. if (i == source.length) { return }
  4783. hist.lastOrigin = hist.lastSelOrigin = null;
  4784. for (;;) {
  4785. event = source.pop();
  4786. if (event.ranges) {
  4787. pushSelectionToHistory(event, dest);
  4788. if (allowSelectionOnly && !event.equals(doc.sel)) {
  4789. setSelection(doc, event, {clearRedo: false});
  4790. return
  4791. }
  4792. selAfter = event;
  4793. } else if (suppress) {
  4794. source.push(event);
  4795. return
  4796. } else { break }
  4797. }
  4798. // Build up a reverse change object to add to the opposite history
  4799. // stack (redo when undoing, and vice versa).
  4800. var antiChanges = [];
  4801. pushSelectionToHistory(selAfter, dest);
  4802. dest.push({changes: antiChanges, generation: hist.generation});
  4803. hist.generation = event.generation || ++hist.maxGeneration;
  4804. var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange");
  4805. var loop = function ( i ) {
  4806. var change = event.changes[i];
  4807. change.origin = type;
  4808. if (filter && !filterChange(doc, change, false)) {
  4809. source.length = 0;
  4810. return {}
  4811. }
  4812. antiChanges.push(historyChangeFromChange(doc, change));
  4813. var after = i ? computeSelAfterChange(doc, change) : lst(source);
  4814. makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change));
  4815. if (!i && doc.cm) { doc.cm.scrollIntoView({from: change.from, to: changeEnd(change)}); }
  4816. var rebased = [];
  4817. // Propagate to the linked documents
  4818. linkedDocs(doc, function (doc, sharedHist) {
  4819. if (!sharedHist && indexOf(rebased, doc.history) == -1) {
  4820. rebaseHist(doc.history, change);
  4821. rebased.push(doc.history);
  4822. }
  4823. makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change));
  4824. });
  4825. };
  4826. for (var i$1 = event.changes.length - 1; i$1 >= 0; --i$1) {
  4827. var returned = loop( i$1 );
  4828. if ( returned ) return returned.v;
  4829. }
  4830. }
  4831. // Sub-views need their line numbers shifted when text is added
  4832. // above or below them in the parent document.
  4833. function shiftDoc(doc, distance) {
  4834. if (distance == 0) { return }
  4835. doc.first += distance;
  4836. doc.sel = new Selection(map(doc.sel.ranges, function (range) { return new Range(
  4837. Pos(range.anchor.line + distance, range.anchor.ch),
  4838. Pos(range.head.line + distance, range.head.ch)
  4839. ); }), doc.sel.primIndex);
  4840. if (doc.cm) {
  4841. regChange(doc.cm, doc.first, doc.first - distance, distance);
  4842. for (var d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++)
  4843. { regLineChange(doc.cm, l, "gutter"); }
  4844. }
  4845. }
  4846. // More lower-level change function, handling only a single document
  4847. // (not linked ones).
  4848. function makeChangeSingleDoc(doc, change, selAfter, spans) {
  4849. if (doc.cm && !doc.cm.curOp)
  4850. { return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans) }
  4851. if (change.to.line < doc.first) {
  4852. shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line));
  4853. return
  4854. }
  4855. if (change.from.line > doc.lastLine()) { return }
  4856. // Clip the change to the size of this doc
  4857. if (change.from.line < doc.first) {
  4858. var shift = change.text.length - 1 - (doc.first - change.from.line);
  4859. shiftDoc(doc, shift);
  4860. change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch),
  4861. text: [lst(change.text)], origin: change.origin};
  4862. }
  4863. var last = doc.lastLine();
  4864. if (change.to.line > last) {
  4865. change = {from: change.from, to: Pos(last, getLine(doc, last).text.length),
  4866. text: [change.text[0]], origin: change.origin};
  4867. }
  4868. change.removed = getBetween(doc, change.from, change.to);
  4869. if (!selAfter) { selAfter = computeSelAfterChange(doc, change); }
  4870. if (doc.cm) { makeChangeSingleDocInEditor(doc.cm, change, spans); }
  4871. else { updateDoc(doc, change, spans); }
  4872. setSelectionNoUndo(doc, selAfter, sel_dontScroll);
  4873. if (doc.cantEdit && skipAtomic(doc, Pos(doc.firstLine(), 0)))
  4874. { doc.cantEdit = false; }
  4875. }
  4876. // Handle the interaction of a change to a document with the editor
  4877. // that this document is part of.
  4878. function makeChangeSingleDocInEditor(cm, change, spans) {
  4879. var doc = cm.doc, display = cm.display, from = change.from, to = change.to;
  4880. var recomputeMaxLength = false, checkWidthStart = from.line;
  4881. if (!cm.options.lineWrapping) {
  4882. checkWidthStart = lineNo(visualLine(getLine(doc, from.line)));
  4883. doc.iter(checkWidthStart, to.line + 1, function (line) {
  4884. if (line == display.maxLine) {
  4885. recomputeMaxLength = true;
  4886. return true
  4887. }
  4888. });
  4889. }
  4890. if (doc.sel.contains(change.from, change.to) > -1)
  4891. { signalCursorActivity(cm); }
  4892. updateDoc(doc, change, spans, estimateHeight(cm));
  4893. if (!cm.options.lineWrapping) {
  4894. doc.iter(checkWidthStart, from.line + change.text.length, function (line) {
  4895. var len = lineLength(line);
  4896. if (len > display.maxLineLength) {
  4897. display.maxLine = line;
  4898. display.maxLineLength = len;
  4899. display.maxLineChanged = true;
  4900. recomputeMaxLength = false;
  4901. }
  4902. });
  4903. if (recomputeMaxLength) { cm.curOp.updateMaxLine = true; }
  4904. }
  4905. retreatFrontier(doc, from.line);
  4906. startWorker(cm, 400);
  4907. var lendiff = change.text.length - (to.line - from.line) - 1;
  4908. // Remember that these lines changed, for updating the display
  4909. if (change.full)
  4910. { regChange(cm); }
  4911. else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change))
  4912. { regLineChange(cm, from.line, "text"); }
  4913. else
  4914. { regChange(cm, from.line, to.line + 1, lendiff); }
  4915. var changesHandler = hasHandler(cm, "changes"), changeHandler = hasHandler(cm, "change");
  4916. if (changeHandler || changesHandler) {
  4917. var obj = {
  4918. from: from, to: to,
  4919. text: change.text,
  4920. removed: change.removed,
  4921. origin: change.origin
  4922. };
  4923. if (changeHandler) { signalLater(cm, "change", cm, obj); }
  4924. if (changesHandler) { (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj); }
  4925. }
  4926. cm.display.selForContextMenu = null;
  4927. }
  4928. function replaceRange(doc, code, from, to, origin) {
  4929. var assign;
  4930. if (!to) { to = from; }
  4931. if (cmp(to, from) < 0) { (assign = [to, from], from = assign[0], to = assign[1]); }
  4932. if (typeof code == "string") { code = doc.splitLines(code); }
  4933. makeChange(doc, {from: from, to: to, text: code, origin: origin});
  4934. }
  4935. // Rebasing/resetting history to deal with externally-sourced changes
  4936. function rebaseHistSelSingle(pos, from, to, diff) {
  4937. if (to < pos.line) {
  4938. pos.line += diff;
  4939. } else if (from < pos.line) {
  4940. pos.line = from;
  4941. pos.ch = 0;
  4942. }
  4943. }
  4944. // Tries to rebase an array of history events given a change in the
  4945. // document. If the change touches the same lines as the event, the
  4946. // event, and everything 'behind' it, is discarded. If the change is
  4947. // before the event, the event's positions are updated. Uses a
  4948. // copy-on-write scheme for the positions, to avoid having to
  4949. // reallocate them all on every rebase, but also avoid problems with
  4950. // shared position objects being unsafely updated.
  4951. function rebaseHistArray(array, from, to, diff) {
  4952. for (var i = 0; i < array.length; ++i) {
  4953. var sub = array[i], ok = true;
  4954. if (sub.ranges) {
  4955. if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true; }
  4956. for (var j = 0; j < sub.ranges.length; j++) {
  4957. rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff);
  4958. rebaseHistSelSingle(sub.ranges[j].head, from, to, diff);
  4959. }
  4960. continue
  4961. }
  4962. for (var j$1 = 0; j$1 < sub.changes.length; ++j$1) {
  4963. var cur = sub.changes[j$1];
  4964. if (to < cur.from.line) {
  4965. cur.from = Pos(cur.from.line + diff, cur.from.ch);
  4966. cur.to = Pos(cur.to.line + diff, cur.to.ch);
  4967. } else if (from <= cur.to.line) {
  4968. ok = false;
  4969. break
  4970. }
  4971. }
  4972. if (!ok) {
  4973. array.splice(0, i + 1);
  4974. i = 0;
  4975. }
  4976. }
  4977. }
  4978. function rebaseHist(hist, change) {
  4979. var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1;
  4980. rebaseHistArray(hist.done, from, to, diff);
  4981. rebaseHistArray(hist.undone, from, to, diff);
  4982. }
  4983. // Utility for applying a change to a line by handle or number,
  4984. // returning the number and optionally registering the line as
  4985. // changed.
  4986. function changeLine(doc, handle, changeType, op) {
  4987. var no = handle, line = handle;
  4988. if (typeof handle == "number") { line = getLine(doc, clipLine(doc, handle)); }
  4989. else { no = lineNo(handle); }
  4990. if (no == null) { return null }
  4991. if (op(line, no) && doc.cm) { regLineChange(doc.cm, no, changeType); }
  4992. return line
  4993. }
  4994. // The document is represented as a BTree consisting of leaves, with
  4995. // chunk of lines in them, and branches, with up to ten leaves or
  4996. // other branch nodes below them. The top node is always a branch
  4997. // node, and is the document object itself (meaning it has
  4998. // additional methods and properties).
  4999. //
  5000. // All nodes have parent links. The tree is used both to go from
  5001. // line numbers to line objects, and to go from objects to numbers.
  5002. // It also indexes by height, and is used to convert between height
  5003. // and line object, and to find the total height of the document.
  5004. //
  5005. // See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html
  5006. function LeafChunk(lines) {
  5007. var this$1 = this;
  5008. this.lines = lines;
  5009. this.parent = null;
  5010. var height = 0;
  5011. for (var i = 0; i < lines.length; ++i) {
  5012. lines[i].parent = this$1;
  5013. height += lines[i].height;
  5014. }
  5015. this.height = height;
  5016. }
  5017. LeafChunk.prototype = {
  5018. chunkSize: function() { return this.lines.length },
  5019. // Remove the n lines at offset 'at'.
  5020. removeInner: function(at, n) {
  5021. var this$1 = this;
  5022. for (var i = at, e = at + n; i < e; ++i) {
  5023. var line = this$1.lines[i];
  5024. this$1.height -= line.height;
  5025. cleanUpLine(line);
  5026. signalLater(line, "delete");
  5027. }
  5028. this.lines.splice(at, n);
  5029. },
  5030. // Helper used to collapse a small branch into a single leaf.
  5031. collapse: function(lines) {
  5032. lines.push.apply(lines, this.lines);
  5033. },
  5034. // Insert the given array of lines at offset 'at', count them as
  5035. // having the given height.
  5036. insertInner: function(at, lines, height) {
  5037. var this$1 = this;
  5038. this.height += height;
  5039. this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at));
  5040. for (var i = 0; i < lines.length; ++i) { lines[i].parent = this$1; }
  5041. },
  5042. // Used to iterate over a part of the tree.
  5043. iterN: function(at, n, op) {
  5044. var this$1 = this;
  5045. for (var e = at + n; at < e; ++at)
  5046. { if (op(this$1.lines[at])) { return true } }
  5047. }
  5048. };
  5049. function BranchChunk(children) {
  5050. var this$1 = this;
  5051. this.children = children;
  5052. var size = 0, height = 0;
  5053. for (var i = 0; i < children.length; ++i) {
  5054. var ch = children[i];
  5055. size += ch.chunkSize(); height += ch.height;
  5056. ch.parent = this$1;
  5057. }
  5058. this.size = size;
  5059. this.height = height;
  5060. this.parent = null;
  5061. }
  5062. BranchChunk.prototype = {
  5063. chunkSize: function() { return this.size },
  5064. removeInner: function(at, n) {
  5065. var this$1 = this;
  5066. this.size -= n;
  5067. for (var i = 0; i < this.children.length; ++i) {
  5068. var child = this$1.children[i], sz = child.chunkSize();
  5069. if (at < sz) {
  5070. var rm = Math.min(n, sz - at), oldHeight = child.height;
  5071. child.removeInner(at, rm);
  5072. this$1.height -= oldHeight - child.height;
  5073. if (sz == rm) { this$1.children.splice(i--, 1); child.parent = null; }
  5074. if ((n -= rm) == 0) { break }
  5075. at = 0;
  5076. } else { at -= sz; }
  5077. }
  5078. // If the result is smaller than 25 lines, ensure that it is a
  5079. // single leaf node.
  5080. if (this.size - n < 25 &&
  5081. (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) {
  5082. var lines = [];
  5083. this.collapse(lines);
  5084. this.children = [new LeafChunk(lines)];
  5085. this.children[0].parent = this;
  5086. }
  5087. },
  5088. collapse: function(lines) {
  5089. var this$1 = this;
  5090. for (var i = 0; i < this.children.length; ++i) { this$1.children[i].collapse(lines); }
  5091. },
  5092. insertInner: function(at, lines, height) {
  5093. var this$1 = this;
  5094. this.size += lines.length;
  5095. this.height += height;
  5096. for (var i = 0; i < this.children.length; ++i) {
  5097. var child = this$1.children[i], sz = child.chunkSize();
  5098. if (at <= sz) {
  5099. child.insertInner(at, lines, height);
  5100. if (child.lines && child.lines.length > 50) {
  5101. // To avoid memory thrashing when child.lines is huge (e.g. first view of a large file), it's never spliced.
  5102. // Instead, small slices are taken. They're taken in order because sequential memory accesses are fastest.
  5103. var remaining = child.lines.length % 25 + 25;
  5104. for (var pos = remaining; pos < child.lines.length;) {
  5105. var leaf = new LeafChunk(child.lines.slice(pos, pos += 25));
  5106. child.height -= leaf.height;
  5107. this$1.children.splice(++i, 0, leaf);
  5108. leaf.parent = this$1;
  5109. }
  5110. child.lines = child.lines.slice(0, remaining);
  5111. this$1.maybeSpill();
  5112. }
  5113. break
  5114. }
  5115. at -= sz;
  5116. }
  5117. },
  5118. // When a node has grown, check whether it should be split.
  5119. maybeSpill: function() {
  5120. if (this.children.length <= 10) { return }
  5121. var me = this;
  5122. do {
  5123. var spilled = me.children.splice(me.children.length - 5, 5);
  5124. var sibling = new BranchChunk(spilled);
  5125. if (!me.parent) { // Become the parent node
  5126. var copy = new BranchChunk(me.children);
  5127. copy.parent = me;
  5128. me.children = [copy, sibling];
  5129. me = copy;
  5130. } else {
  5131. me.size -= sibling.size;
  5132. me.height -= sibling.height;
  5133. var myIndex = indexOf(me.parent.children, me);
  5134. me.parent.children.splice(myIndex + 1, 0, sibling);
  5135. }
  5136. sibling.parent = me.parent;
  5137. } while (me.children.length > 10)
  5138. me.parent.maybeSpill();
  5139. },
  5140. iterN: function(at, n, op) {
  5141. var this$1 = this;
  5142. for (var i = 0; i < this.children.length; ++i) {
  5143. var child = this$1.children[i], sz = child.chunkSize();
  5144. if (at < sz) {
  5145. var used = Math.min(n, sz - at);
  5146. if (child.iterN(at, used, op)) { return true }
  5147. if ((n -= used) == 0) { break }
  5148. at = 0;
  5149. } else { at -= sz; }
  5150. }
  5151. }
  5152. };
  5153. // Line widgets are block elements displayed above or below a line.
  5154. var LineWidget = function(doc, node, options) {
  5155. var this$1 = this;
  5156. if (options) { for (var opt in options) { if (options.hasOwnProperty(opt))
  5157. { this$1[opt] = options[opt]; } } }
  5158. this.doc = doc;
  5159. this.node = node;
  5160. };
  5161. LineWidget.prototype.clear = function () {
  5162. var this$1 = this;
  5163. var cm = this.doc.cm, ws = this.line.widgets, line = this.line, no = lineNo(line);
  5164. if (no == null || !ws) { return }
  5165. for (var i = 0; i < ws.length; ++i) { if (ws[i] == this$1) { ws.splice(i--, 1); } }
  5166. if (!ws.length) { line.widgets = null; }
  5167. var height = widgetHeight(this);
  5168. updateLineHeight(line, Math.max(0, line.height - height));
  5169. if (cm) {
  5170. runInOp(cm, function () {
  5171. adjustScrollWhenAboveVisible(cm, line, -height);
  5172. regLineChange(cm, no, "widget");
  5173. });
  5174. signalLater(cm, "lineWidgetCleared", cm, this, no);
  5175. }
  5176. };
  5177. LineWidget.prototype.changed = function () {
  5178. var this$1 = this;
  5179. var oldH = this.height, cm = this.doc.cm, line = this.line;
  5180. this.height = null;
  5181. var diff = widgetHeight(this) - oldH;
  5182. if (!diff) { return }
  5183. if (!lineIsHidden(this.doc, line)) { updateLineHeight(line, line.height + diff); }
  5184. if (cm) {
  5185. runInOp(cm, function () {
  5186. cm.curOp.forceUpdate = true;
  5187. adjustScrollWhenAboveVisible(cm, line, diff);
  5188. signalLater(cm, "lineWidgetChanged", cm, this$1, lineNo(line));
  5189. });
  5190. }
  5191. };
  5192. eventMixin(LineWidget);
  5193. function adjustScrollWhenAboveVisible(cm, line, diff) {
  5194. if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop))
  5195. { addToScrollTop(cm, diff); }
  5196. }
  5197. function addLineWidget(doc, handle, node, options) {
  5198. var widget = new LineWidget(doc, node, options);
  5199. var cm = doc.cm;
  5200. if (cm && widget.noHScroll) { cm.display.alignWidgets = true; }
  5201. changeLine(doc, handle, "widget", function (line) {
  5202. var widgets = line.widgets || (line.widgets = []);
  5203. if (widget.insertAt == null) { widgets.push(widget); }
  5204. else { widgets.splice(Math.min(widgets.length - 1, Math.max(0, widget.insertAt)), 0, widget); }
  5205. widget.line = line;
  5206. if (cm && !lineIsHidden(doc, line)) {
  5207. var aboveVisible = heightAtLine(line) < doc.scrollTop;
  5208. updateLineHeight(line, line.height + widgetHeight(widget));
  5209. if (aboveVisible) { addToScrollTop(cm, widget.height); }
  5210. cm.curOp.forceUpdate = true;
  5211. }
  5212. return true
  5213. });
  5214. if (cm) { signalLater(cm, "lineWidgetAdded", cm, widget, typeof handle == "number" ? handle : lineNo(handle)); }
  5215. return widget
  5216. }
  5217. // TEXTMARKERS
  5218. // Created with markText and setBookmark methods. A TextMarker is a
  5219. // handle that can be used to clear or find a marked position in the
  5220. // document. Line objects hold arrays (markedSpans) containing
  5221. // {from, to, marker} object pointing to such marker objects, and
  5222. // indicating that such a marker is present on that line. Multiple
  5223. // lines may point to the same marker when it spans across lines.
  5224. // The spans will have null for their from/to properties when the
  5225. // marker continues beyond the start/end of the line. Markers have
  5226. // links back to the lines they currently touch.
  5227. // Collapsed markers have unique ids, in order to be able to order
  5228. // them, which is needed for uniquely determining an outer marker
  5229. // when they overlap (they may nest, but not partially overlap).
  5230. var nextMarkerId = 0;
  5231. var TextMarker = function(doc, type) {
  5232. this.lines = [];
  5233. this.type = type;
  5234. this.doc = doc;
  5235. this.id = ++nextMarkerId;
  5236. };
  5237. // Clear the marker.
  5238. TextMarker.prototype.clear = function () {
  5239. var this$1 = this;
  5240. if (this.explicitlyCleared) { return }
  5241. var cm = this.doc.cm, withOp = cm && !cm.curOp;
  5242. if (withOp) { startOperation(cm); }
  5243. if (hasHandler(this, "clear")) {
  5244. var found = this.find();
  5245. if (found) { signalLater(this, "clear", found.from, found.to); }
  5246. }
  5247. var min = null, max = null;
  5248. for (var i = 0; i < this.lines.length; ++i) {
  5249. var line = this$1.lines[i];
  5250. var span = getMarkedSpanFor(line.markedSpans, this$1);
  5251. if (cm && !this$1.collapsed) { regLineChange(cm, lineNo(line), "text"); }
  5252. else if (cm) {
  5253. if (span.to != null) { max = lineNo(line); }
  5254. if (span.from != null) { min = lineNo(line); }
  5255. }
  5256. line.markedSpans = removeMarkedSpan(line.markedSpans, span);
  5257. if (span.from == null && this$1.collapsed && !lineIsHidden(this$1.doc, line) && cm)
  5258. { updateLineHeight(line, textHeight(cm.display)); }
  5259. }
  5260. if (cm && this.collapsed && !cm.options.lineWrapping) { for (var i$1 = 0; i$1 < this.lines.length; ++i$1) {
  5261. var visual = visualLine(this$1.lines[i$1]), len = lineLength(visual);
  5262. if (len > cm.display.maxLineLength) {
  5263. cm.display.maxLine = visual;
  5264. cm.display.maxLineLength = len;
  5265. cm.display.maxLineChanged = true;
  5266. }
  5267. } }
  5268. if (min != null && cm && this.collapsed) { regChange(cm, min, max + 1); }
  5269. this.lines.length = 0;
  5270. this.explicitlyCleared = true;
  5271. if (this.atomic && this.doc.cantEdit) {
  5272. this.doc.cantEdit = false;
  5273. if (cm) { reCheckSelection(cm.doc); }
  5274. }
  5275. if (cm) { signalLater(cm, "markerCleared", cm, this, min, max); }
  5276. if (withOp) { endOperation(cm); }
  5277. if (this.parent) { this.parent.clear(); }
  5278. };
  5279. // Find the position of the marker in the document. Returns a {from,
  5280. // to} object by default. Side can be passed to get a specific side
  5281. // -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the
  5282. // Pos objects returned contain a line object, rather than a line
  5283. // number (used to prevent looking up the same line twice).
  5284. TextMarker.prototype.find = function (side, lineObj) {
  5285. var this$1 = this;
  5286. if (side == null && this.type == "bookmark") { side = 1; }
  5287. var from, to;
  5288. for (var i = 0; i < this.lines.length; ++i) {
  5289. var line = this$1.lines[i];
  5290. var span = getMarkedSpanFor(line.markedSpans, this$1);
  5291. if (span.from != null) {
  5292. from = Pos(lineObj ? line : lineNo(line), span.from);
  5293. if (side == -1) { return from }
  5294. }
  5295. if (span.to != null) {
  5296. to = Pos(lineObj ? line : lineNo(line), span.to);
  5297. if (side == 1) { return to }
  5298. }
  5299. }
  5300. return from && {from: from, to: to}
  5301. };
  5302. // Signals that the marker's widget changed, and surrounding layout
  5303. // should be recomputed.
  5304. TextMarker.prototype.changed = function () {
  5305. var this$1 = this;
  5306. var pos = this.find(-1, true), widget = this, cm = this.doc.cm;
  5307. if (!pos || !cm) { return }
  5308. runInOp(cm, function () {
  5309. var line = pos.line, lineN = lineNo(pos.line);
  5310. var view = findViewForLine(cm, lineN);
  5311. if (view) {
  5312. clearLineMeasurementCacheFor(view);
  5313. cm.curOp.selectionChanged = cm.curOp.forceUpdate = true;
  5314. }
  5315. cm.curOp.updateMaxLine = true;
  5316. if (!lineIsHidden(widget.doc, line) && widget.height != null) {
  5317. var oldHeight = widget.height;
  5318. widget.height = null;
  5319. var dHeight = widgetHeight(widget) - oldHeight;
  5320. if (dHeight)
  5321. { updateLineHeight(line, line.height + dHeight); }
  5322. }
  5323. signalLater(cm, "markerChanged", cm, this$1);
  5324. });
  5325. };
  5326. TextMarker.prototype.attachLine = function (line) {
  5327. if (!this.lines.length && this.doc.cm) {
  5328. var op = this.doc.cm.curOp;
  5329. if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1)
  5330. { (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this); }
  5331. }
  5332. this.lines.push(line);
  5333. };
  5334. TextMarker.prototype.detachLine = function (line) {
  5335. this.lines.splice(indexOf(this.lines, line), 1);
  5336. if (!this.lines.length && this.doc.cm) {
  5337. var op = this.doc.cm.curOp
  5338. ;(op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this);
  5339. }
  5340. };
  5341. eventMixin(TextMarker);
  5342. // Create a marker, wire it up to the right lines, and
  5343. function markText(doc, from, to, options, type) {
  5344. // Shared markers (across linked documents) are handled separately
  5345. // (markTextShared will call out to this again, once per
  5346. // document).
  5347. if (options && options.shared) { return markTextShared(doc, from, to, options, type) }
  5348. // Ensure we are in an operation.
  5349. if (doc.cm && !doc.cm.curOp) { return operation(doc.cm, markText)(doc, from, to, options, type) }
  5350. var marker = new TextMarker(doc, type), diff = cmp(from, to);
  5351. if (options) { copyObj(options, marker, false); }
  5352. // Don't connect empty markers unless clearWhenEmpty is false
  5353. if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false)
  5354. { return marker }
  5355. if (marker.replacedWith) {
  5356. // Showing up as a widget implies collapsed (widget replaces text)
  5357. marker.collapsed = true;
  5358. marker.widgetNode = eltP("span", [marker.replacedWith], "CodeMirror-widget");
  5359. if (!options.handleMouseEvents) { marker.widgetNode.setAttribute("cm-ignore-events", "true"); }
  5360. if (options.insertLeft) { marker.widgetNode.insertLeft = true; }
  5361. }
  5362. if (marker.collapsed) {
  5363. if (conflictingCollapsedRange(doc, from.line, from, to, marker) ||
  5364. from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker))
  5365. { throw new Error("Inserting collapsed marker partially overlapping an existing one") }
  5366. seeCollapsedSpans();
  5367. }
  5368. if (marker.addToHistory)
  5369. { addChangeToHistory(doc, {from: from, to: to, origin: "markText"}, doc.sel, NaN); }
  5370. var curLine = from.line, cm = doc.cm, updateMaxLine;
  5371. doc.iter(curLine, to.line + 1, function (line) {
  5372. if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine)
  5373. { updateMaxLine = true; }
  5374. if (marker.collapsed && curLine != from.line) { updateLineHeight(line, 0); }
  5375. addMarkedSpan(line, new MarkedSpan(marker,
  5376. curLine == from.line ? from.ch : null,
  5377. curLine == to.line ? to.ch : null));
  5378. ++curLine;
  5379. });
  5380. // lineIsHidden depends on the presence of the spans, so needs a second pass
  5381. if (marker.collapsed) { doc.iter(from.line, to.line + 1, function (line) {
  5382. if (lineIsHidden(doc, line)) { updateLineHeight(line, 0); }
  5383. }); }
  5384. if (marker.clearOnEnter) { on(marker, "beforeCursorEnter", function () { return marker.clear(); }); }
  5385. if (marker.readOnly) {
  5386. seeReadOnlySpans();
  5387. if (doc.history.done.length || doc.history.undone.length)
  5388. { doc.clearHistory(); }
  5389. }
  5390. if (marker.collapsed) {
  5391. marker.id = ++nextMarkerId;
  5392. marker.atomic = true;
  5393. }
  5394. if (cm) {
  5395. // Sync editor state
  5396. if (updateMaxLine) { cm.curOp.updateMaxLine = true; }
  5397. if (marker.collapsed)
  5398. { regChange(cm, from.line, to.line + 1); }
  5399. else if (marker.className || marker.startStyle || marker.endStyle || marker.css ||
  5400. marker.attributes || marker.title)
  5401. { for (var i = from.line; i <= to.line; i++) { regLineChange(cm, i, "text"); } }
  5402. if (marker.atomic) { reCheckSelection(cm.doc); }
  5403. signalLater(cm, "markerAdded", cm, marker);
  5404. }
  5405. return marker
  5406. }
  5407. // SHARED TEXTMARKERS
  5408. // A shared marker spans multiple linked documents. It is
  5409. // implemented as a meta-marker-object controlling multiple normal
  5410. // markers.
  5411. var SharedTextMarker = function(markers, primary) {
  5412. var this$1 = this;
  5413. this.markers = markers;
  5414. this.primary = primary;
  5415. for (var i = 0; i < markers.length; ++i)
  5416. { markers[i].parent = this$1; }
  5417. };
  5418. SharedTextMarker.prototype.clear = function () {
  5419. var this$1 = this;
  5420. if (this.explicitlyCleared) { return }
  5421. this.explicitlyCleared = true;
  5422. for (var i = 0; i < this.markers.length; ++i)
  5423. { this$1.markers[i].clear(); }
  5424. signalLater(this, "clear");
  5425. };
  5426. SharedTextMarker.prototype.find = function (side, lineObj) {
  5427. return this.primary.find(side, lineObj)
  5428. };
  5429. eventMixin(SharedTextMarker);
  5430. function markTextShared(doc, from, to, options, type) {
  5431. options = copyObj(options);
  5432. options.shared = false;
  5433. var markers = [markText(doc, from, to, options, type)], primary = markers[0];
  5434. var widget = options.widgetNode;
  5435. linkedDocs(doc, function (doc) {
  5436. if (widget) { options.widgetNode = widget.cloneNode(true); }
  5437. markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type));
  5438. for (var i = 0; i < doc.linked.length; ++i)
  5439. { if (doc.linked[i].isParent) { return } }
  5440. primary = lst(markers);
  5441. });
  5442. return new SharedTextMarker(markers, primary)
  5443. }
  5444. function findSharedMarkers(doc) {
  5445. return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())), function (m) { return m.parent; })
  5446. }
  5447. function copySharedMarkers(doc, markers) {
  5448. for (var i = 0; i < markers.length; i++) {
  5449. var marker = markers[i], pos = marker.find();
  5450. var mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to);
  5451. if (cmp(mFrom, mTo)) {
  5452. var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type);
  5453. marker.markers.push(subMark);
  5454. subMark.parent = marker;
  5455. }
  5456. }
  5457. }
  5458. function detachSharedMarkers(markers) {
  5459. var loop = function ( i ) {
  5460. var marker = markers[i], linked = [marker.primary.doc];
  5461. linkedDocs(marker.primary.doc, function (d) { return linked.push(d); });
  5462. for (var j = 0; j < marker.markers.length; j++) {
  5463. var subMarker = marker.markers[j];
  5464. if (indexOf(linked, subMarker.doc) == -1) {
  5465. subMarker.parent = null;
  5466. marker.markers.splice(j--, 1);
  5467. }
  5468. }
  5469. };
  5470. for (var i = 0; i < markers.length; i++) loop( i );
  5471. }
  5472. var nextDocId = 0;
  5473. var Doc = function(text, mode, firstLine, lineSep, direction) {
  5474. if (!(this instanceof Doc)) { return new Doc(text, mode, firstLine, lineSep, direction) }
  5475. if (firstLine == null) { firstLine = 0; }
  5476. BranchChunk.call(this, [new LeafChunk([new Line("", null)])]);
  5477. this.first = firstLine;
  5478. this.scrollTop = this.scrollLeft = 0;
  5479. this.cantEdit = false;
  5480. this.cleanGeneration = 1;
  5481. this.modeFrontier = this.highlightFrontier = firstLine;
  5482. var start = Pos(firstLine, 0);
  5483. this.sel = simpleSelection(start);
  5484. this.history = new History(null);
  5485. this.id = ++nextDocId;
  5486. this.modeOption = mode;
  5487. this.lineSep = lineSep;
  5488. this.direction = (direction == "rtl") ? "rtl" : "ltr";
  5489. this.extend = false;
  5490. if (typeof text == "string") { text = this.splitLines(text); }
  5491. updateDoc(this, {from: start, to: start, text: text});
  5492. setSelection(this, simpleSelection(start), sel_dontScroll);
  5493. };
  5494. Doc.prototype = createObj(BranchChunk.prototype, {
  5495. constructor: Doc,
  5496. // Iterate over the document. Supports two forms -- with only one
  5497. // argument, it calls that for each line in the document. With
  5498. // three, it iterates over the range given by the first two (with
  5499. // the second being non-inclusive).
  5500. iter: function(from, to, op) {
  5501. if (op) { this.iterN(from - this.first, to - from, op); }
  5502. else { this.iterN(this.first, this.first + this.size, from); }
  5503. },
  5504. // Non-public interface for adding and removing lines.
  5505. insert: function(at, lines) {
  5506. var height = 0;
  5507. for (var i = 0; i < lines.length; ++i) { height += lines[i].height; }
  5508. this.insertInner(at - this.first, lines, height);
  5509. },
  5510. remove: function(at, n) { this.removeInner(at - this.first, n); },
  5511. // From here, the methods are part of the public interface. Most
  5512. // are also available from CodeMirror (editor) instances.
  5513. getValue: function(lineSep) {
  5514. var lines = getLines(this, this.first, this.first + this.size);
  5515. if (lineSep === false) { return lines }
  5516. return lines.join(lineSep || this.lineSeparator())
  5517. },
  5518. setValue: docMethodOp(function(code) {
  5519. var top = Pos(this.first, 0), last = this.first + this.size - 1;
  5520. makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length),
  5521. text: this.splitLines(code), origin: "setValue", full: true}, true);
  5522. if (this.cm) { scrollToCoords(this.cm, 0, 0); }
  5523. setSelection(this, simpleSelection(top), sel_dontScroll);
  5524. }),
  5525. replaceRange: function(code, from, to, origin) {
  5526. from = clipPos(this, from);
  5527. to = to ? clipPos(this, to) : from;
  5528. replaceRange(this, code, from, to, origin);
  5529. },
  5530. getRange: function(from, to, lineSep) {
  5531. var lines = getBetween(this, clipPos(this, from), clipPos(this, to));
  5532. if (lineSep === false) { return lines }
  5533. return lines.join(lineSep || this.lineSeparator())
  5534. },
  5535. getLine: function(line) {var l = this.getLineHandle(line); return l && l.text},
  5536. getLineHandle: function(line) {if (isLine(this, line)) { return getLine(this, line) }},
  5537. getLineNumber: function(line) {return lineNo(line)},
  5538. getLineHandleVisualStart: function(line) {
  5539. if (typeof line == "number") { line = getLine(this, line); }
  5540. return visualLine(line)
  5541. },
  5542. lineCount: function() {return this.size},
  5543. firstLine: function() {return this.first},
  5544. lastLine: function() {return this.first + this.size - 1},
  5545. clipPos: function(pos) {return clipPos(this, pos)},
  5546. getCursor: function(start) {
  5547. var range$$1 = this.sel.primary(), pos;
  5548. if (start == null || start == "head") { pos = range$$1.head; }
  5549. else if (start == "anchor") { pos = range$$1.anchor; }
  5550. else if (start == "end" || start == "to" || start === false) { pos = range$$1.to(); }
  5551. else { pos = range$$1.from(); }
  5552. return pos
  5553. },
  5554. listSelections: function() { return this.sel.ranges },
  5555. somethingSelected: function() {return this.sel.somethingSelected()},
  5556. setCursor: docMethodOp(function(line, ch, options) {
  5557. setSimpleSelection(this, clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line), null, options);
  5558. }),
  5559. setSelection: docMethodOp(function(anchor, head, options) {
  5560. setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options);
  5561. }),
  5562. extendSelection: docMethodOp(function(head, other, options) {
  5563. extendSelection(this, clipPos(this, head), other && clipPos(this, other), options);
  5564. }),
  5565. extendSelections: docMethodOp(function(heads, options) {
  5566. extendSelections(this, clipPosArray(this, heads), options);
  5567. }),
  5568. extendSelectionsBy: docMethodOp(function(f, options) {
  5569. var heads = map(this.sel.ranges, f);
  5570. extendSelections(this, clipPosArray(this, heads), options);
  5571. }),
  5572. setSelections: docMethodOp(function(ranges, primary, options) {
  5573. var this$1 = this;
  5574. if (!ranges.length) { return }
  5575. var out = [];
  5576. for (var i = 0; i < ranges.length; i++)
  5577. { out[i] = new Range(clipPos(this$1, ranges[i].anchor),
  5578. clipPos(this$1, ranges[i].head)); }
  5579. if (primary == null) { primary = Math.min(ranges.length - 1, this.sel.primIndex); }
  5580. setSelection(this, normalizeSelection(this.cm, out, primary), options);
  5581. }),
  5582. addSelection: docMethodOp(function(anchor, head, options) {
  5583. var ranges = this.sel.ranges.slice(0);
  5584. ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor)));
  5585. setSelection(this, normalizeSelection(this.cm, ranges, ranges.length - 1), options);
  5586. }),
  5587. getSelection: function(lineSep) {
  5588. var this$1 = this;
  5589. var ranges = this.sel.ranges, lines;
  5590. for (var i = 0; i < ranges.length; i++) {
  5591. var sel = getBetween(this$1, ranges[i].from(), ranges[i].to());
  5592. lines = lines ? lines.concat(sel) : sel;
  5593. }
  5594. if (lineSep === false) { return lines }
  5595. else { return lines.join(lineSep || this.lineSeparator()) }
  5596. },
  5597. getSelections: function(lineSep) {
  5598. var this$1 = this;
  5599. var parts = [], ranges = this.sel.ranges;
  5600. for (var i = 0; i < ranges.length; i++) {
  5601. var sel = getBetween(this$1, ranges[i].from(), ranges[i].to());
  5602. if (lineSep !== false) { sel = sel.join(lineSep || this$1.lineSeparator()); }
  5603. parts[i] = sel;
  5604. }
  5605. return parts
  5606. },
  5607. replaceSelection: function(code, collapse, origin) {
  5608. var dup = [];
  5609. for (var i = 0; i < this.sel.ranges.length; i++)
  5610. { dup[i] = code; }
  5611. this.replaceSelections(dup, collapse, origin || "+input");
  5612. },
  5613. replaceSelections: docMethodOp(function(code, collapse, origin) {
  5614. var this$1 = this;
  5615. var changes = [], sel = this.sel;
  5616. for (var i = 0; i < sel.ranges.length; i++) {
  5617. var range$$1 = sel.ranges[i];
  5618. changes[i] = {from: range$$1.from(), to: range$$1.to(), text: this$1.splitLines(code[i]), origin: origin};
  5619. }
  5620. var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse);
  5621. for (var i$1 = changes.length - 1; i$1 >= 0; i$1--)
  5622. { makeChange(this$1, changes[i$1]); }
  5623. if (newSel) { setSelectionReplaceHistory(this, newSel); }
  5624. else if (this.cm) { ensureCursorVisible(this.cm); }
  5625. }),
  5626. undo: docMethodOp(function() {makeChangeFromHistory(this, "undo");}),
  5627. redo: docMethodOp(function() {makeChangeFromHistory(this, "redo");}),
  5628. undoSelection: docMethodOp(function() {makeChangeFromHistory(this, "undo", true);}),
  5629. redoSelection: docMethodOp(function() {makeChangeFromHistory(this, "redo", true);}),
  5630. setExtending: function(val) {this.extend = val;},
  5631. getExtending: function() {return this.extend},
  5632. historySize: function() {
  5633. var hist = this.history, done = 0, undone = 0;
  5634. for (var i = 0; i < hist.done.length; i++) { if (!hist.done[i].ranges) { ++done; } }
  5635. for (var i$1 = 0; i$1 < hist.undone.length; i$1++) { if (!hist.undone[i$1].ranges) { ++undone; } }
  5636. return {undo: done, redo: undone}
  5637. },
  5638. clearHistory: function() {this.history = new History(this.history.maxGeneration);},
  5639. markClean: function() {
  5640. this.cleanGeneration = this.changeGeneration(true);
  5641. },
  5642. changeGeneration: function(forceSplit) {
  5643. if (forceSplit)
  5644. { this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null; }
  5645. return this.history.generation
  5646. },
  5647. isClean: function (gen) {
  5648. return this.history.generation == (gen || this.cleanGeneration)
  5649. },
  5650. getHistory: function() {
  5651. return {done: copyHistoryArray(this.history.done),
  5652. undone: copyHistoryArray(this.history.undone)}
  5653. },
  5654. setHistory: function(histData) {
  5655. var hist = this.history = new History(this.history.maxGeneration);
  5656. hist.done = copyHistoryArray(histData.done.slice(0), null, true);
  5657. hist.undone = copyHistoryArray(histData.undone.slice(0), null, true);
  5658. },
  5659. setGutterMarker: docMethodOp(function(line, gutterID, value) {
  5660. return changeLine(this, line, "gutter", function (line) {
  5661. var markers = line.gutterMarkers || (line.gutterMarkers = {});
  5662. markers[gutterID] = value;
  5663. if (!value && isEmpty(markers)) { line.gutterMarkers = null; }
  5664. return true
  5665. })
  5666. }),
  5667. clearGutter: docMethodOp(function(gutterID) {
  5668. var this$1 = this;
  5669. this.iter(function (line) {
  5670. if (line.gutterMarkers && line.gutterMarkers[gutterID]) {
  5671. changeLine(this$1, line, "gutter", function () {
  5672. line.gutterMarkers[gutterID] = null;
  5673. if (isEmpty(line.gutterMarkers)) { line.gutterMarkers = null; }
  5674. return true
  5675. });
  5676. }
  5677. });
  5678. }),
  5679. lineInfo: function(line) {
  5680. var n;
  5681. if (typeof line == "number") {
  5682. if (!isLine(this, line)) { return null }
  5683. n = line;
  5684. line = getLine(this, line);
  5685. if (!line) { return null }
  5686. } else {
  5687. n = lineNo(line);
  5688. if (n == null) { return null }
  5689. }
  5690. return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers,
  5691. textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass,
  5692. widgets: line.widgets}
  5693. },
  5694. addLineClass: docMethodOp(function(handle, where, cls) {
  5695. return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) {
  5696. var prop = where == "text" ? "textClass"
  5697. : where == "background" ? "bgClass"
  5698. : where == "gutter" ? "gutterClass" : "wrapClass";
  5699. if (!line[prop]) { line[prop] = cls; }
  5700. else if (classTest(cls).test(line[prop])) { return false }
  5701. else { line[prop] += " " + cls; }
  5702. return true
  5703. })
  5704. }),
  5705. removeLineClass: docMethodOp(function(handle, where, cls) {
  5706. return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) {
  5707. var prop = where == "text" ? "textClass"
  5708. : where == "background" ? "bgClass"
  5709. : where == "gutter" ? "gutterClass" : "wrapClass";
  5710. var cur = line[prop];
  5711. if (!cur) { return false }
  5712. else if (cls == null) { line[prop] = null; }
  5713. else {
  5714. var found = cur.match(classTest(cls));
  5715. if (!found) { return false }
  5716. var end = found.index + found[0].length;
  5717. line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null;
  5718. }
  5719. return true
  5720. })
  5721. }),
  5722. addLineWidget: docMethodOp(function(handle, node, options) {
  5723. return addLineWidget(this, handle, node, options)
  5724. }),
  5725. removeLineWidget: function(widget) { widget.clear(); },
  5726. markText: function(from, to, options) {
  5727. return markText(this, clipPos(this, from), clipPos(this, to), options, options && options.type || "range")
  5728. },
  5729. setBookmark: function(pos, options) {
  5730. var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options),
  5731. insertLeft: options && options.insertLeft,
  5732. clearWhenEmpty: false, shared: options && options.shared,
  5733. handleMouseEvents: options && options.handleMouseEvents};
  5734. pos = clipPos(this, pos);
  5735. return markText(this, pos, pos, realOpts, "bookmark")
  5736. },
  5737. findMarksAt: function(pos) {
  5738. pos = clipPos(this, pos);
  5739. var markers = [], spans = getLine(this, pos.line).markedSpans;
  5740. if (spans) { for (var i = 0; i < spans.length; ++i) {
  5741. var span = spans[i];
  5742. if ((span.from == null || span.from <= pos.ch) &&
  5743. (span.to == null || span.to >= pos.ch))
  5744. { markers.push(span.marker.parent || span.marker); }
  5745. } }
  5746. return markers
  5747. },
  5748. findMarks: function(from, to, filter) {
  5749. from = clipPos(this, from); to = clipPos(this, to);
  5750. var found = [], lineNo$$1 = from.line;
  5751. this.iter(from.line, to.line + 1, function (line) {
  5752. var spans = line.markedSpans;
  5753. if (spans) { for (var i = 0; i < spans.length; i++) {
  5754. var span = spans[i];
  5755. if (!(span.to != null && lineNo$$1 == from.line && from.ch >= span.to ||
  5756. span.from == null && lineNo$$1 != from.line ||
  5757. span.from != null && lineNo$$1 == to.line && span.from >= to.ch) &&
  5758. (!filter || filter(span.marker)))
  5759. { found.push(span.marker.parent || span.marker); }
  5760. } }
  5761. ++lineNo$$1;
  5762. });
  5763. return found
  5764. },
  5765. getAllMarks: function() {
  5766. var markers = [];
  5767. this.iter(function (line) {
  5768. var sps = line.markedSpans;
  5769. if (sps) { for (var i = 0; i < sps.length; ++i)
  5770. { if (sps[i].from != null) { markers.push(sps[i].marker); } } }
  5771. });
  5772. return markers
  5773. },
  5774. posFromIndex: function(off) {
  5775. var ch, lineNo$$1 = this.first, sepSize = this.lineSeparator().length;
  5776. this.iter(function (line) {
  5777. var sz = line.text.length + sepSize;
  5778. if (sz > off) { ch = off; return true }
  5779. off -= sz;
  5780. ++lineNo$$1;
  5781. });
  5782. return clipPos(this, Pos(lineNo$$1, ch))
  5783. },
  5784. indexFromPos: function (coords) {
  5785. coords = clipPos(this, coords);
  5786. var index = coords.ch;
  5787. if (coords.line < this.first || coords.ch < 0) { return 0 }
  5788. var sepSize = this.lineSeparator().length;
  5789. this.iter(this.first, coords.line, function (line) { // iter aborts when callback returns a truthy value
  5790. index += line.text.length + sepSize;
  5791. });
  5792. return index
  5793. },
  5794. copy: function(copyHistory) {
  5795. var doc = new Doc(getLines(this, this.first, this.first + this.size),
  5796. this.modeOption, this.first, this.lineSep, this.direction);
  5797. doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft;
  5798. doc.sel = this.sel;
  5799. doc.extend = false;
  5800. if (copyHistory) {
  5801. doc.history.undoDepth = this.history.undoDepth;
  5802. doc.setHistory(this.getHistory());
  5803. }
  5804. return doc
  5805. },
  5806. linkedDoc: function(options) {
  5807. if (!options) { options = {}; }
  5808. var from = this.first, to = this.first + this.size;
  5809. if (options.from != null && options.from > from) { from = options.from; }
  5810. if (options.to != null && options.to < to) { to = options.to; }
  5811. var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from, this.lineSep, this.direction);
  5812. if (options.sharedHist) { copy.history = this.history
  5813. ; }(this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist});
  5814. copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}];
  5815. copySharedMarkers(copy, findSharedMarkers(this));
  5816. return copy
  5817. },
  5818. unlinkDoc: function(other) {
  5819. var this$1 = this;
  5820. if (other instanceof CodeMirror) { other = other.doc; }
  5821. if (this.linked) { for (var i = 0; i < this.linked.length; ++i) {
  5822. var link = this$1.linked[i];
  5823. if (link.doc != other) { continue }
  5824. this$1.linked.splice(i, 1);
  5825. other.unlinkDoc(this$1);
  5826. detachSharedMarkers(findSharedMarkers(this$1));
  5827. break
  5828. } }
  5829. // If the histories were shared, split them again
  5830. if (other.history == this.history) {
  5831. var splitIds = [other.id];
  5832. linkedDocs(other, function (doc) { return splitIds.push(doc.id); }, true);
  5833. other.history = new History(null);
  5834. other.history.done = copyHistoryArray(this.history.done, splitIds);
  5835. other.history.undone = copyHistoryArray(this.history.undone, splitIds);
  5836. }
  5837. },
  5838. iterLinkedDocs: function(f) {linkedDocs(this, f);},
  5839. getMode: function() {return this.mode},
  5840. getEditor: function() {return this.cm},
  5841. splitLines: function(str) {
  5842. if (this.lineSep) { return str.split(this.lineSep) }
  5843. return splitLinesAuto(str)
  5844. },
  5845. lineSeparator: function() { return this.lineSep || "\n" },
  5846. setDirection: docMethodOp(function (dir) {
  5847. if (dir != "rtl") { dir = "ltr"; }
  5848. if (dir == this.direction) { return }
  5849. this.direction = dir;
  5850. this.iter(function (line) { return line.order = null; });
  5851. if (this.cm) { directionChanged(this.cm); }
  5852. })
  5853. });
  5854. // Public alias.
  5855. Doc.prototype.eachLine = Doc.prototype.iter;
  5856. // Kludge to work around strange IE behavior where it'll sometimes
  5857. // re-fire a series of drag-related events right after the drop (#1551)
  5858. var lastDrop = 0;
  5859. function onDrop(e) {
  5860. var cm = this;
  5861. clearDragCursor(cm);
  5862. if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e))
  5863. { return }
  5864. e_preventDefault(e);
  5865. if (ie) { lastDrop = +new Date; }
  5866. var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files;
  5867. if (!pos || cm.isReadOnly()) { return }
  5868. // Might be a file drop, in which case we simply extract the text
  5869. // and insert it.
  5870. if (files && files.length && window.FileReader && window.File) {
  5871. var n = files.length, text = Array(n), read = 0;
  5872. var loadFile = function (file, i) {
  5873. if (cm.options.allowDropFileTypes &&
  5874. indexOf(cm.options.allowDropFileTypes, file.type) == -1)
  5875. { return }
  5876. var reader = new FileReader;
  5877. reader.onload = operation(cm, function () {
  5878. var content = reader.result;
  5879. if (/[\x00-\x08\x0e-\x1f]{2}/.test(content)) { content = ""; }
  5880. text[i] = content;
  5881. if (++read == n) {
  5882. pos = clipPos(cm.doc, pos);
  5883. var change = {from: pos, to: pos,
  5884. text: cm.doc.splitLines(text.join(cm.doc.lineSeparator())),
  5885. origin: "paste"};
  5886. makeChange(cm.doc, change);
  5887. setSelectionReplaceHistory(cm.doc, simpleSelection(pos, changeEnd(change)));
  5888. }
  5889. });
  5890. reader.readAsText(file);
  5891. };
  5892. for (var i = 0; i < n; ++i) { loadFile(files[i], i); }
  5893. } else { // Normal drop
  5894. // Don't do a replace if the drop happened inside of the selected text.
  5895. if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) {
  5896. cm.state.draggingText(e);
  5897. // Ensure the editor is re-focused
  5898. setTimeout(function () { return cm.display.input.focus(); }, 20);
  5899. return
  5900. }
  5901. try {
  5902. var text$1 = e.dataTransfer.getData("Text");
  5903. if (text$1) {
  5904. var selected;
  5905. if (cm.state.draggingText && !cm.state.draggingText.copy)
  5906. { selected = cm.listSelections(); }
  5907. setSelectionNoUndo(cm.doc, simpleSelection(pos, pos));
  5908. if (selected) { for (var i$1 = 0; i$1 < selected.length; ++i$1)
  5909. { replaceRange(cm.doc, "", selected[i$1].anchor, selected[i$1].head, "drag"); } }
  5910. cm.replaceSelection(text$1, "around", "paste");
  5911. cm.display.input.focus();
  5912. }
  5913. }
  5914. catch(e){}
  5915. }
  5916. }
  5917. function onDragStart(cm, e) {
  5918. if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return }
  5919. if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) { return }
  5920. e.dataTransfer.setData("Text", cm.getSelection());
  5921. e.dataTransfer.effectAllowed = "copyMove";
  5922. // Use dummy image instead of default browsers image.
  5923. // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there.
  5924. if (e.dataTransfer.setDragImage && !safari) {
  5925. var img = elt("img", null, null, "position: fixed; left: 0; top: 0;");
  5926. img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";
  5927. if (presto) {
  5928. img.width = img.height = 1;
  5929. cm.display.wrapper.appendChild(img);
  5930. // Force a relayout, or Opera won't use our image for some obscure reason
  5931. img._top = img.offsetTop;
  5932. }
  5933. e.dataTransfer.setDragImage(img, 0, 0);
  5934. if (presto) { img.parentNode.removeChild(img); }
  5935. }
  5936. }
  5937. function onDragOver(cm, e) {
  5938. var pos = posFromMouse(cm, e);
  5939. if (!pos) { return }
  5940. var frag = document.createDocumentFragment();
  5941. drawSelectionCursor(cm, pos, frag);
  5942. if (!cm.display.dragCursor) {
  5943. cm.display.dragCursor = elt("div", null, "CodeMirror-cursors CodeMirror-dragcursors");
  5944. cm.display.lineSpace.insertBefore(cm.display.dragCursor, cm.display.cursorDiv);
  5945. }
  5946. removeChildrenAndAdd(cm.display.dragCursor, frag);
  5947. }
  5948. function clearDragCursor(cm) {
  5949. if (cm.display.dragCursor) {
  5950. cm.display.lineSpace.removeChild(cm.display.dragCursor);
  5951. cm.display.dragCursor = null;
  5952. }
  5953. }
  5954. // These must be handled carefully, because naively registering a
  5955. // handler for each editor will cause the editors to never be
  5956. // garbage collected.
  5957. function forEachCodeMirror(f) {
  5958. if (!document.getElementsByClassName) { return }
  5959. var byClass = document.getElementsByClassName("CodeMirror"), editors = [];
  5960. for (var i = 0; i < byClass.length; i++) {
  5961. var cm = byClass[i].CodeMirror;
  5962. if (cm) { editors.push(cm); }
  5963. }
  5964. if (editors.length) { editors[0].operation(function () {
  5965. for (var i = 0; i < editors.length; i++) { f(editors[i]); }
  5966. }); }
  5967. }
  5968. var globalsRegistered = false;
  5969. function ensureGlobalHandlers() {
  5970. if (globalsRegistered) { return }
  5971. registerGlobalHandlers();
  5972. globalsRegistered = true;
  5973. }
  5974. function registerGlobalHandlers() {
  5975. // When the window resizes, we need to refresh active editors.
  5976. var resizeTimer;
  5977. on(window, "resize", function () {
  5978. if (resizeTimer == null) { resizeTimer = setTimeout(function () {
  5979. resizeTimer = null;
  5980. forEachCodeMirror(onResize);
  5981. }, 100); }
  5982. });
  5983. // When the window loses focus, we want to show the editor as blurred
  5984. on(window, "blur", function () { return forEachCodeMirror(onBlur); });
  5985. }
  5986. // Called when the window resizes
  5987. function onResize(cm) {
  5988. var d = cm.display;
  5989. // Might be a text scaling operation, clear size caches.
  5990. d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
  5991. d.scrollbarsClipped = false;
  5992. cm.setSize();
  5993. }
  5994. var keyNames = {
  5995. 3: "Pause", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt",
  5996. 19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End",
  5997. 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert",
  5998. 46: "Delete", 59: ";", 61: "=", 91: "Mod", 92: "Mod", 93: "Mod",
  5999. 106: "*", 107: "=", 109: "-", 110: ".", 111: "/", 145: "ScrollLock",
  6000. 173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\",
  6001. 221: "]", 222: "'", 63232: "Up", 63233: "Down", 63234: "Left", 63235: "Right", 63272: "Delete",
  6002. 63273: "Home", 63275: "End", 63276: "PageUp", 63277: "PageDown", 63302: "Insert"
  6003. };
  6004. // Number keys
  6005. for (var i = 0; i < 10; i++) { keyNames[i + 48] = keyNames[i + 96] = String(i); }
  6006. // Alphabetic keys
  6007. for (var i$1 = 65; i$1 <= 90; i$1++) { keyNames[i$1] = String.fromCharCode(i$1); }
  6008. // Function keys
  6009. for (var i$2 = 1; i$2 <= 12; i$2++) { keyNames[i$2 + 111] = keyNames[i$2 + 63235] = "F" + i$2; }
  6010. var keyMap = {};
  6011. keyMap.basic = {
  6012. "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown",
  6013. "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown",
  6014. "Delete": "delCharAfter", "Backspace": "delCharBefore", "Shift-Backspace": "delCharBefore",
  6015. "Tab": "defaultTab", "Shift-Tab": "indentAuto",
  6016. "Enter": "newlineAndIndent", "Insert": "toggleOverwrite",
  6017. "Esc": "singleSelection"
  6018. };
  6019. // Note that the save and find-related commands aren't defined by
  6020. // default. User code or addons can define them. Unknown commands
  6021. // are simply ignored.
  6022. keyMap.pcDefault = {
  6023. "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo",
  6024. "Ctrl-Home": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Up": "goLineUp", "Ctrl-Down": "goLineDown",
  6025. "Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd",
  6026. "Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find",
  6027. "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll",
  6028. "Ctrl-[": "indentLess", "Ctrl-]": "indentMore",
  6029. "Ctrl-U": "undoSelection", "Shift-Ctrl-U": "redoSelection", "Alt-U": "redoSelection",
  6030. "fallthrough": "basic"
  6031. };
  6032. // Very basic readline/emacs-style bindings, which are standard on Mac.
  6033. keyMap.emacsy = {
  6034. "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown",
  6035. "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd",
  6036. "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp", "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore",
  6037. "Alt-D": "delWordAfter", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars",
  6038. "Ctrl-O": "openLine"
  6039. };
  6040. keyMap.macDefault = {
  6041. "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo",
  6042. "Cmd-Home": "goDocStart", "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft",
  6043. "Alt-Right": "goGroupRight", "Cmd-Left": "goLineLeft", "Cmd-Right": "goLineRight", "Alt-Backspace": "delGroupBefore",
  6044. "Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find",
  6045. "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll",
  6046. "Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delWrappedLineLeft", "Cmd-Delete": "delWrappedLineRight",
  6047. "Cmd-U": "undoSelection", "Shift-Cmd-U": "redoSelection", "Ctrl-Up": "goDocStart", "Ctrl-Down": "goDocEnd",
  6048. "fallthrough": ["basic", "emacsy"]
  6049. };
  6050. keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault;
  6051. // KEYMAP DISPATCH
  6052. function normalizeKeyName(name) {
  6053. var parts = name.split(/-(?!$)/);
  6054. name = parts[parts.length - 1];
  6055. var alt, ctrl, shift, cmd;
  6056. for (var i = 0; i < parts.length - 1; i++) {
  6057. var mod = parts[i];
  6058. if (/^(cmd|meta|m)$/i.test(mod)) { cmd = true; }
  6059. else if (/^a(lt)?$/i.test(mod)) { alt = true; }
  6060. else if (/^(c|ctrl|control)$/i.test(mod)) { ctrl = true; }
  6061. else if (/^s(hift)?$/i.test(mod)) { shift = true; }
  6062. else { throw new Error("Unrecognized modifier name: " + mod) }
  6063. }
  6064. if (alt) { name = "Alt-" + name; }
  6065. if (ctrl) { name = "Ctrl-" + name; }
  6066. if (cmd) { name = "Cmd-" + name; }
  6067. if (shift) { name = "Shift-" + name; }
  6068. return name
  6069. }
  6070. // This is a kludge to keep keymaps mostly working as raw objects
  6071. // (backwards compatibility) while at the same time support features
  6072. // like normalization and multi-stroke key bindings. It compiles a
  6073. // new normalized keymap, and then updates the old object to reflect
  6074. // this.
  6075. function normalizeKeyMap(keymap) {
  6076. var copy = {};
  6077. for (var keyname in keymap) { if (keymap.hasOwnProperty(keyname)) {
  6078. var value = keymap[keyname];
  6079. if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) { continue }
  6080. if (value == "...") { delete keymap[keyname]; continue }
  6081. var keys = map(keyname.split(" "), normalizeKeyName);
  6082. for (var i = 0; i < keys.length; i++) {
  6083. var val = (void 0), name = (void 0);
  6084. if (i == keys.length - 1) {
  6085. name = keys.join(" ");
  6086. val = value;
  6087. } else {
  6088. name = keys.slice(0, i + 1).join(" ");
  6089. val = "...";
  6090. }
  6091. var prev = copy[name];
  6092. if (!prev) { copy[name] = val; }
  6093. else if (prev != val) { throw new Error("Inconsistent bindings for " + name) }
  6094. }
  6095. delete keymap[keyname];
  6096. } }
  6097. for (var prop in copy) { keymap[prop] = copy[prop]; }
  6098. return keymap
  6099. }
  6100. function lookupKey(key, map$$1, handle, context) {
  6101. map$$1 = getKeyMap(map$$1);
  6102. var found = map$$1.call ? map$$1.call(key, context) : map$$1[key];
  6103. if (found === false) { return "nothing" }
  6104. if (found === "...") { return "multi" }
  6105. if (found != null && handle(found)) { return "handled" }
  6106. if (map$$1.fallthrough) {
  6107. if (Object.prototype.toString.call(map$$1.fallthrough) != "[object Array]")
  6108. { return lookupKey(key, map$$1.fallthrough, handle, context) }
  6109. for (var i = 0; i < map$$1.fallthrough.length; i++) {
  6110. var result = lookupKey(key, map$$1.fallthrough[i], handle, context);
  6111. if (result) { return result }
  6112. }
  6113. }
  6114. }
  6115. // Modifier key presses don't count as 'real' key presses for the
  6116. // purpose of keymap fallthrough.
  6117. function isModifierKey(value) {
  6118. var name = typeof value == "string" ? value : keyNames[value.keyCode];
  6119. return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod"
  6120. }
  6121. function addModifierNames(name, event, noShift) {
  6122. var base = name;
  6123. if (event.altKey && base != "Alt") { name = "Alt-" + name; }
  6124. if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != "Ctrl") { name = "Ctrl-" + name; }
  6125. if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != "Cmd") { name = "Cmd-" + name; }
  6126. if (!noShift && event.shiftKey && base != "Shift") { name = "Shift-" + name; }
  6127. return name
  6128. }
  6129. // Look up the name of a key as indicated by an event object.
  6130. function keyName(event, noShift) {
  6131. if (presto && event.keyCode == 34 && event["char"]) { return false }
  6132. var name = keyNames[event.keyCode];
  6133. if (name == null || event.altGraphKey) { return false }
  6134. // Ctrl-ScrollLock has keyCode 3, same as Ctrl-Pause,
  6135. // so we'll use event.code when available (Chrome 48+, FF 38+, Safari 10.1+)
  6136. if (event.keyCode == 3 && event.code) { name = event.code; }
  6137. return addModifierNames(name, event, noShift)
  6138. }
  6139. function getKeyMap(val) {
  6140. return typeof val == "string" ? keyMap[val] : val
  6141. }
  6142. // Helper for deleting text near the selection(s), used to implement
  6143. // backspace, delete, and similar functionality.
  6144. function deleteNearSelection(cm, compute) {
  6145. var ranges = cm.doc.sel.ranges, kill = [];
  6146. // Build up a set of ranges to kill first, merging overlapping
  6147. // ranges.
  6148. for (var i = 0; i < ranges.length; i++) {
  6149. var toKill = compute(ranges[i]);
  6150. while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) {
  6151. var replaced = kill.pop();
  6152. if (cmp(replaced.from, toKill.from) < 0) {
  6153. toKill.from = replaced.from;
  6154. break
  6155. }
  6156. }
  6157. kill.push(toKill);
  6158. }
  6159. // Next, remove those actual ranges.
  6160. runInOp(cm, function () {
  6161. for (var i = kill.length - 1; i >= 0; i--)
  6162. { replaceRange(cm.doc, "", kill[i].from, kill[i].to, "+delete"); }
  6163. ensureCursorVisible(cm);
  6164. });
  6165. }
  6166. function moveCharLogically(line, ch, dir) {
  6167. var target = skipExtendingChars(line.text, ch + dir, dir);
  6168. return target < 0 || target > line.text.length ? null : target
  6169. }
  6170. function moveLogically(line, start, dir) {
  6171. var ch = moveCharLogically(line, start.ch, dir);
  6172. return ch == null ? null : new Pos(start.line, ch, dir < 0 ? "after" : "before")
  6173. }
  6174. function endOfLine(visually, cm, lineObj, lineNo, dir) {
  6175. if (visually) {
  6176. var order = getOrder(lineObj, cm.doc.direction);
  6177. if (order) {
  6178. var part = dir < 0 ? lst(order) : order[0];
  6179. var moveInStorageOrder = (dir < 0) == (part.level == 1);
  6180. var sticky = moveInStorageOrder ? "after" : "before";
  6181. var ch;
  6182. // With a wrapped rtl chunk (possibly spanning multiple bidi parts),
  6183. // it could be that the last bidi part is not on the last visual line,
  6184. // since visual lines contain content order-consecutive chunks.
  6185. // Thus, in rtl, we are looking for the first (content-order) character
  6186. // in the rtl chunk that is on the last line (that is, the same line
  6187. // as the last (content-order) character).
  6188. if (part.level > 0 || cm.doc.direction == "rtl") {
  6189. var prep = prepareMeasureForLine(cm, lineObj);
  6190. ch = dir < 0 ? lineObj.text.length - 1 : 0;
  6191. var targetTop = measureCharPrepared(cm, prep, ch).top;
  6192. ch = findFirst(function (ch) { return measureCharPrepared(cm, prep, ch).top == targetTop; }, (dir < 0) == (part.level == 1) ? part.from : part.to - 1, ch);
  6193. if (sticky == "before") { ch = moveCharLogically(lineObj, ch, 1); }
  6194. } else { ch = dir < 0 ? part.to : part.from; }
  6195. return new Pos(lineNo, ch, sticky)
  6196. }
  6197. }
  6198. return new Pos(lineNo, dir < 0 ? lineObj.text.length : 0, dir < 0 ? "before" : "after")
  6199. }
  6200. function moveVisually(cm, line, start, dir) {
  6201. var bidi = getOrder(line, cm.doc.direction);
  6202. if (!bidi) { return moveLogically(line, start, dir) }
  6203. if (start.ch >= line.text.length) {
  6204. start.ch = line.text.length;
  6205. start.sticky = "before";
  6206. } else if (start.ch <= 0) {
  6207. start.ch = 0;
  6208. start.sticky = "after";
  6209. }
  6210. var partPos = getBidiPartAt(bidi, start.ch, start.sticky), part = bidi[partPos];
  6211. if (cm.doc.direction == "ltr" && part.level % 2 == 0 && (dir > 0 ? part.to > start.ch : part.from < start.ch)) {
  6212. // Case 1: We move within an ltr part in an ltr editor. Even with wrapped lines,
  6213. // nothing interesting happens.
  6214. return moveLogically(line, start, dir)
  6215. }
  6216. var mv = function (pos, dir) { return moveCharLogically(line, pos instanceof Pos ? pos.ch : pos, dir); };
  6217. var prep;
  6218. var getWrappedLineExtent = function (ch) {
  6219. if (!cm.options.lineWrapping) { return {begin: 0, end: line.text.length} }
  6220. prep = prep || prepareMeasureForLine(cm, line);
  6221. return wrappedLineExtentChar(cm, line, prep, ch)
  6222. };
  6223. var wrappedLineExtent = getWrappedLineExtent(start.sticky == "before" ? mv(start, -1) : start.ch);
  6224. if (cm.doc.direction == "rtl" || part.level == 1) {
  6225. var moveInStorageOrder = (part.level == 1) == (dir < 0);
  6226. var ch = mv(start, moveInStorageOrder ? 1 : -1);
  6227. if (ch != null && (!moveInStorageOrder ? ch >= part.from && ch >= wrappedLineExtent.begin : ch <= part.to && ch <= wrappedLineExtent.end)) {
  6228. // Case 2: We move within an rtl part or in an rtl editor on the same visual line
  6229. var sticky = moveInStorageOrder ? "before" : "after";
  6230. return new Pos(start.line, ch, sticky)
  6231. }
  6232. }
  6233. // Case 3: Could not move within this bidi part in this visual line, so leave
  6234. // the current bidi part
  6235. var searchInVisualLine = function (partPos, dir, wrappedLineExtent) {
  6236. var getRes = function (ch, moveInStorageOrder) { return moveInStorageOrder
  6237. ? new Pos(start.line, mv(ch, 1), "before")
  6238. : new Pos(start.line, ch, "after"); };
  6239. for (; partPos >= 0 && partPos < bidi.length; partPos += dir) {
  6240. var part = bidi[partPos];
  6241. var moveInStorageOrder = (dir > 0) == (part.level != 1);
  6242. var ch = moveInStorageOrder ? wrappedLineExtent.begin : mv(wrappedLineExtent.end, -1);
  6243. if (part.from <= ch && ch < part.to) { return getRes(ch, moveInStorageOrder) }
  6244. ch = moveInStorageOrder ? part.from : mv(part.to, -1);
  6245. if (wrappedLineExtent.begin <= ch && ch < wrappedLineExtent.end) { return getRes(ch, moveInStorageOrder) }
  6246. }
  6247. };
  6248. // Case 3a: Look for other bidi parts on the same visual line
  6249. var res = searchInVisualLine(partPos + dir, dir, wrappedLineExtent);
  6250. if (res) { return res }
  6251. // Case 3b: Look for other bidi parts on the next visual line
  6252. var nextCh = dir > 0 ? wrappedLineExtent.end : mv(wrappedLineExtent.begin, -1);
  6253. if (nextCh != null && !(dir > 0 && nextCh == line.text.length)) {
  6254. res = searchInVisualLine(dir > 0 ? 0 : bidi.length - 1, dir, getWrappedLineExtent(nextCh));
  6255. if (res) { return res }
  6256. }
  6257. // Case 4: Nowhere to move
  6258. return null
  6259. }
  6260. // Commands are parameter-less actions that can be performed on an
  6261. // editor, mostly used for keybindings.
  6262. var commands = {
  6263. selectAll: selectAll,
  6264. singleSelection: function (cm) { return cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll); },
  6265. killLine: function (cm) { return deleteNearSelection(cm, function (range) {
  6266. if (range.empty()) {
  6267. var len = getLine(cm.doc, range.head.line).text.length;
  6268. if (range.head.ch == len && range.head.line < cm.lastLine())
  6269. { return {from: range.head, to: Pos(range.head.line + 1, 0)} }
  6270. else
  6271. { return {from: range.head, to: Pos(range.head.line, len)} }
  6272. } else {
  6273. return {from: range.from(), to: range.to()}
  6274. }
  6275. }); },
  6276. deleteLine: function (cm) { return deleteNearSelection(cm, function (range) { return ({
  6277. from: Pos(range.from().line, 0),
  6278. to: clipPos(cm.doc, Pos(range.to().line + 1, 0))
  6279. }); }); },
  6280. delLineLeft: function (cm) { return deleteNearSelection(cm, function (range) { return ({
  6281. from: Pos(range.from().line, 0), to: range.from()
  6282. }); }); },
  6283. delWrappedLineLeft: function (cm) { return deleteNearSelection(cm, function (range) {
  6284. var top = cm.charCoords(range.head, "div").top + 5;
  6285. var leftPos = cm.coordsChar({left: 0, top: top}, "div");
  6286. return {from: leftPos, to: range.from()}
  6287. }); },
  6288. delWrappedLineRight: function (cm) { return deleteNearSelection(cm, function (range) {
  6289. var top = cm.charCoords(range.head, "div").top + 5;
  6290. var rightPos = cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div");
  6291. return {from: range.from(), to: rightPos }
  6292. }); },
  6293. undo: function (cm) { return cm.undo(); },
  6294. redo: function (cm) { return cm.redo(); },
  6295. undoSelection: function (cm) { return cm.undoSelection(); },
  6296. redoSelection: function (cm) { return cm.redoSelection(); },
  6297. goDocStart: function (cm) { return cm.extendSelection(Pos(cm.firstLine(), 0)); },
  6298. goDocEnd: function (cm) { return cm.extendSelection(Pos(cm.lastLine())); },
  6299. goLineStart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStart(cm, range.head.line); },
  6300. {origin: "+move", bias: 1}
  6301. ); },
  6302. goLineStartSmart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStartSmart(cm, range.head); },
  6303. {origin: "+move", bias: 1}
  6304. ); },
  6305. goLineEnd: function (cm) { return cm.extendSelectionsBy(function (range) { return lineEnd(cm, range.head.line); },
  6306. {origin: "+move", bias: -1}
  6307. ); },
  6308. goLineRight: function (cm) { return cm.extendSelectionsBy(function (range) {
  6309. var top = cm.cursorCoords(range.head, "div").top + 5;
  6310. return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div")
  6311. }, sel_move); },
  6312. goLineLeft: function (cm) { return cm.extendSelectionsBy(function (range) {
  6313. var top = cm.cursorCoords(range.head, "div").top + 5;
  6314. return cm.coordsChar({left: 0, top: top}, "div")
  6315. }, sel_move); },
  6316. goLineLeftSmart: function (cm) { return cm.extendSelectionsBy(function (range) {
  6317. var top = cm.cursorCoords(range.head, "div").top + 5;
  6318. var pos = cm.coordsChar({left: 0, top: top}, "div");
  6319. if (pos.ch < cm.getLine(pos.line).search(/\S/)) { return lineStartSmart(cm, range.head) }
  6320. return pos
  6321. }, sel_move); },
  6322. goLineUp: function (cm) { return cm.moveV(-1, "line"); },
  6323. goLineDown: function (cm) { return cm.moveV(1, "line"); },
  6324. goPageUp: function (cm) { return cm.moveV(-1, "page"); },
  6325. goPageDown: function (cm) { return cm.moveV(1, "page"); },
  6326. goCharLeft: function (cm) { return cm.moveH(-1, "char"); },
  6327. goCharRight: function (cm) { return cm.moveH(1, "char"); },
  6328. goColumnLeft: function (cm) { return cm.moveH(-1, "column"); },
  6329. goColumnRight: function (cm) { return cm.moveH(1, "column"); },
  6330. goWordLeft: function (cm) { return cm.moveH(-1, "word"); },
  6331. goGroupRight: function (cm) { return cm.moveH(1, "group"); },
  6332. goGroupLeft: function (cm) { return cm.moveH(-1, "group"); },
  6333. goWordRight: function (cm) { return cm.moveH(1, "word"); },
  6334. delCharBefore: function (cm) { return cm.deleteH(-1, "char"); },
  6335. delCharAfter: function (cm) { return cm.deleteH(1, "char"); },
  6336. delWordBefore: function (cm) { return cm.deleteH(-1, "word"); },
  6337. delWordAfter: function (cm) { return cm.deleteH(1, "word"); },
  6338. delGroupBefore: function (cm) { return cm.deleteH(-1, "group"); },
  6339. delGroupAfter: function (cm) { return cm.deleteH(1, "group"); },
  6340. indentAuto: function (cm) { return cm.indentSelection("smart"); },
  6341. indentMore: function (cm) { return cm.indentSelection("add"); },
  6342. indentLess: function (cm) { return cm.indentSelection("subtract"); },
  6343. insertTab: function (cm) { return cm.replaceSelection("\t"); },
  6344. insertSoftTab: function (cm) {
  6345. var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize;
  6346. for (var i = 0; i < ranges.length; i++) {
  6347. var pos = ranges[i].from();
  6348. var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize);
  6349. spaces.push(spaceStr(tabSize - col % tabSize));
  6350. }
  6351. cm.replaceSelections(spaces);
  6352. },
  6353. defaultTab: function (cm) {
  6354. if (cm.somethingSelected()) { cm.indentSelection("add"); }
  6355. else { cm.execCommand("insertTab"); }
  6356. },
  6357. // Swap the two chars left and right of each selection's head.
  6358. // Move cursor behind the two swapped characters afterwards.
  6359. //
  6360. // Doesn't consider line feeds a character.
  6361. // Doesn't scan more than one line above to find a character.
  6362. // Doesn't do anything on an empty line.
  6363. // Doesn't do anything with non-empty selections.
  6364. transposeChars: function (cm) { return runInOp(cm, function () {
  6365. var ranges = cm.listSelections(), newSel = [];
  6366. for (var i = 0; i < ranges.length; i++) {
  6367. if (!ranges[i].empty()) { continue }
  6368. var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text;
  6369. if (line) {
  6370. if (cur.ch == line.length) { cur = new Pos(cur.line, cur.ch - 1); }
  6371. if (cur.ch > 0) {
  6372. cur = new Pos(cur.line, cur.ch + 1);
  6373. cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2),
  6374. Pos(cur.line, cur.ch - 2), cur, "+transpose");
  6375. } else if (cur.line > cm.doc.first) {
  6376. var prev = getLine(cm.doc, cur.line - 1).text;
  6377. if (prev) {
  6378. cur = new Pos(cur.line, 1);
  6379. cm.replaceRange(line.charAt(0) + cm.doc.lineSeparator() +
  6380. prev.charAt(prev.length - 1),
  6381. Pos(cur.line - 1, prev.length - 1), cur, "+transpose");
  6382. }
  6383. }
  6384. }
  6385. newSel.push(new Range(cur, cur));
  6386. }
  6387. cm.setSelections(newSel);
  6388. }); },
  6389. newlineAndIndent: function (cm) { return runInOp(cm, function () {
  6390. var sels = cm.listSelections();
  6391. for (var i = sels.length - 1; i >= 0; i--)
  6392. { cm.replaceRange(cm.doc.lineSeparator(), sels[i].anchor, sels[i].head, "+input"); }
  6393. sels = cm.listSelections();
  6394. for (var i$1 = 0; i$1 < sels.length; i$1++)
  6395. { cm.indentLine(sels[i$1].from().line, null, true); }
  6396. ensureCursorVisible(cm);
  6397. }); },
  6398. openLine: function (cm) { return cm.replaceSelection("\n", "start"); },
  6399. toggleOverwrite: function (cm) { return cm.toggleOverwrite(); }
  6400. };
  6401. function lineStart(cm, lineN) {
  6402. var line = getLine(cm.doc, lineN);
  6403. var visual = visualLine(line);
  6404. if (visual != line) { lineN = lineNo(visual); }
  6405. return endOfLine(true, cm, visual, lineN, 1)
  6406. }
  6407. function lineEnd(cm, lineN) {
  6408. var line = getLine(cm.doc, lineN);
  6409. var visual = visualLineEnd(line);
  6410. if (visual != line) { lineN = lineNo(visual); }
  6411. return endOfLine(true, cm, line, lineN, -1)
  6412. }
  6413. function lineStartSmart(cm, pos) {
  6414. var start = lineStart(cm, pos.line);
  6415. var line = getLine(cm.doc, start.line);
  6416. var order = getOrder(line, cm.doc.direction);
  6417. if (!order || order[0].level == 0) {
  6418. var firstNonWS = Math.max(0, line.text.search(/\S/));
  6419. var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch;
  6420. return Pos(start.line, inWS ? 0 : firstNonWS, start.sticky)
  6421. }
  6422. return start
  6423. }
  6424. // Run a handler that was bound to a key.
  6425. function doHandleBinding(cm, bound, dropShift) {
  6426. if (typeof bound == "string") {
  6427. bound = commands[bound];
  6428. if (!bound) { return false }
  6429. }
  6430. // Ensure previous input has been read, so that the handler sees a
  6431. // consistent view of the document
  6432. cm.display.input.ensurePolled();
  6433. var prevShift = cm.display.shift, done = false;
  6434. try {
  6435. if (cm.isReadOnly()) { cm.state.suppressEdits = true; }
  6436. if (dropShift) { cm.display.shift = false; }
  6437. done = bound(cm) != Pass;
  6438. } finally {
  6439. cm.display.shift = prevShift;
  6440. cm.state.suppressEdits = false;
  6441. }
  6442. return done
  6443. }
  6444. function lookupKeyForEditor(cm, name, handle) {
  6445. for (var i = 0; i < cm.state.keyMaps.length; i++) {
  6446. var result = lookupKey(name, cm.state.keyMaps[i], handle, cm);
  6447. if (result) { return result }
  6448. }
  6449. return (cm.options.extraKeys && lookupKey(name, cm.options.extraKeys, handle, cm))
  6450. || lookupKey(name, cm.options.keyMap, handle, cm)
  6451. }
  6452. // Note that, despite the name, this function is also used to check
  6453. // for bound mouse clicks.
  6454. var stopSeq = new Delayed;
  6455. function dispatchKey(cm, name, e, handle) {
  6456. var seq = cm.state.keySeq;
  6457. if (seq) {
  6458. if (isModifierKey(name)) { return "handled" }
  6459. if (/\'$/.test(name))
  6460. { cm.state.keySeq = null; }
  6461. else
  6462. { stopSeq.set(50, function () {
  6463. if (cm.state.keySeq == seq) {
  6464. cm.state.keySeq = null;
  6465. cm.display.input.reset();
  6466. }
  6467. }); }
  6468. if (dispatchKeyInner(cm, seq + " " + name, e, handle)) { return true }
  6469. }
  6470. return dispatchKeyInner(cm, name, e, handle)
  6471. }
  6472. function dispatchKeyInner(cm, name, e, handle) {
  6473. var result = lookupKeyForEditor(cm, name, handle);
  6474. if (result == "multi")
  6475. { cm.state.keySeq = name; }
  6476. if (result == "handled")
  6477. { signalLater(cm, "keyHandled", cm, name, e); }
  6478. if (result == "handled" || result == "multi") {
  6479. e_preventDefault(e);
  6480. restartBlink(cm);
  6481. }
  6482. return !!result
  6483. }
  6484. // Handle a key from the keydown event.
  6485. function handleKeyBinding(cm, e) {
  6486. var name = keyName(e, true);
  6487. if (!name) { return false }
  6488. if (e.shiftKey && !cm.state.keySeq) {
  6489. // First try to resolve full name (including 'Shift-'). Failing
  6490. // that, see if there is a cursor-motion command (starting with
  6491. // 'go') bound to the keyname without 'Shift-'.
  6492. return dispatchKey(cm, "Shift-" + name, e, function (b) { return doHandleBinding(cm, b, true); })
  6493. || dispatchKey(cm, name, e, function (b) {
  6494. if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion)
  6495. { return doHandleBinding(cm, b) }
  6496. })
  6497. } else {
  6498. return dispatchKey(cm, name, e, function (b) { return doHandleBinding(cm, b); })
  6499. }
  6500. }
  6501. // Handle a key from the keypress event
  6502. function handleCharBinding(cm, e, ch) {
  6503. return dispatchKey(cm, "'" + ch + "'", e, function (b) { return doHandleBinding(cm, b, true); })
  6504. }
  6505. var lastStoppedKey = null;
  6506. function onKeyDown(e) {
  6507. var cm = this;
  6508. cm.curOp.focus = activeElt();
  6509. if (signalDOMEvent(cm, e)) { return }
  6510. // IE does strange things with escape.
  6511. if (ie && ie_version < 11 && e.keyCode == 27) { e.returnValue = false; }
  6512. var code = e.keyCode;
  6513. cm.display.shift = code == 16 || e.shiftKey;
  6514. var handled = handleKeyBinding(cm, e);
  6515. if (presto) {
  6516. lastStoppedKey = handled ? code : null;
  6517. // Opera has no cut event... we try to at least catch the key combo
  6518. if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey))
  6519. { cm.replaceSelection("", null, "cut"); }
  6520. }
  6521. // Turn mouse into crosshair when Alt is held on Mac.
  6522. if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className))
  6523. { showCrossHair(cm); }
  6524. }
  6525. function showCrossHair(cm) {
  6526. var lineDiv = cm.display.lineDiv;
  6527. addClass(lineDiv, "CodeMirror-crosshair");
  6528. function up(e) {
  6529. if (e.keyCode == 18 || !e.altKey) {
  6530. rmClass(lineDiv, "CodeMirror-crosshair");
  6531. off(document, "keyup", up);
  6532. off(document, "mouseover", up);
  6533. }
  6534. }
  6535. on(document, "keyup", up);
  6536. on(document, "mouseover", up);
  6537. }
  6538. function onKeyUp(e) {
  6539. if (e.keyCode == 16) { this.doc.sel.shift = false; }
  6540. signalDOMEvent(this, e);
  6541. }
  6542. function onKeyPress(e) {
  6543. var cm = this;
  6544. if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) { return }
  6545. var keyCode = e.keyCode, charCode = e.charCode;
  6546. if (presto && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return}
  6547. if ((presto && (!e.which || e.which < 10)) && handleKeyBinding(cm, e)) { return }
  6548. var ch = String.fromCharCode(charCode == null ? keyCode : charCode);
  6549. // Some browsers fire keypress events for backspace
  6550. if (ch == "\x08") { return }
  6551. if (handleCharBinding(cm, e, ch)) { return }
  6552. cm.display.input.onKeyPress(e);
  6553. }
  6554. var DOUBLECLICK_DELAY = 400;
  6555. var PastClick = function(time, pos, button) {
  6556. this.time = time;
  6557. this.pos = pos;
  6558. this.button = button;
  6559. };
  6560. PastClick.prototype.compare = function (time, pos, button) {
  6561. return this.time + DOUBLECLICK_DELAY > time &&
  6562. cmp(pos, this.pos) == 0 && button == this.button
  6563. };
  6564. var lastClick, lastDoubleClick;
  6565. function clickRepeat(pos, button) {
  6566. var now = +new Date;
  6567. if (lastDoubleClick && lastDoubleClick.compare(now, pos, button)) {
  6568. lastClick = lastDoubleClick = null;
  6569. return "triple"
  6570. } else if (lastClick && lastClick.compare(now, pos, button)) {
  6571. lastDoubleClick = new PastClick(now, pos, button);
  6572. lastClick = null;
  6573. return "double"
  6574. } else {
  6575. lastClick = new PastClick(now, pos, button);
  6576. lastDoubleClick = null;
  6577. return "single"
  6578. }
  6579. }
  6580. // A mouse down can be a single click, double click, triple click,
  6581. // start of selection drag, start of text drag, new cursor
  6582. // (ctrl-click), rectangle drag (alt-drag), or xwin
  6583. // middle-click-paste. Or it might be a click on something we should
  6584. // not interfere with, such as a scrollbar or widget.
  6585. function onMouseDown(e) {
  6586. var cm = this, display = cm.display;
  6587. if (signalDOMEvent(cm, e) || display.activeTouch && display.input.supportsTouch()) { return }
  6588. display.input.ensurePolled();
  6589. display.shift = e.shiftKey;
  6590. if (eventInWidget(display, e)) {
  6591. if (!webkit) {
  6592. // Briefly turn off draggability, to allow widgets to do
  6593. // normal dragging things.
  6594. display.scroller.draggable = false;
  6595. setTimeout(function () { return display.scroller.draggable = true; }, 100);
  6596. }
  6597. return
  6598. }
  6599. if (clickInGutter(cm, e)) { return }
  6600. var pos = posFromMouse(cm, e), button = e_button(e), repeat = pos ? clickRepeat(pos, button) : "single";
  6601. window.focus();
  6602. // #3261: make sure, that we're not starting a second selection
  6603. if (button == 1 && cm.state.selectingText)
  6604. { cm.state.selectingText(e); }
  6605. if (pos && handleMappedButton(cm, button, pos, repeat, e)) { return }
  6606. if (button == 1) {
  6607. if (pos) { leftButtonDown(cm, pos, repeat, e); }
  6608. else if (e_target(e) == display.scroller) { e_preventDefault(e); }
  6609. } else if (button == 2) {
  6610. if (pos) { extendSelection(cm.doc, pos); }
  6611. setTimeout(function () { return display.input.focus(); }, 20);
  6612. } else if (button == 3) {
  6613. if (captureRightClick) { cm.display.input.onContextMenu(e); }
  6614. else { delayBlurEvent(cm); }
  6615. }
  6616. }
  6617. function handleMappedButton(cm, button, pos, repeat, event) {
  6618. var name = "Click";
  6619. if (repeat == "double") { name = "Double" + name; }
  6620. else if (repeat == "triple") { name = "Triple" + name; }
  6621. name = (button == 1 ? "Left" : button == 2 ? "Middle" : "Right") + name;
  6622. return dispatchKey(cm, addModifierNames(name, event), event, function (bound) {
  6623. if (typeof bound == "string") { bound = commands[bound]; }
  6624. if (!bound) { return false }
  6625. var done = false;
  6626. try {
  6627. if (cm.isReadOnly()) { cm.state.suppressEdits = true; }
  6628. done = bound(cm, pos) != Pass;
  6629. } finally {
  6630. cm.state.suppressEdits = false;
  6631. }
  6632. return done
  6633. })
  6634. }
  6635. function configureMouse(cm, repeat, event) {
  6636. var option = cm.getOption("configureMouse");
  6637. var value = option ? option(cm, repeat, event) : {};
  6638. if (value.unit == null) {
  6639. var rect = chromeOS ? event.shiftKey && event.metaKey : event.altKey;
  6640. value.unit = rect ? "rectangle" : repeat == "single" ? "char" : repeat == "double" ? "word" : "line";
  6641. }
  6642. if (value.extend == null || cm.doc.extend) { value.extend = cm.doc.extend || event.shiftKey; }
  6643. if (value.addNew == null) { value.addNew = mac ? event.metaKey : event.ctrlKey; }
  6644. if (value.moveOnDrag == null) { value.moveOnDrag = !(mac ? event.altKey : event.ctrlKey); }
  6645. return value
  6646. }
  6647. function leftButtonDown(cm, pos, repeat, event) {
  6648. if (ie) { setTimeout(bind(ensureFocus, cm), 0); }
  6649. else { cm.curOp.focus = activeElt(); }
  6650. var behavior = configureMouse(cm, repeat, event);
  6651. var sel = cm.doc.sel, contained;
  6652. if (cm.options.dragDrop && dragAndDrop && !cm.isReadOnly() &&
  6653. repeat == "single" && (contained = sel.contains(pos)) > -1 &&
  6654. (cmp((contained = sel.ranges[contained]).from(), pos) < 0 || pos.xRel > 0) &&
  6655. (cmp(contained.to(), pos) > 0 || pos.xRel < 0))
  6656. { leftButtonStartDrag(cm, event, pos, behavior); }
  6657. else
  6658. { leftButtonSelect(cm, event, pos, behavior); }
  6659. }
  6660. // Start a text drag. When it ends, see if any dragging actually
  6661. // happen, and treat as a click if it didn't.
  6662. function leftButtonStartDrag(cm, event, pos, behavior) {
  6663. var display = cm.display, moved = false;
  6664. var dragEnd = operation(cm, function (e) {
  6665. if (webkit) { display.scroller.draggable = false; }
  6666. cm.state.draggingText = false;
  6667. off(display.wrapper.ownerDocument, "mouseup", dragEnd);
  6668. off(display.wrapper.ownerDocument, "mousemove", mouseMove);
  6669. off(display.scroller, "dragstart", dragStart);
  6670. off(display.scroller, "drop", dragEnd);
  6671. if (!moved) {
  6672. e_preventDefault(e);
  6673. if (!behavior.addNew)
  6674. { extendSelection(cm.doc, pos, null, null, behavior.extend); }
  6675. // Work around unexplainable focus problem in IE9 (#2127) and Chrome (#3081)
  6676. if (webkit || ie && ie_version == 9)
  6677. { setTimeout(function () {display.wrapper.ownerDocument.body.focus(); display.input.focus();}, 20); }
  6678. else
  6679. { display.input.focus(); }
  6680. }
  6681. });
  6682. var mouseMove = function(e2) {
  6683. moved = moved || Math.abs(event.clientX - e2.clientX) + Math.abs(event.clientY - e2.clientY) >= 10;
  6684. };
  6685. var dragStart = function () { return moved = true; };
  6686. // Let the drag handler handle this.
  6687. if (webkit) { display.scroller.draggable = true; }
  6688. cm.state.draggingText = dragEnd;
  6689. dragEnd.copy = !behavior.moveOnDrag;
  6690. // IE's approach to draggable
  6691. if (display.scroller.dragDrop) { display.scroller.dragDrop(); }
  6692. on(display.wrapper.ownerDocument, "mouseup", dragEnd);
  6693. on(display.wrapper.ownerDocument, "mousemove", mouseMove);
  6694. on(display.scroller, "dragstart", dragStart);
  6695. on(display.scroller, "drop", dragEnd);
  6696. delayBlurEvent(cm);
  6697. setTimeout(function () { return display.input.focus(); }, 20);
  6698. }
  6699. function rangeForUnit(cm, pos, unit) {
  6700. if (unit == "char") { return new Range(pos, pos) }
  6701. if (unit == "word") { return cm.findWordAt(pos) }
  6702. if (unit == "line") { return new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))) }
  6703. var result = unit(cm, pos);
  6704. return new Range(result.from, result.to)
  6705. }
  6706. // Normal selection, as opposed to text dragging.
  6707. function leftButtonSelect(cm, event, start, behavior) {
  6708. var display = cm.display, doc = cm.doc;
  6709. e_preventDefault(event);
  6710. var ourRange, ourIndex, startSel = doc.sel, ranges = startSel.ranges;
  6711. if (behavior.addNew && !behavior.extend) {
  6712. ourIndex = doc.sel.contains(start);
  6713. if (ourIndex > -1)
  6714. { ourRange = ranges[ourIndex]; }
  6715. else
  6716. { ourRange = new Range(start, start); }
  6717. } else {
  6718. ourRange = doc.sel.primary();
  6719. ourIndex = doc.sel.primIndex;
  6720. }
  6721. if (behavior.unit == "rectangle") {
  6722. if (!behavior.addNew) { ourRange = new Range(start, start); }
  6723. start = posFromMouse(cm, event, true, true);
  6724. ourIndex = -1;
  6725. } else {
  6726. var range$$1 = rangeForUnit(cm, start, behavior.unit);
  6727. if (behavior.extend)
  6728. { ourRange = extendRange(ourRange, range$$1.anchor, range$$1.head, behavior.extend); }
  6729. else
  6730. { ourRange = range$$1; }
  6731. }
  6732. if (!behavior.addNew) {
  6733. ourIndex = 0;
  6734. setSelection(doc, new Selection([ourRange], 0), sel_mouse);
  6735. startSel = doc.sel;
  6736. } else if (ourIndex == -1) {
  6737. ourIndex = ranges.length;
  6738. setSelection(doc, normalizeSelection(cm, ranges.concat([ourRange]), ourIndex),
  6739. {scroll: false, origin: "*mouse"});
  6740. } else if (ranges.length > 1 && ranges[ourIndex].empty() && behavior.unit == "char" && !behavior.extend) {
  6741. setSelection(doc, normalizeSelection(cm, ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0),
  6742. {scroll: false, origin: "*mouse"});
  6743. startSel = doc.sel;
  6744. } else {
  6745. replaceOneSelection(doc, ourIndex, ourRange, sel_mouse);
  6746. }
  6747. var lastPos = start;
  6748. function extendTo(pos) {
  6749. if (cmp(lastPos, pos) == 0) { return }
  6750. lastPos = pos;
  6751. if (behavior.unit == "rectangle") {
  6752. var ranges = [], tabSize = cm.options.tabSize;
  6753. var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize);
  6754. var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize);
  6755. var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol);
  6756. for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line));
  6757. line <= end; line++) {
  6758. var text = getLine(doc, line).text, leftPos = findColumn(text, left, tabSize);
  6759. if (left == right)
  6760. { ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos))); }
  6761. else if (text.length > leftPos)
  6762. { ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize)))); }
  6763. }
  6764. if (!ranges.length) { ranges.push(new Range(start, start)); }
  6765. setSelection(doc, normalizeSelection(cm, startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex),
  6766. {origin: "*mouse", scroll: false});
  6767. cm.scrollIntoView(pos);
  6768. } else {
  6769. var oldRange = ourRange;
  6770. var range$$1 = rangeForUnit(cm, pos, behavior.unit);
  6771. var anchor = oldRange.anchor, head;
  6772. if (cmp(range$$1.anchor, anchor) > 0) {
  6773. head = range$$1.head;
  6774. anchor = minPos(oldRange.from(), range$$1.anchor);
  6775. } else {
  6776. head = range$$1.anchor;
  6777. anchor = maxPos(oldRange.to(), range$$1.head);
  6778. }
  6779. var ranges$1 = startSel.ranges.slice(0);
  6780. ranges$1[ourIndex] = bidiSimplify(cm, new Range(clipPos(doc, anchor), head));
  6781. setSelection(doc, normalizeSelection(cm, ranges$1, ourIndex), sel_mouse);
  6782. }
  6783. }
  6784. var editorSize = display.wrapper.getBoundingClientRect();
  6785. // Used to ensure timeout re-tries don't fire when another extend
  6786. // happened in the meantime (clearTimeout isn't reliable -- at
  6787. // least on Chrome, the timeouts still happen even when cleared,
  6788. // if the clear happens after their scheduled firing time).
  6789. var counter = 0;
  6790. function extend(e) {
  6791. var curCount = ++counter;
  6792. var cur = posFromMouse(cm, e, true, behavior.unit == "rectangle");
  6793. if (!cur) { return }
  6794. if (cmp(cur, lastPos) != 0) {
  6795. cm.curOp.focus = activeElt();
  6796. extendTo(cur);
  6797. var visible = visibleLines(display, doc);
  6798. if (cur.line >= visible.to || cur.line < visible.from)
  6799. { setTimeout(operation(cm, function () {if (counter == curCount) { extend(e); }}), 150); }
  6800. } else {
  6801. var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0;
  6802. if (outside) { setTimeout(operation(cm, function () {
  6803. if (counter != curCount) { return }
  6804. display.scroller.scrollTop += outside;
  6805. extend(e);
  6806. }), 50); }
  6807. }
  6808. }
  6809. function done(e) {
  6810. cm.state.selectingText = false;
  6811. counter = Infinity;
  6812. // If e is null or undefined we interpret this as someone trying
  6813. // to explicitly cancel the selection rather than the user
  6814. // letting go of the mouse button.
  6815. if (e) {
  6816. e_preventDefault(e);
  6817. display.input.focus();
  6818. }
  6819. off(display.wrapper.ownerDocument, "mousemove", move);
  6820. off(display.wrapper.ownerDocument, "mouseup", up);
  6821. doc.history.lastSelOrigin = null;
  6822. }
  6823. var move = operation(cm, function (e) {
  6824. if (e.buttons === 0 || !e_button(e)) { done(e); }
  6825. else { extend(e); }
  6826. });
  6827. var up = operation(cm, done);
  6828. cm.state.selectingText = up;
  6829. on(display.wrapper.ownerDocument, "mousemove", move);
  6830. on(display.wrapper.ownerDocument, "mouseup", up);
  6831. }
  6832. // Used when mouse-selecting to adjust the anchor to the proper side
  6833. // of a bidi jump depending on the visual position of the head.
  6834. function bidiSimplify(cm, range$$1) {
  6835. var anchor = range$$1.anchor;
  6836. var head = range$$1.head;
  6837. var anchorLine = getLine(cm.doc, anchor.line);
  6838. if (cmp(anchor, head) == 0 && anchor.sticky == head.sticky) { return range$$1 }
  6839. var order = getOrder(anchorLine);
  6840. if (!order) { return range$$1 }
  6841. var index = getBidiPartAt(order, anchor.ch, anchor.sticky), part = order[index];
  6842. if (part.from != anchor.ch && part.to != anchor.ch) { return range$$1 }
  6843. var boundary = index + ((part.from == anchor.ch) == (part.level != 1) ? 0 : 1);
  6844. if (boundary == 0 || boundary == order.length) { return range$$1 }
  6845. // Compute the relative visual position of the head compared to the
  6846. // anchor (<0 is to the left, >0 to the right)
  6847. var leftSide;
  6848. if (head.line != anchor.line) {
  6849. leftSide = (head.line - anchor.line) * (cm.doc.direction == "ltr" ? 1 : -1) > 0;
  6850. } else {
  6851. var headIndex = getBidiPartAt(order, head.ch, head.sticky);
  6852. var dir = headIndex - index || (head.ch - anchor.ch) * (part.level == 1 ? -1 : 1);
  6853. if (headIndex == boundary - 1 || headIndex == boundary)
  6854. { leftSide = dir < 0; }
  6855. else
  6856. { leftSide = dir > 0; }
  6857. }
  6858. var usePart = order[boundary + (leftSide ? -1 : 0)];
  6859. var from = leftSide == (usePart.level == 1);
  6860. var ch = from ? usePart.from : usePart.to, sticky = from ? "after" : "before";
  6861. return anchor.ch == ch && anchor.sticky == sticky ? range$$1 : new Range(new Pos(anchor.line, ch, sticky), head)
  6862. }
  6863. // Determines whether an event happened in the gutter, and fires the
  6864. // handlers for the corresponding event.
  6865. function gutterEvent(cm, e, type, prevent) {
  6866. var mX, mY;
  6867. if (e.touches) {
  6868. mX = e.touches[0].clientX;
  6869. mY = e.touches[0].clientY;
  6870. } else {
  6871. try { mX = e.clientX; mY = e.clientY; }
  6872. catch(e) { return false }
  6873. }
  6874. if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) { return false }
  6875. if (prevent) { e_preventDefault(e); }
  6876. var display = cm.display;
  6877. var lineBox = display.lineDiv.getBoundingClientRect();
  6878. if (mY > lineBox.bottom || !hasHandler(cm, type)) { return e_defaultPrevented(e) }
  6879. mY -= lineBox.top - display.viewOffset;
  6880. for (var i = 0; i < cm.display.gutterSpecs.length; ++i) {
  6881. var g = display.gutters.childNodes[i];
  6882. if (g && g.getBoundingClientRect().right >= mX) {
  6883. var line = lineAtHeight(cm.doc, mY);
  6884. var gutter = cm.display.gutterSpecs[i];
  6885. signal(cm, type, cm, line, gutter.className, e);
  6886. return e_defaultPrevented(e)
  6887. }
  6888. }
  6889. }
  6890. function clickInGutter(cm, e) {
  6891. return gutterEvent(cm, e, "gutterClick", true)
  6892. }
  6893. // CONTEXT MENU HANDLING
  6894. // To make the context menu work, we need to briefly unhide the
  6895. // textarea (making it as unobtrusive as possible) to let the
  6896. // right-click take effect on it.
  6897. function onContextMenu(cm, e) {
  6898. if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) { return }
  6899. if (signalDOMEvent(cm, e, "contextmenu")) { return }
  6900. if (!captureRightClick) { cm.display.input.onContextMenu(e); }
  6901. }
  6902. function contextMenuInGutter(cm, e) {
  6903. if (!hasHandler(cm, "gutterContextMenu")) { return false }
  6904. return gutterEvent(cm, e, "gutterContextMenu", false)
  6905. }
  6906. function themeChanged(cm) {
  6907. cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") +
  6908. cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-");
  6909. clearCaches(cm);
  6910. }
  6911. var Init = {toString: function(){return "CodeMirror.Init"}};
  6912. var defaults = {};
  6913. var optionHandlers = {};
  6914. function defineOptions(CodeMirror) {
  6915. var optionHandlers = CodeMirror.optionHandlers;
  6916. function option(name, deflt, handle, notOnInit) {
  6917. CodeMirror.defaults[name] = deflt;
  6918. if (handle) { optionHandlers[name] =
  6919. notOnInit ? function (cm, val, old) {if (old != Init) { handle(cm, val, old); }} : handle; }
  6920. }
  6921. CodeMirror.defineOption = option;
  6922. // Passed to option handlers when there is no old value.
  6923. CodeMirror.Init = Init;
  6924. // These two are, on init, called from the constructor because they
  6925. // have to be initialized before the editor can start at all.
  6926. option("value", "", function (cm, val) { return cm.setValue(val); }, true);
  6927. option("mode", null, function (cm, val) {
  6928. cm.doc.modeOption = val;
  6929. loadMode(cm);
  6930. }, true);
  6931. option("indentUnit", 2, loadMode, true);
  6932. option("indentWithTabs", false);
  6933. option("smartIndent", true);
  6934. option("tabSize", 4, function (cm) {
  6935. resetModeState(cm);
  6936. clearCaches(cm);
  6937. regChange(cm);
  6938. }, true);
  6939. option("lineSeparator", null, function (cm, val) {
  6940. cm.doc.lineSep = val;
  6941. if (!val) { return }
  6942. var newBreaks = [], lineNo = cm.doc.first;
  6943. cm.doc.iter(function (line) {
  6944. for (var pos = 0;;) {
  6945. var found = line.text.indexOf(val, pos);
  6946. if (found == -1) { break }
  6947. pos = found + val.length;
  6948. newBreaks.push(Pos(lineNo, found));
  6949. }
  6950. lineNo++;
  6951. });
  6952. for (var i = newBreaks.length - 1; i >= 0; i--)
  6953. { replaceRange(cm.doc, val, newBreaks[i], Pos(newBreaks[i].line, newBreaks[i].ch + val.length)); }
  6954. });
  6955. option("specialChars", /[\u0000-\u001f\u007f-\u009f\u00ad\u061c\u200b-\u200f\u2028\u2029\ufeff\ufff9-\ufffc]/g, function (cm, val, old) {
  6956. cm.state.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g");
  6957. if (old != Init) { cm.refresh(); }
  6958. });
  6959. option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function (cm) { return cm.refresh(); }, true);
  6960. option("electricChars", true);
  6961. option("inputStyle", mobile ? "contenteditable" : "textarea", function () {
  6962. throw new Error("inputStyle can not (yet) be changed in a running editor") // FIXME
  6963. }, true);
  6964. option("spellcheck", false, function (cm, val) { return cm.getInputField().spellcheck = val; }, true);
  6965. option("autocorrect", false, function (cm, val) { return cm.getInputField().autocorrect = val; }, true);
  6966. option("autocapitalize", false, function (cm, val) { return cm.getInputField().autocapitalize = val; }, true);
  6967. option("rtlMoveVisually", !windows);
  6968. option("wholeLineUpdateBefore", true);
  6969. option("theme", "default", function (cm) {
  6970. themeChanged(cm);
  6971. updateGutters(cm);
  6972. }, true);
  6973. option("keyMap", "default", function (cm, val, old) {
  6974. var next = getKeyMap(val);
  6975. var prev = old != Init && getKeyMap(old);
  6976. if (prev && prev.detach) { prev.detach(cm, next); }
  6977. if (next.attach) { next.attach(cm, prev || null); }
  6978. });
  6979. option("extraKeys", null);
  6980. option("configureMouse", null);
  6981. option("lineWrapping", false, wrappingChanged, true);
  6982. option("gutters", [], function (cm, val) {
  6983. cm.display.gutterSpecs = getGutters(val, cm.options.lineNumbers);
  6984. updateGutters(cm);
  6985. }, true);
  6986. option("fixedGutter", true, function (cm, val) {
  6987. cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0";
  6988. cm.refresh();
  6989. }, true);
  6990. option("coverGutterNextToScrollbar", false, function (cm) { return updateScrollbars(cm); }, true);
  6991. option("scrollbarStyle", "native", function (cm) {
  6992. initScrollbars(cm);
  6993. updateScrollbars(cm);
  6994. cm.display.scrollbars.setScrollTop(cm.doc.scrollTop);
  6995. cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft);
  6996. }, true);
  6997. option("lineNumbers", false, function (cm, val) {
  6998. cm.display.gutterSpecs = getGutters(cm.options.gutters, val);
  6999. updateGutters(cm);
  7000. }, true);
  7001. option("firstLineNumber", 1, updateGutters, true);
  7002. option("lineNumberFormatter", function (integer) { return integer; }, updateGutters, true);
  7003. option("showCursorWhenSelecting", false, updateSelection, true);
  7004. option("resetSelectionOnContextMenu", true);
  7005. option("lineWiseCopyCut", true);
  7006. option("pasteLinesPerSelection", true);
  7007. option("selectionsMayTouch", false);
  7008. option("readOnly", false, function (cm, val) {
  7009. if (val == "nocursor") {
  7010. onBlur(cm);
  7011. cm.display.input.blur();
  7012. }
  7013. cm.display.input.readOnlyChanged(val);
  7014. });
  7015. option("disableInput", false, function (cm, val) {if (!val) { cm.display.input.reset(); }}, true);
  7016. option("dragDrop", true, dragDropChanged);
  7017. option("allowDropFileTypes", null);
  7018. option("cursorBlinkRate", 530);
  7019. option("cursorScrollMargin", 0);
  7020. option("cursorHeight", 1, updateSelection, true);
  7021. option("singleCursorHeightPerLine", true, updateSelection, true);
  7022. option("workTime", 100);
  7023. option("workDelay", 100);
  7024. option("flattenSpans", true, resetModeState, true);
  7025. option("addModeClass", false, resetModeState, true);
  7026. option("pollInterval", 100);
  7027. option("undoDepth", 200, function (cm, val) { return cm.doc.history.undoDepth = val; });
  7028. option("historyEventDelay", 1250);
  7029. option("viewportMargin", 10, function (cm) { return cm.refresh(); }, true);
  7030. option("maxHighlightLength", 10000, resetModeState, true);
  7031. option("moveInputWithCursor", true, function (cm, val) {
  7032. if (!val) { cm.display.input.resetPosition(); }
  7033. });
  7034. option("tabindex", null, function (cm, val) { return cm.display.input.getField().tabIndex = val || ""; });
  7035. option("autofocus", null);
  7036. option("direction", "ltr", function (cm, val) { return cm.doc.setDirection(val); }, true);
  7037. option("phrases", null);
  7038. }
  7039. function dragDropChanged(cm, value, old) {
  7040. var wasOn = old && old != Init;
  7041. if (!value != !wasOn) {
  7042. var funcs = cm.display.dragFunctions;
  7043. var toggle = value ? on : off;
  7044. toggle(cm.display.scroller, "dragstart", funcs.start);
  7045. toggle(cm.display.scroller, "dragenter", funcs.enter);
  7046. toggle(cm.display.scroller, "dragover", funcs.over);
  7047. toggle(cm.display.scroller, "dragleave", funcs.leave);
  7048. toggle(cm.display.scroller, "drop", funcs.drop);
  7049. }
  7050. }
  7051. function wrappingChanged(cm) {
  7052. if (cm.options.lineWrapping) {
  7053. addClass(cm.display.wrapper, "CodeMirror-wrap");
  7054. cm.display.sizer.style.minWidth = "";
  7055. cm.display.sizerWidth = null;
  7056. } else {
  7057. rmClass(cm.display.wrapper, "CodeMirror-wrap");
  7058. findMaxLine(cm);
  7059. }
  7060. estimateLineHeights(cm);
  7061. regChange(cm);
  7062. clearCaches(cm);
  7063. setTimeout(function () { return updateScrollbars(cm); }, 100);
  7064. }
  7065. // A CodeMirror instance represents an editor. This is the object
  7066. // that user code is usually dealing with.
  7067. function CodeMirror(place, options) {
  7068. var this$1 = this;
  7069. if (!(this instanceof CodeMirror)) { return new CodeMirror(place, options) }
  7070. this.options = options = options ? copyObj(options) : {};
  7071. // Determine effective options based on given values and defaults.
  7072. copyObj(defaults, options, false);
  7073. var doc = options.value;
  7074. if (typeof doc == "string") { doc = new Doc(doc, options.mode, null, options.lineSeparator, options.direction); }
  7075. else if (options.mode) { doc.modeOption = options.mode; }
  7076. this.doc = doc;
  7077. var input = new CodeMirror.inputStyles[options.inputStyle](this);
  7078. var display = this.display = new Display(place, doc, input, options);
  7079. display.wrapper.CodeMirror = this;
  7080. themeChanged(this);
  7081. if (options.lineWrapping)
  7082. { this.display.wrapper.className += " CodeMirror-wrap"; }
  7083. initScrollbars(this);
  7084. this.state = {
  7085. keyMaps: [], // stores maps added by addKeyMap
  7086. overlays: [], // highlighting overlays, as added by addOverlay
  7087. modeGen: 0, // bumped when mode/overlay changes, used to invalidate highlighting info
  7088. overwrite: false,
  7089. delayingBlurEvent: false,
  7090. focused: false,
  7091. suppressEdits: false, // used to disable editing during key handlers when in readOnly mode
  7092. pasteIncoming: -1, cutIncoming: -1, // help recognize paste/cut edits in input.poll
  7093. selectingText: false,
  7094. draggingText: false,
  7095. highlight: new Delayed(), // stores highlight worker timeout
  7096. keySeq: null, // Unfinished key sequence
  7097. specialChars: null
  7098. };
  7099. if (options.autofocus && !mobile) { display.input.focus(); }
  7100. // Override magic textarea content restore that IE sometimes does
  7101. // on our hidden textarea on reload
  7102. if (ie && ie_version < 11) { setTimeout(function () { return this$1.display.input.reset(true); }, 20); }
  7103. registerEventHandlers(this);
  7104. ensureGlobalHandlers();
  7105. startOperation(this);
  7106. this.curOp.forceUpdate = true;
  7107. attachDoc(this, doc);
  7108. if ((options.autofocus && !mobile) || this.hasFocus())
  7109. { setTimeout(bind(onFocus, this), 20); }
  7110. else
  7111. { onBlur(this); }
  7112. for (var opt in optionHandlers) { if (optionHandlers.hasOwnProperty(opt))
  7113. { optionHandlers[opt](this$1, options[opt], Init); } }
  7114. maybeUpdateLineNumberWidth(this);
  7115. if (options.finishInit) { options.finishInit(this); }
  7116. for (var i = 0; i < initHooks.length; ++i) { initHooks[i](this$1); }
  7117. endOperation(this);
  7118. // Suppress optimizelegibility in Webkit, since it breaks text
  7119. // measuring on line wrapping boundaries.
  7120. if (webkit && options.lineWrapping &&
  7121. getComputedStyle(display.lineDiv).textRendering == "optimizelegibility")
  7122. { display.lineDiv.style.textRendering = "auto"; }
  7123. }
  7124. // The default configuration options.
  7125. CodeMirror.defaults = defaults;
  7126. // Functions to run when options are changed.
  7127. CodeMirror.optionHandlers = optionHandlers;
  7128. // Attach the necessary event handlers when initializing the editor
  7129. function registerEventHandlers(cm) {
  7130. var d = cm.display;
  7131. on(d.scroller, "mousedown", operation(cm, onMouseDown));
  7132. // Older IE's will not fire a second mousedown for a double click
  7133. if (ie && ie_version < 11)
  7134. { on(d.scroller, "dblclick", operation(cm, function (e) {
  7135. if (signalDOMEvent(cm, e)) { return }
  7136. var pos = posFromMouse(cm, e);
  7137. if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) { return }
  7138. e_preventDefault(e);
  7139. var word = cm.findWordAt(pos);
  7140. extendSelection(cm.doc, word.anchor, word.head);
  7141. })); }
  7142. else
  7143. { on(d.scroller, "dblclick", function (e) { return signalDOMEvent(cm, e) || e_preventDefault(e); }); }
  7144. // Some browsers fire contextmenu *after* opening the menu, at
  7145. // which point we can't mess with it anymore. Context menu is
  7146. // handled in onMouseDown for these browsers.
  7147. on(d.scroller, "contextmenu", function (e) { return onContextMenu(cm, e); });
  7148. // Used to suppress mouse event handling when a touch happens
  7149. var touchFinished, prevTouch = {end: 0};
  7150. function finishTouch() {
  7151. if (d.activeTouch) {
  7152. touchFinished = setTimeout(function () { return d.activeTouch = null; }, 1000);
  7153. prevTouch = d.activeTouch;
  7154. prevTouch.end = +new Date;
  7155. }
  7156. }
  7157. function isMouseLikeTouchEvent(e) {
  7158. if (e.touches.length != 1) { return false }
  7159. var touch = e.touches[0];
  7160. return touch.radiusX <= 1 && touch.radiusY <= 1
  7161. }
  7162. function farAway(touch, other) {
  7163. if (other.left == null) { return true }
  7164. var dx = other.left - touch.left, dy = other.top - touch.top;
  7165. return dx * dx + dy * dy > 20 * 20
  7166. }
  7167. on(d.scroller, "touchstart", function (e) {
  7168. if (!signalDOMEvent(cm, e) && !isMouseLikeTouchEvent(e) && !clickInGutter(cm, e)) {
  7169. d.input.ensurePolled();
  7170. clearTimeout(touchFinished);
  7171. var now = +new Date;
  7172. d.activeTouch = {start: now, moved: false,
  7173. prev: now - prevTouch.end <= 300 ? prevTouch : null};
  7174. if (e.touches.length == 1) {
  7175. d.activeTouch.left = e.touches[0].pageX;
  7176. d.activeTouch.top = e.touches[0].pageY;
  7177. }
  7178. }
  7179. });
  7180. on(d.scroller, "touchmove", function () {
  7181. if (d.activeTouch) { d.activeTouch.moved = true; }
  7182. });
  7183. on(d.scroller, "touchend", function (e) {
  7184. var touch = d.activeTouch;
  7185. if (touch && !eventInWidget(d, e) && touch.left != null &&
  7186. !touch.moved && new Date - touch.start < 300) {
  7187. var pos = cm.coordsChar(d.activeTouch, "page"), range;
  7188. if (!touch.prev || farAway(touch, touch.prev)) // Single tap
  7189. { range = new Range(pos, pos); }
  7190. else if (!touch.prev.prev || farAway(touch, touch.prev.prev)) // Double tap
  7191. { range = cm.findWordAt(pos); }
  7192. else // Triple tap
  7193. { range = new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))); }
  7194. cm.setSelection(range.anchor, range.head);
  7195. cm.focus();
  7196. e_preventDefault(e);
  7197. }
  7198. finishTouch();
  7199. });
  7200. on(d.scroller, "touchcancel", finishTouch);
  7201. // Sync scrolling between fake scrollbars and real scrollable
  7202. // area, ensure viewport is updated when scrolling.
  7203. on(d.scroller, "scroll", function () {
  7204. if (d.scroller.clientHeight) {
  7205. updateScrollTop(cm, d.scroller.scrollTop);
  7206. setScrollLeft(cm, d.scroller.scrollLeft, true);
  7207. signal(cm, "scroll", cm);
  7208. }
  7209. });
  7210. // Listen to wheel events in order to try and update the viewport on time.
  7211. on(d.scroller, "mousewheel", function (e) { return onScrollWheel(cm, e); });
  7212. on(d.scroller, "DOMMouseScroll", function (e) { return onScrollWheel(cm, e); });
  7213. // Prevent wrapper from ever scrolling
  7214. on(d.wrapper, "scroll", function () { return d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; });
  7215. d.dragFunctions = {
  7216. enter: function (e) {if (!signalDOMEvent(cm, e)) { e_stop(e); }},
  7217. over: function (e) {if (!signalDOMEvent(cm, e)) { onDragOver(cm, e); e_stop(e); }},
  7218. start: function (e) { return onDragStart(cm, e); },
  7219. drop: operation(cm, onDrop),
  7220. leave: function (e) {if (!signalDOMEvent(cm, e)) { clearDragCursor(cm); }}
  7221. };
  7222. var inp = d.input.getField();
  7223. on(inp, "keyup", function (e) { return onKeyUp.call(cm, e); });
  7224. on(inp, "keydown", operation(cm, onKeyDown));
  7225. on(inp, "keypress", operation(cm, onKeyPress));
  7226. on(inp, "focus", function (e) { return onFocus(cm, e); });
  7227. on(inp, "blur", function (e) { return onBlur(cm, e); });
  7228. }
  7229. var initHooks = [];
  7230. CodeMirror.defineInitHook = function (f) { return initHooks.push(f); };
  7231. // Indent the given line. The how parameter can be "smart",
  7232. // "add"/null, "subtract", or "prev". When aggressive is false
  7233. // (typically set to true for forced single-line indents), empty
  7234. // lines are not indented, and places where the mode returns Pass
  7235. // are left alone.
  7236. function indentLine(cm, n, how, aggressive) {
  7237. var doc = cm.doc, state;
  7238. if (how == null) { how = "add"; }
  7239. if (how == "smart") {
  7240. // Fall back to "prev" when the mode doesn't have an indentation
  7241. // method.
  7242. if (!doc.mode.indent) { how = "prev"; }
  7243. else { state = getContextBefore(cm, n).state; }
  7244. }
  7245. var tabSize = cm.options.tabSize;
  7246. var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize);
  7247. if (line.stateAfter) { line.stateAfter = null; }
  7248. var curSpaceString = line.text.match(/^\s*/)[0], indentation;
  7249. if (!aggressive && !/\S/.test(line.text)) {
  7250. indentation = 0;
  7251. how = "not";
  7252. } else if (how == "smart") {
  7253. indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text);
  7254. if (indentation == Pass || indentation > 150) {
  7255. if (!aggressive) { return }
  7256. how = "prev";
  7257. }
  7258. }
  7259. if (how == "prev") {
  7260. if (n > doc.first) { indentation = countColumn(getLine(doc, n-1).text, null, tabSize); }
  7261. else { indentation = 0; }
  7262. } else if (how == "add") {
  7263. indentation = curSpace + cm.options.indentUnit;
  7264. } else if (how == "subtract") {
  7265. indentation = curSpace - cm.options.indentUnit;
  7266. } else if (typeof how == "number") {
  7267. indentation = curSpace + how;
  7268. }
  7269. indentation = Math.max(0, indentation);
  7270. var indentString = "", pos = 0;
  7271. if (cm.options.indentWithTabs)
  7272. { for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";} }
  7273. if (pos < indentation) { indentString += spaceStr(indentation - pos); }
  7274. if (indentString != curSpaceString) {
  7275. replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input");
  7276. line.stateAfter = null;
  7277. return true
  7278. } else {
  7279. // Ensure that, if the cursor was in the whitespace at the start
  7280. // of the line, it is moved to the end of that space.
  7281. for (var i$1 = 0; i$1 < doc.sel.ranges.length; i$1++) {
  7282. var range = doc.sel.ranges[i$1];
  7283. if (range.head.line == n && range.head.ch < curSpaceString.length) {
  7284. var pos$1 = Pos(n, curSpaceString.length);
  7285. replaceOneSelection(doc, i$1, new Range(pos$1, pos$1));
  7286. break
  7287. }
  7288. }
  7289. }
  7290. }
  7291. // This will be set to a {lineWise: bool, text: [string]} object, so
  7292. // that, when pasting, we know what kind of selections the copied
  7293. // text was made out of.
  7294. var lastCopied = null;
  7295. function setLastCopied(newLastCopied) {
  7296. lastCopied = newLastCopied;
  7297. }
  7298. function applyTextInput(cm, inserted, deleted, sel, origin) {
  7299. var doc = cm.doc;
  7300. cm.display.shift = false;
  7301. if (!sel) { sel = doc.sel; }
  7302. var recent = +new Date - 200;
  7303. var paste = origin == "paste" || cm.state.pasteIncoming > recent;
  7304. var textLines = splitLinesAuto(inserted), multiPaste = null;
  7305. // When pasting N lines into N selections, insert one line per selection
  7306. if (paste && sel.ranges.length > 1) {
  7307. if (lastCopied && lastCopied.text.join("\n") == inserted) {
  7308. if (sel.ranges.length % lastCopied.text.length == 0) {
  7309. multiPaste = [];
  7310. for (var i = 0; i < lastCopied.text.length; i++)
  7311. { multiPaste.push(doc.splitLines(lastCopied.text[i])); }
  7312. }
  7313. } else if (textLines.length == sel.ranges.length && cm.options.pasteLinesPerSelection) {
  7314. multiPaste = map(textLines, function (l) { return [l]; });
  7315. }
  7316. }
  7317. var updateInput = cm.curOp.updateInput;
  7318. // Normal behavior is to insert the new text into every selection
  7319. for (var i$1 = sel.ranges.length - 1; i$1 >= 0; i$1--) {
  7320. var range$$1 = sel.ranges[i$1];
  7321. var from = range$$1.from(), to = range$$1.to();
  7322. if (range$$1.empty()) {
  7323. if (deleted && deleted > 0) // Handle deletion
  7324. { from = Pos(from.line, from.ch - deleted); }
  7325. else if (cm.state.overwrite && !paste) // Handle overwrite
  7326. { to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length)); }
  7327. else if (paste && lastCopied && lastCopied.lineWise && lastCopied.text.join("\n") == inserted)
  7328. { from = to = Pos(from.line, 0); }
  7329. }
  7330. var changeEvent = {from: from, to: to, text: multiPaste ? multiPaste[i$1 % multiPaste.length] : textLines,
  7331. origin: origin || (paste ? "paste" : cm.state.cutIncoming > recent ? "cut" : "+input")};
  7332. makeChange(cm.doc, changeEvent);
  7333. signalLater(cm, "inputRead", cm, changeEvent);
  7334. }
  7335. if (inserted && !paste)
  7336. { triggerElectric(cm, inserted); }
  7337. ensureCursorVisible(cm);
  7338. if (cm.curOp.updateInput < 2) { cm.curOp.updateInput = updateInput; }
  7339. cm.curOp.typing = true;
  7340. cm.state.pasteIncoming = cm.state.cutIncoming = -1;
  7341. }
  7342. function handlePaste(e, cm) {
  7343. var pasted = e.clipboardData && e.clipboardData.getData("Text");
  7344. if (pasted) {
  7345. e.preventDefault();
  7346. if (!cm.isReadOnly() && !cm.options.disableInput)
  7347. { runInOp(cm, function () { return applyTextInput(cm, pasted, 0, null, "paste"); }); }
  7348. return true
  7349. }
  7350. }
  7351. function triggerElectric(cm, inserted) {
  7352. // When an 'electric' character is inserted, immediately trigger a reindent
  7353. if (!cm.options.electricChars || !cm.options.smartIndent) { return }
  7354. var sel = cm.doc.sel;
  7355. for (var i = sel.ranges.length - 1; i >= 0; i--) {
  7356. var range$$1 = sel.ranges[i];
  7357. if (range$$1.head.ch > 100 || (i && sel.ranges[i - 1].head.line == range$$1.head.line)) { continue }
  7358. var mode = cm.getModeAt(range$$1.head);
  7359. var indented = false;
  7360. if (mode.electricChars) {
  7361. for (var j = 0; j < mode.electricChars.length; j++)
  7362. { if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) {
  7363. indented = indentLine(cm, range$$1.head.line, "smart");
  7364. break
  7365. } }
  7366. } else if (mode.electricInput) {
  7367. if (mode.electricInput.test(getLine(cm.doc, range$$1.head.line).text.slice(0, range$$1.head.ch)))
  7368. { indented = indentLine(cm, range$$1.head.line, "smart"); }
  7369. }
  7370. if (indented) { signalLater(cm, "electricInput", cm, range$$1.head.line); }
  7371. }
  7372. }
  7373. function copyableRanges(cm) {
  7374. var text = [], ranges = [];
  7375. for (var i = 0; i < cm.doc.sel.ranges.length; i++) {
  7376. var line = cm.doc.sel.ranges[i].head.line;
  7377. var lineRange = {anchor: Pos(line, 0), head: Pos(line + 1, 0)};
  7378. ranges.push(lineRange);
  7379. text.push(cm.getRange(lineRange.anchor, lineRange.head));
  7380. }
  7381. return {text: text, ranges: ranges}
  7382. }
  7383. function disableBrowserMagic(field, spellcheck, autocorrect, autocapitalize) {
  7384. field.setAttribute("autocorrect", autocorrect ? "" : "off");
  7385. field.setAttribute("autocapitalize", autocapitalize ? "" : "off");
  7386. field.setAttribute("spellcheck", !!spellcheck);
  7387. }
  7388. function hiddenTextarea() {
  7389. var te = elt("textarea", null, null, "position: absolute; bottom: -1em; padding: 0; width: 1px; height: 1em; outline: none");
  7390. var div = elt("div", [te], null, "overflow: hidden; position: relative; width: 3px; height: 0px;");
  7391. // The textarea is kept positioned near the cursor to prevent the
  7392. // fact that it'll be scrolled into view on input from scrolling
  7393. // our fake cursor out of view. On webkit, when wrap=off, paste is
  7394. // very slow. So make the area wide instead.
  7395. if (webkit) { te.style.width = "1000px"; }
  7396. else { te.setAttribute("wrap", "off"); }
  7397. // If border: 0; -- iOS fails to open keyboard (issue #1287)
  7398. if (ios) { te.style.border = "1px solid black"; }
  7399. disableBrowserMagic(te);
  7400. return div
  7401. }
  7402. // The publicly visible API. Note that methodOp(f) means
  7403. // 'wrap f in an operation, performed on its `this` parameter'.
  7404. // This is not the complete set of editor methods. Most of the
  7405. // methods defined on the Doc type are also injected into
  7406. // CodeMirror.prototype, for backwards compatibility and
  7407. // convenience.
  7408. function addEditorMethods(CodeMirror) {
  7409. var optionHandlers = CodeMirror.optionHandlers;
  7410. var helpers = CodeMirror.helpers = {};
  7411. CodeMirror.prototype = {
  7412. constructor: CodeMirror,
  7413. focus: function(){window.focus(); this.display.input.focus();},
  7414. setOption: function(option, value) {
  7415. var options = this.options, old = options[option];
  7416. if (options[option] == value && option != "mode") { return }
  7417. options[option] = value;
  7418. if (optionHandlers.hasOwnProperty(option))
  7419. { operation(this, optionHandlers[option])(this, value, old); }
  7420. signal(this, "optionChange", this, option);
  7421. },
  7422. getOption: function(option) {return this.options[option]},
  7423. getDoc: function() {return this.doc},
  7424. addKeyMap: function(map$$1, bottom) {
  7425. this.state.keyMaps[bottom ? "push" : "unshift"](getKeyMap(map$$1));
  7426. },
  7427. removeKeyMap: function(map$$1) {
  7428. var maps = this.state.keyMaps;
  7429. for (var i = 0; i < maps.length; ++i)
  7430. { if (maps[i] == map$$1 || maps[i].name == map$$1) {
  7431. maps.splice(i, 1);
  7432. return true
  7433. } }
  7434. },
  7435. addOverlay: methodOp(function(spec, options) {
  7436. var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec);
  7437. if (mode.startState) { throw new Error("Overlays may not be stateful.") }
  7438. insertSorted(this.state.overlays,
  7439. {mode: mode, modeSpec: spec, opaque: options && options.opaque,
  7440. priority: (options && options.priority) || 0},
  7441. function (overlay) { return overlay.priority; });
  7442. this.state.modeGen++;
  7443. regChange(this);
  7444. }),
  7445. removeOverlay: methodOp(function(spec) {
  7446. var this$1 = this;
  7447. var overlays = this.state.overlays;
  7448. for (var i = 0; i < overlays.length; ++i) {
  7449. var cur = overlays[i].modeSpec;
  7450. if (cur == spec || typeof spec == "string" && cur.name == spec) {
  7451. overlays.splice(i, 1);
  7452. this$1.state.modeGen++;
  7453. regChange(this$1);
  7454. return
  7455. }
  7456. }
  7457. }),
  7458. indentLine: methodOp(function(n, dir, aggressive) {
  7459. if (typeof dir != "string" && typeof dir != "number") {
  7460. if (dir == null) { dir = this.options.smartIndent ? "smart" : "prev"; }
  7461. else { dir = dir ? "add" : "subtract"; }
  7462. }
  7463. if (isLine(this.doc, n)) { indentLine(this, n, dir, aggressive); }
  7464. }),
  7465. indentSelection: methodOp(function(how) {
  7466. var this$1 = this;
  7467. var ranges = this.doc.sel.ranges, end = -1;
  7468. for (var i = 0; i < ranges.length; i++) {
  7469. var range$$1 = ranges[i];
  7470. if (!range$$1.empty()) {
  7471. var from = range$$1.from(), to = range$$1.to();
  7472. var start = Math.max(end, from.line);
  7473. end = Math.min(this$1.lastLine(), to.line - (to.ch ? 0 : 1)) + 1;
  7474. for (var j = start; j < end; ++j)
  7475. { indentLine(this$1, j, how); }
  7476. var newRanges = this$1.doc.sel.ranges;
  7477. if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i].from().ch > 0)
  7478. { replaceOneSelection(this$1.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll); }
  7479. } else if (range$$1.head.line > end) {
  7480. indentLine(this$1, range$$1.head.line, how, true);
  7481. end = range$$1.head.line;
  7482. if (i == this$1.doc.sel.primIndex) { ensureCursorVisible(this$1); }
  7483. }
  7484. }
  7485. }),
  7486. // Fetch the parser token for a given character. Useful for hacks
  7487. // that want to inspect the mode state (say, for completion).
  7488. getTokenAt: function(pos, precise) {
  7489. return takeToken(this, pos, precise)
  7490. },
  7491. getLineTokens: function(line, precise) {
  7492. return takeToken(this, Pos(line), precise, true)
  7493. },
  7494. getTokenTypeAt: function(pos) {
  7495. pos = clipPos(this.doc, pos);
  7496. var styles = getLineStyles(this, getLine(this.doc, pos.line));
  7497. var before = 0, after = (styles.length - 1) / 2, ch = pos.ch;
  7498. var type;
  7499. if (ch == 0) { type = styles[2]; }
  7500. else { for (;;) {
  7501. var mid = (before + after) >> 1;
  7502. if ((mid ? styles[mid * 2 - 1] : 0) >= ch) { after = mid; }
  7503. else if (styles[mid * 2 + 1] < ch) { before = mid + 1; }
  7504. else { type = styles[mid * 2 + 2]; break }
  7505. } }
  7506. var cut = type ? type.indexOf("overlay ") : -1;
  7507. return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1)
  7508. },
  7509. getModeAt: function(pos) {
  7510. var mode = this.doc.mode;
  7511. if (!mode.innerMode) { return mode }
  7512. return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode
  7513. },
  7514. getHelper: function(pos, type) {
  7515. return this.getHelpers(pos, type)[0]
  7516. },
  7517. getHelpers: function(pos, type) {
  7518. var this$1 = this;
  7519. var found = [];
  7520. if (!helpers.hasOwnProperty(type)) { return found }
  7521. var help = helpers[type], mode = this.getModeAt(pos);
  7522. if (typeof mode[type] == "string") {
  7523. if (help[mode[type]]) { found.push(help[mode[type]]); }
  7524. } else if (mode[type]) {
  7525. for (var i = 0; i < mode[type].length; i++) {
  7526. var val = help[mode[type][i]];
  7527. if (val) { found.push(val); }
  7528. }
  7529. } else if (mode.helperType && help[mode.helperType]) {
  7530. found.push(help[mode.helperType]);
  7531. } else if (help[mode.name]) {
  7532. found.push(help[mode.name]);
  7533. }
  7534. for (var i$1 = 0; i$1 < help._global.length; i$1++) {
  7535. var cur = help._global[i$1];
  7536. if (cur.pred(mode, this$1) && indexOf(found, cur.val) == -1)
  7537. { found.push(cur.val); }
  7538. }
  7539. return found
  7540. },
  7541. getStateAfter: function(line, precise) {
  7542. var doc = this.doc;
  7543. line = clipLine(doc, line == null ? doc.first + doc.size - 1: line);
  7544. return getContextBefore(this, line + 1, precise).state
  7545. },
  7546. cursorCoords: function(start, mode) {
  7547. var pos, range$$1 = this.doc.sel.primary();
  7548. if (start == null) { pos = range$$1.head; }
  7549. else if (typeof start == "object") { pos = clipPos(this.doc, start); }
  7550. else { pos = start ? range$$1.from() : range$$1.to(); }
  7551. return cursorCoords(this, pos, mode || "page")
  7552. },
  7553. charCoords: function(pos, mode) {
  7554. return charCoords(this, clipPos(this.doc, pos), mode || "page")
  7555. },
  7556. coordsChar: function(coords, mode) {
  7557. coords = fromCoordSystem(this, coords, mode || "page");
  7558. return coordsChar(this, coords.left, coords.top)
  7559. },
  7560. lineAtHeight: function(height, mode) {
  7561. height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top;
  7562. return lineAtHeight(this.doc, height + this.display.viewOffset)
  7563. },
  7564. heightAtLine: function(line, mode, includeWidgets) {
  7565. var end = false, lineObj;
  7566. if (typeof line == "number") {
  7567. var last = this.doc.first + this.doc.size - 1;
  7568. if (line < this.doc.first) { line = this.doc.first; }
  7569. else if (line > last) { line = last; end = true; }
  7570. lineObj = getLine(this.doc, line);
  7571. } else {
  7572. lineObj = line;
  7573. }
  7574. return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || "page", includeWidgets || end).top +
  7575. (end ? this.doc.height - heightAtLine(lineObj) : 0)
  7576. },
  7577. defaultTextHeight: function() { return textHeight(this.display) },
  7578. defaultCharWidth: function() { return charWidth(this.display) },
  7579. getViewport: function() { return {from: this.display.viewFrom, to: this.display.viewTo}},
  7580. addWidget: function(pos, node, scroll, vert, horiz) {
  7581. var display = this.display;
  7582. pos = cursorCoords(this, clipPos(this.doc, pos));
  7583. var top = pos.bottom, left = pos.left;
  7584. node.style.position = "absolute";
  7585. node.setAttribute("cm-ignore-events", "true");
  7586. this.display.input.setUneditable(node);
  7587. display.sizer.appendChild(node);
  7588. if (vert == "over") {
  7589. top = pos.top;
  7590. } else if (vert == "above" || vert == "near") {
  7591. var vspace = Math.max(display.wrapper.clientHeight, this.doc.height),
  7592. hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth);
  7593. // Default to positioning above (if specified and possible); otherwise default to positioning below
  7594. if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight)
  7595. { top = pos.top - node.offsetHeight; }
  7596. else if (pos.bottom + node.offsetHeight <= vspace)
  7597. { top = pos.bottom; }
  7598. if (left + node.offsetWidth > hspace)
  7599. { left = hspace - node.offsetWidth; }
  7600. }
  7601. node.style.top = top + "px";
  7602. node.style.left = node.style.right = "";
  7603. if (horiz == "right") {
  7604. left = display.sizer.clientWidth - node.offsetWidth;
  7605. node.style.right = "0px";
  7606. } else {
  7607. if (horiz == "left") { left = 0; }
  7608. else if (horiz == "middle") { left = (display.sizer.clientWidth - node.offsetWidth) / 2; }
  7609. node.style.left = left + "px";
  7610. }
  7611. if (scroll)
  7612. { scrollIntoView(this, {left: left, top: top, right: left + node.offsetWidth, bottom: top + node.offsetHeight}); }
  7613. },
  7614. triggerOnKeyDown: methodOp(onKeyDown),
  7615. triggerOnKeyPress: methodOp(onKeyPress),
  7616. triggerOnKeyUp: onKeyUp,
  7617. triggerOnMouseDown: methodOp(onMouseDown),
  7618. execCommand: function(cmd) {
  7619. if (commands.hasOwnProperty(cmd))
  7620. { return commands[cmd].call(null, this) }
  7621. },
  7622. triggerElectric: methodOp(function(text) { triggerElectric(this, text); }),
  7623. findPosH: function(from, amount, unit, visually) {
  7624. var this$1 = this;
  7625. var dir = 1;
  7626. if (amount < 0) { dir = -1; amount = -amount; }
  7627. var cur = clipPos(this.doc, from);
  7628. for (var i = 0; i < amount; ++i) {
  7629. cur = findPosH(this$1.doc, cur, dir, unit, visually);
  7630. if (cur.hitSide) { break }
  7631. }
  7632. return cur
  7633. },
  7634. moveH: methodOp(function(dir, unit) {
  7635. var this$1 = this;
  7636. this.extendSelectionsBy(function (range$$1) {
  7637. if (this$1.display.shift || this$1.doc.extend || range$$1.empty())
  7638. { return findPosH(this$1.doc, range$$1.head, dir, unit, this$1.options.rtlMoveVisually) }
  7639. else
  7640. { return dir < 0 ? range$$1.from() : range$$1.to() }
  7641. }, sel_move);
  7642. }),
  7643. deleteH: methodOp(function(dir, unit) {
  7644. var sel = this.doc.sel, doc = this.doc;
  7645. if (sel.somethingSelected())
  7646. { doc.replaceSelection("", null, "+delete"); }
  7647. else
  7648. { deleteNearSelection(this, function (range$$1) {
  7649. var other = findPosH(doc, range$$1.head, dir, unit, false);
  7650. return dir < 0 ? {from: other, to: range$$1.head} : {from: range$$1.head, to: other}
  7651. }); }
  7652. }),
  7653. findPosV: function(from, amount, unit, goalColumn) {
  7654. var this$1 = this;
  7655. var dir = 1, x = goalColumn;
  7656. if (amount < 0) { dir = -1; amount = -amount; }
  7657. var cur = clipPos(this.doc, from);
  7658. for (var i = 0; i < amount; ++i) {
  7659. var coords = cursorCoords(this$1, cur, "div");
  7660. if (x == null) { x = coords.left; }
  7661. else { coords.left = x; }
  7662. cur = findPosV(this$1, coords, dir, unit);
  7663. if (cur.hitSide) { break }
  7664. }
  7665. return cur
  7666. },
  7667. moveV: methodOp(function(dir, unit) {
  7668. var this$1 = this;
  7669. var doc = this.doc, goals = [];
  7670. var collapse = !this.display.shift && !doc.extend && doc.sel.somethingSelected();
  7671. doc.extendSelectionsBy(function (range$$1) {
  7672. if (collapse)
  7673. { return dir < 0 ? range$$1.from() : range$$1.to() }
  7674. var headPos = cursorCoords(this$1, range$$1.head, "div");
  7675. if (range$$1.goalColumn != null) { headPos.left = range$$1.goalColumn; }
  7676. goals.push(headPos.left);
  7677. var pos = findPosV(this$1, headPos, dir, unit);
  7678. if (unit == "page" && range$$1 == doc.sel.primary())
  7679. { addToScrollTop(this$1, charCoords(this$1, pos, "div").top - headPos.top); }
  7680. return pos
  7681. }, sel_move);
  7682. if (goals.length) { for (var i = 0; i < doc.sel.ranges.length; i++)
  7683. { doc.sel.ranges[i].goalColumn = goals[i]; } }
  7684. }),
  7685. // Find the word at the given position (as returned by coordsChar).
  7686. findWordAt: function(pos) {
  7687. var doc = this.doc, line = getLine(doc, pos.line).text;
  7688. var start = pos.ch, end = pos.ch;
  7689. if (line) {
  7690. var helper = this.getHelper(pos, "wordChars");
  7691. if ((pos.sticky == "before" || end == line.length) && start) { --start; } else { ++end; }
  7692. var startChar = line.charAt(start);
  7693. var check = isWordChar(startChar, helper)
  7694. ? function (ch) { return isWordChar(ch, helper); }
  7695. : /\s/.test(startChar) ? function (ch) { return /\s/.test(ch); }
  7696. : function (ch) { return (!/\s/.test(ch) && !isWordChar(ch)); };
  7697. while (start > 0 && check(line.charAt(start - 1))) { --start; }
  7698. while (end < line.length && check(line.charAt(end))) { ++end; }
  7699. }
  7700. return new Range(Pos(pos.line, start), Pos(pos.line, end))
  7701. },
  7702. toggleOverwrite: function(value) {
  7703. if (value != null && value == this.state.overwrite) { return }
  7704. if (this.state.overwrite = !this.state.overwrite)
  7705. { addClass(this.display.cursorDiv, "CodeMirror-overwrite"); }
  7706. else
  7707. { rmClass(this.display.cursorDiv, "CodeMirror-overwrite"); }
  7708. signal(this, "overwriteToggle", this, this.state.overwrite);
  7709. },
  7710. hasFocus: function() { return this.display.input.getField() == activeElt() },
  7711. isReadOnly: function() { return !!(this.options.readOnly || this.doc.cantEdit) },
  7712. scrollTo: methodOp(function (x, y) { scrollToCoords(this, x, y); }),
  7713. getScrollInfo: function() {
  7714. var scroller = this.display.scroller;
  7715. return {left: scroller.scrollLeft, top: scroller.scrollTop,
  7716. height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight,
  7717. width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth,
  7718. clientHeight: displayHeight(this), clientWidth: displayWidth(this)}
  7719. },
  7720. scrollIntoView: methodOp(function(range$$1, margin) {
  7721. if (range$$1 == null) {
  7722. range$$1 = {from: this.doc.sel.primary().head, to: null};
  7723. if (margin == null) { margin = this.options.cursorScrollMargin; }
  7724. } else if (typeof range$$1 == "number") {
  7725. range$$1 = {from: Pos(range$$1, 0), to: null};
  7726. } else if (range$$1.from == null) {
  7727. range$$1 = {from: range$$1, to: null};
  7728. }
  7729. if (!range$$1.to) { range$$1.to = range$$1.from; }
  7730. range$$1.margin = margin || 0;
  7731. if (range$$1.from.line != null) {
  7732. scrollToRange(this, range$$1);
  7733. } else {
  7734. scrollToCoordsRange(this, range$$1.from, range$$1.to, range$$1.margin);
  7735. }
  7736. }),
  7737. setSize: methodOp(function(width, height) {
  7738. var this$1 = this;
  7739. var interpret = function (val) { return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val; };
  7740. if (width != null) { this.display.wrapper.style.width = interpret(width); }
  7741. if (height != null) { this.display.wrapper.style.height = interpret(height); }
  7742. if (this.options.lineWrapping) { clearLineMeasurementCache(this); }
  7743. var lineNo$$1 = this.display.viewFrom;
  7744. this.doc.iter(lineNo$$1, this.display.viewTo, function (line) {
  7745. if (line.widgets) { for (var i = 0; i < line.widgets.length; i++)
  7746. { if (line.widgets[i].noHScroll) { regLineChange(this$1, lineNo$$1, "widget"); break } } }
  7747. ++lineNo$$1;
  7748. });
  7749. this.curOp.forceUpdate = true;
  7750. signal(this, "refresh", this);
  7751. }),
  7752. operation: function(f){return runInOp(this, f)},
  7753. startOperation: function(){return startOperation(this)},
  7754. endOperation: function(){return endOperation(this)},
  7755. refresh: methodOp(function() {
  7756. var oldHeight = this.display.cachedTextHeight;
  7757. regChange(this);
  7758. this.curOp.forceUpdate = true;
  7759. clearCaches(this);
  7760. scrollToCoords(this, this.doc.scrollLeft, this.doc.scrollTop);
  7761. updateGutterSpace(this.display);
  7762. if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5)
  7763. { estimateLineHeights(this); }
  7764. signal(this, "refresh", this);
  7765. }),
  7766. swapDoc: methodOp(function(doc) {
  7767. var old = this.doc;
  7768. old.cm = null;
  7769. // Cancel the current text selection if any (#5821)
  7770. if (this.state.selectingText) { this.state.selectingText(); }
  7771. attachDoc(this, doc);
  7772. clearCaches(this);
  7773. this.display.input.reset();
  7774. scrollToCoords(this, doc.scrollLeft, doc.scrollTop);
  7775. this.curOp.forceScroll = true;
  7776. signalLater(this, "swapDoc", this, old);
  7777. return old
  7778. }),
  7779. phrase: function(phraseText) {
  7780. var phrases = this.options.phrases;
  7781. return phrases && Object.prototype.hasOwnProperty.call(phrases, phraseText) ? phrases[phraseText] : phraseText
  7782. },
  7783. getInputField: function(){return this.display.input.getField()},
  7784. getWrapperElement: function(){return this.display.wrapper},
  7785. getScrollerElement: function(){return this.display.scroller},
  7786. getGutterElement: function(){return this.display.gutters}
  7787. };
  7788. eventMixin(CodeMirror);
  7789. CodeMirror.registerHelper = function(type, name, value) {
  7790. if (!helpers.hasOwnProperty(type)) { helpers[type] = CodeMirror[type] = {_global: []}; }
  7791. helpers[type][name] = value;
  7792. };
  7793. CodeMirror.registerGlobalHelper = function(type, name, predicate, value) {
  7794. CodeMirror.registerHelper(type, name, value);
  7795. helpers[type]._global.push({pred: predicate, val: value});
  7796. };
  7797. }
  7798. // Used for horizontal relative motion. Dir is -1 or 1 (left or
  7799. // right), unit can be "char", "column" (like char, but doesn't
  7800. // cross line boundaries), "word" (across next word), or "group" (to
  7801. // the start of next group of word or non-word-non-whitespace
  7802. // chars). The visually param controls whether, in right-to-left
  7803. // text, direction 1 means to move towards the next index in the
  7804. // string, or towards the character to the right of the current
  7805. // position. The resulting position will have a hitSide=true
  7806. // property if it reached the end of the document.
  7807. function findPosH(doc, pos, dir, unit, visually) {
  7808. var oldPos = pos;
  7809. var origDir = dir;
  7810. var lineObj = getLine(doc, pos.line);
  7811. function findNextLine() {
  7812. var l = pos.line + dir;
  7813. if (l < doc.first || l >= doc.first + doc.size) { return false }
  7814. pos = new Pos(l, pos.ch, pos.sticky);
  7815. return lineObj = getLine(doc, l)
  7816. }
  7817. function moveOnce(boundToLine) {
  7818. var next;
  7819. if (visually) {
  7820. next = moveVisually(doc.cm, lineObj, pos, dir);
  7821. } else {
  7822. next = moveLogically(lineObj, pos, dir);
  7823. }
  7824. if (next == null) {
  7825. if (!boundToLine && findNextLine())
  7826. { pos = endOfLine(visually, doc.cm, lineObj, pos.line, dir); }
  7827. else
  7828. { return false }
  7829. } else {
  7830. pos = next;
  7831. }
  7832. return true
  7833. }
  7834. if (unit == "char") {
  7835. moveOnce();
  7836. } else if (unit == "column") {
  7837. moveOnce(true);
  7838. } else if (unit == "word" || unit == "group") {
  7839. var sawType = null, group = unit == "group";
  7840. var helper = doc.cm && doc.cm.getHelper(pos, "wordChars");
  7841. for (var first = true;; first = false) {
  7842. if (dir < 0 && !moveOnce(!first)) { break }
  7843. var cur = lineObj.text.charAt(pos.ch) || "\n";
  7844. var type = isWordChar(cur, helper) ? "w"
  7845. : group && cur == "\n" ? "n"
  7846. : !group || /\s/.test(cur) ? null
  7847. : "p";
  7848. if (group && !first && !type) { type = "s"; }
  7849. if (sawType && sawType != type) {
  7850. if (dir < 0) {dir = 1; moveOnce(); pos.sticky = "after";}
  7851. break
  7852. }
  7853. if (type) { sawType = type; }
  7854. if (dir > 0 && !moveOnce(!first)) { break }
  7855. }
  7856. }
  7857. var result = skipAtomic(doc, pos, oldPos, origDir, true);
  7858. if (equalCursorPos(oldPos, result)) { result.hitSide = true; }
  7859. return result
  7860. }
  7861. // For relative vertical movement. Dir may be -1 or 1. Unit can be
  7862. // "page" or "line". The resulting position will have a hitSide=true
  7863. // property if it reached the end of the document.
  7864. function findPosV(cm, pos, dir, unit) {
  7865. var doc = cm.doc, x = pos.left, y;
  7866. if (unit == "page") {
  7867. var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight);
  7868. var moveAmount = Math.max(pageSize - .5 * textHeight(cm.display), 3);
  7869. y = (dir > 0 ? pos.bottom : pos.top) + dir * moveAmount;
  7870. } else if (unit == "line") {
  7871. y = dir > 0 ? pos.bottom + 3 : pos.top - 3;
  7872. }
  7873. var target;
  7874. for (;;) {
  7875. target = coordsChar(cm, x, y);
  7876. if (!target.outside) { break }
  7877. if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break }
  7878. y += dir * 5;
  7879. }
  7880. return target
  7881. }
  7882. // CONTENTEDITABLE INPUT STYLE
  7883. var ContentEditableInput = function(cm) {
  7884. this.cm = cm;
  7885. this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null;
  7886. this.polling = new Delayed();
  7887. this.composing = null;
  7888. this.gracePeriod = false;
  7889. this.readDOMTimeout = null;
  7890. };
  7891. ContentEditableInput.prototype.init = function (display) {
  7892. var this$1 = this;
  7893. var input = this, cm = input.cm;
  7894. var div = input.div = display.lineDiv;
  7895. disableBrowserMagic(div, cm.options.spellcheck, cm.options.autocorrect, cm.options.autocapitalize);
  7896. on(div, "paste", function (e) {
  7897. if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { return }
  7898. // IE doesn't fire input events, so we schedule a read for the pasted content in this way
  7899. if (ie_version <= 11) { setTimeout(operation(cm, function () { return this$1.updateFromDOM(); }), 20); }
  7900. });
  7901. on(div, "compositionstart", function (e) {
  7902. this$1.composing = {data: e.data, done: false};
  7903. });
  7904. on(div, "compositionupdate", function (e) {
  7905. if (!this$1.composing) { this$1.composing = {data: e.data, done: false}; }
  7906. });
  7907. on(div, "compositionend", function (e) {
  7908. if (this$1.composing) {
  7909. if (e.data != this$1.composing.data) { this$1.readFromDOMSoon(); }
  7910. this$1.composing.done = true;
  7911. }
  7912. });
  7913. on(div, "touchstart", function () { return input.forceCompositionEnd(); });
  7914. on(div, "input", function () {
  7915. if (!this$1.composing) { this$1.readFromDOMSoon(); }
  7916. });
  7917. function onCopyCut(e) {
  7918. if (signalDOMEvent(cm, e)) { return }
  7919. if (cm.somethingSelected()) {
  7920. setLastCopied({lineWise: false, text: cm.getSelections()});
  7921. if (e.type == "cut") { cm.replaceSelection("", null, "cut"); }
  7922. } else if (!cm.options.lineWiseCopyCut) {
  7923. return
  7924. } else {
  7925. var ranges = copyableRanges(cm);
  7926. setLastCopied({lineWise: true, text: ranges.text});
  7927. if (e.type == "cut") {
  7928. cm.operation(function () {
  7929. cm.setSelections(ranges.ranges, 0, sel_dontScroll);
  7930. cm.replaceSelection("", null, "cut");
  7931. });
  7932. }
  7933. }
  7934. if (e.clipboardData) {
  7935. e.clipboardData.clearData();
  7936. var content = lastCopied.text.join("\n");
  7937. // iOS exposes the clipboard API, but seems to discard content inserted into it
  7938. e.clipboardData.setData("Text", content);
  7939. if (e.clipboardData.getData("Text") == content) {
  7940. e.preventDefault();
  7941. return
  7942. }
  7943. }
  7944. // Old-fashioned briefly-focus-a-textarea hack
  7945. var kludge = hiddenTextarea(), te = kludge.firstChild;
  7946. cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild);
  7947. te.value = lastCopied.text.join("\n");
  7948. var hadFocus = document.activeElement;
  7949. selectInput(te);
  7950. setTimeout(function () {
  7951. cm.display.lineSpace.removeChild(kludge);
  7952. hadFocus.focus();
  7953. if (hadFocus == div) { input.showPrimarySelection(); }
  7954. }, 50);
  7955. }
  7956. on(div, "copy", onCopyCut);
  7957. on(div, "cut", onCopyCut);
  7958. };
  7959. ContentEditableInput.prototype.prepareSelection = function () {
  7960. var result = prepareSelection(this.cm, false);
  7961. result.focus = this.cm.state.focused;
  7962. return result
  7963. };
  7964. ContentEditableInput.prototype.showSelection = function (info, takeFocus) {
  7965. if (!info || !this.cm.display.view.length) { return }
  7966. if (info.focus || takeFocus) { this.showPrimarySelection(); }
  7967. this.showMultipleSelections(info);
  7968. };
  7969. ContentEditableInput.prototype.getSelection = function () {
  7970. return this.cm.display.wrapper.ownerDocument.getSelection()
  7971. };
  7972. ContentEditableInput.prototype.showPrimarySelection = function () {
  7973. var sel = this.getSelection(), cm = this.cm, prim = cm.doc.sel.primary();
  7974. var from = prim.from(), to = prim.to();
  7975. if (cm.display.viewTo == cm.display.viewFrom || from.line >= cm.display.viewTo || to.line < cm.display.viewFrom) {
  7976. sel.removeAllRanges();
  7977. return
  7978. }
  7979. var curAnchor = domToPos(cm, sel.anchorNode, sel.anchorOffset);
  7980. var curFocus = domToPos(cm, sel.focusNode, sel.focusOffset);
  7981. if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad &&
  7982. cmp(minPos(curAnchor, curFocus), from) == 0 &&
  7983. cmp(maxPos(curAnchor, curFocus), to) == 0)
  7984. { return }
  7985. var view = cm.display.view;
  7986. var start = (from.line >= cm.display.viewFrom && posToDOM(cm, from)) ||
  7987. {node: view[0].measure.map[2], offset: 0};
  7988. var end = to.line < cm.display.viewTo && posToDOM(cm, to);
  7989. if (!end) {
  7990. var measure = view[view.length - 1].measure;
  7991. var map$$1 = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map;
  7992. end = {node: map$$1[map$$1.length - 1], offset: map$$1[map$$1.length - 2] - map$$1[map$$1.length - 3]};
  7993. }
  7994. if (!start || !end) {
  7995. sel.removeAllRanges();
  7996. return
  7997. }
  7998. var old = sel.rangeCount && sel.getRangeAt(0), rng;
  7999. try { rng = range(start.node, start.offset, end.offset, end.node); }
  8000. catch(e) {} // Our model of the DOM might be outdated, in which case the range we try to set can be impossible
  8001. if (rng) {
  8002. if (!gecko && cm.state.focused) {
  8003. sel.collapse(start.node, start.offset);
  8004. if (!rng.collapsed) {
  8005. sel.removeAllRanges();
  8006. sel.addRange(rng);
  8007. }
  8008. } else {
  8009. sel.removeAllRanges();
  8010. sel.addRange(rng);
  8011. }
  8012. if (old && sel.anchorNode == null) { sel.addRange(old); }
  8013. else if (gecko) { this.startGracePeriod(); }
  8014. }
  8015. this.rememberSelection();
  8016. };
  8017. ContentEditableInput.prototype.startGracePeriod = function () {
  8018. var this$1 = this;
  8019. clearTimeout(this.gracePeriod);
  8020. this.gracePeriod = setTimeout(function () {
  8021. this$1.gracePeriod = false;
  8022. if (this$1.selectionChanged())
  8023. { this$1.cm.operation(function () { return this$1.cm.curOp.selectionChanged = true; }); }
  8024. }, 20);
  8025. };
  8026. ContentEditableInput.prototype.showMultipleSelections = function (info) {
  8027. removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors);
  8028. removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection);
  8029. };
  8030. ContentEditableInput.prototype.rememberSelection = function () {
  8031. var sel = this.getSelection();
  8032. this.lastAnchorNode = sel.anchorNode; this.lastAnchorOffset = sel.anchorOffset;
  8033. this.lastFocusNode = sel.focusNode; this.lastFocusOffset = sel.focusOffset;
  8034. };
  8035. ContentEditableInput.prototype.selectionInEditor = function () {
  8036. var sel = this.getSelection();
  8037. if (!sel.rangeCount) { return false }
  8038. var node = sel.getRangeAt(0).commonAncestorContainer;
  8039. return contains(this.div, node)
  8040. };
  8041. ContentEditableInput.prototype.focus = function () {
  8042. if (this.cm.options.readOnly != "nocursor") {
  8043. if (!this.selectionInEditor())
  8044. { this.showSelection(this.prepareSelection(), true); }
  8045. this.div.focus();
  8046. }
  8047. };
  8048. ContentEditableInput.prototype.blur = function () { this.div.blur(); };
  8049. ContentEditableInput.prototype.getField = function () { return this.div };
  8050. ContentEditableInput.prototype.supportsTouch = function () { return true };
  8051. ContentEditableInput.prototype.receivedFocus = function () {
  8052. var input = this;
  8053. if (this.selectionInEditor())
  8054. { this.pollSelection(); }
  8055. else
  8056. { runInOp(this.cm, function () { return input.cm.curOp.selectionChanged = true; }); }
  8057. function poll() {
  8058. if (input.cm.state.focused) {
  8059. input.pollSelection();
  8060. input.polling.set(input.cm.options.pollInterval, poll);
  8061. }
  8062. }
  8063. this.polling.set(this.cm.options.pollInterval, poll);
  8064. };
  8065. ContentEditableInput.prototype.selectionChanged = function () {
  8066. var sel = this.getSelection();
  8067. return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset ||
  8068. sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset
  8069. };
  8070. ContentEditableInput.prototype.pollSelection = function () {
  8071. if (this.readDOMTimeout != null || this.gracePeriod || !this.selectionChanged()) { return }
  8072. var sel = this.getSelection(), cm = this.cm;
  8073. // On Android Chrome (version 56, at least), backspacing into an
  8074. // uneditable block element will put the cursor in that element,
  8075. // and then, because it's not editable, hide the virtual keyboard.
  8076. // Because Android doesn't allow us to actually detect backspace
  8077. // presses in a sane way, this code checks for when that happens
  8078. // and simulates a backspace press in this case.
  8079. if (android && chrome && this.cm.display.gutterSpecs.length && isInGutter(sel.anchorNode)) {
  8080. this.cm.triggerOnKeyDown({type: "keydown", keyCode: 8, preventDefault: Math.abs});
  8081. this.blur();
  8082. this.focus();
  8083. return
  8084. }
  8085. if (this.composing) { return }
  8086. this.rememberSelection();
  8087. var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset);
  8088. var head = domToPos(cm, sel.focusNode, sel.focusOffset);
  8089. if (anchor && head) { runInOp(cm, function () {
  8090. setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll);
  8091. if (anchor.bad || head.bad) { cm.curOp.selectionChanged = true; }
  8092. }); }
  8093. };
  8094. ContentEditableInput.prototype.pollContent = function () {
  8095. if (this.readDOMTimeout != null) {
  8096. clearTimeout(this.readDOMTimeout);
  8097. this.readDOMTimeout = null;
  8098. }
  8099. var cm = this.cm, display = cm.display, sel = cm.doc.sel.primary();
  8100. var from = sel.from(), to = sel.to();
  8101. if (from.ch == 0 && from.line > cm.firstLine())
  8102. { from = Pos(from.line - 1, getLine(cm.doc, from.line - 1).length); }
  8103. if (to.ch == getLine(cm.doc, to.line).text.length && to.line < cm.lastLine())
  8104. { to = Pos(to.line + 1, 0); }
  8105. if (from.line < display.viewFrom || to.line > display.viewTo - 1) { return false }
  8106. var fromIndex, fromLine, fromNode;
  8107. if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) {
  8108. fromLine = lineNo(display.view[0].line);
  8109. fromNode = display.view[0].node;
  8110. } else {
  8111. fromLine = lineNo(display.view[fromIndex].line);
  8112. fromNode = display.view[fromIndex - 1].node.nextSibling;
  8113. }
  8114. var toIndex = findViewIndex(cm, to.line);
  8115. var toLine, toNode;
  8116. if (toIndex == display.view.length - 1) {
  8117. toLine = display.viewTo - 1;
  8118. toNode = display.lineDiv.lastChild;
  8119. } else {
  8120. toLine = lineNo(display.view[toIndex + 1].line) - 1;
  8121. toNode = display.view[toIndex + 1].node.previousSibling;
  8122. }
  8123. if (!fromNode) { return false }
  8124. var newText = cm.doc.splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine));
  8125. var oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length));
  8126. while (newText.length > 1 && oldText.length > 1) {
  8127. if (lst(newText) == lst(oldText)) { newText.pop(); oldText.pop(); toLine--; }
  8128. else if (newText[0] == oldText[0]) { newText.shift(); oldText.shift(); fromLine++; }
  8129. else { break }
  8130. }
  8131. var cutFront = 0, cutEnd = 0;
  8132. var newTop = newText[0], oldTop = oldText[0], maxCutFront = Math.min(newTop.length, oldTop.length);
  8133. while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront))
  8134. { ++cutFront; }
  8135. var newBot = lst(newText), oldBot = lst(oldText);
  8136. var maxCutEnd = Math.min(newBot.length - (newText.length == 1 ? cutFront : 0),
  8137. oldBot.length - (oldText.length == 1 ? cutFront : 0));
  8138. while (cutEnd < maxCutEnd &&
  8139. newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1))
  8140. { ++cutEnd; }
  8141. // Try to move start of change to start of selection if ambiguous
  8142. if (newText.length == 1 && oldText.length == 1 && fromLine == from.line) {
  8143. while (cutFront && cutFront > from.ch &&
  8144. newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) {
  8145. cutFront--;
  8146. cutEnd++;
  8147. }
  8148. }
  8149. newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd).replace(/^\u200b+/, "");
  8150. newText[0] = newText[0].slice(cutFront).replace(/\u200b+$/, "");
  8151. var chFrom = Pos(fromLine, cutFront);
  8152. var chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0);
  8153. if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) {
  8154. replaceRange(cm.doc, newText, chFrom, chTo, "+input");
  8155. return true
  8156. }
  8157. };
  8158. ContentEditableInput.prototype.ensurePolled = function () {
  8159. this.forceCompositionEnd();
  8160. };
  8161. ContentEditableInput.prototype.reset = function () {
  8162. this.forceCompositionEnd();
  8163. };
  8164. ContentEditableInput.prototype.forceCompositionEnd = function () {
  8165. if (!this.composing) { return }
  8166. clearTimeout(this.readDOMTimeout);
  8167. this.composing = null;
  8168. this.updateFromDOM();
  8169. this.div.blur();
  8170. this.div.focus();
  8171. };
  8172. ContentEditableInput.prototype.readFromDOMSoon = function () {
  8173. var this$1 = this;
  8174. if (this.readDOMTimeout != null) { return }
  8175. this.readDOMTimeout = setTimeout(function () {
  8176. this$1.readDOMTimeout = null;
  8177. if (this$1.composing) {
  8178. if (this$1.composing.done) { this$1.composing = null; }
  8179. else { return }
  8180. }
  8181. this$1.updateFromDOM();
  8182. }, 80);
  8183. };
  8184. ContentEditableInput.prototype.updateFromDOM = function () {
  8185. var this$1 = this;
  8186. if (this.cm.isReadOnly() || !this.pollContent())
  8187. { runInOp(this.cm, function () { return regChange(this$1.cm); }); }
  8188. };
  8189. ContentEditableInput.prototype.setUneditable = function (node) {
  8190. node.contentEditable = "false";
  8191. };
  8192. ContentEditableInput.prototype.onKeyPress = function (e) {
  8193. if (e.charCode == 0 || this.composing) { return }
  8194. e.preventDefault();
  8195. if (!this.cm.isReadOnly())
  8196. { operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0); }
  8197. };
  8198. ContentEditableInput.prototype.readOnlyChanged = function (val) {
  8199. this.div.contentEditable = String(val != "nocursor");
  8200. };
  8201. ContentEditableInput.prototype.onContextMenu = function () {};
  8202. ContentEditableInput.prototype.resetPosition = function () {};
  8203. ContentEditableInput.prototype.needsContentAttribute = true;
  8204. function posToDOM(cm, pos) {
  8205. var view = findViewForLine(cm, pos.line);
  8206. if (!view || view.hidden) { return null }
  8207. var line = getLine(cm.doc, pos.line);
  8208. var info = mapFromLineView(view, line, pos.line);
  8209. var order = getOrder(line, cm.doc.direction), side = "left";
  8210. if (order) {
  8211. var partPos = getBidiPartAt(order, pos.ch);
  8212. side = partPos % 2 ? "right" : "left";
  8213. }
  8214. var result = nodeAndOffsetInLineMap(info.map, pos.ch, side);
  8215. result.offset = result.collapse == "right" ? result.end : result.start;
  8216. return result
  8217. }
  8218. function isInGutter(node) {
  8219. for (var scan = node; scan; scan = scan.parentNode)
  8220. { if (/CodeMirror-gutter-wrapper/.test(scan.className)) { return true } }
  8221. return false
  8222. }
  8223. function badPos(pos, bad) { if (bad) { pos.bad = true; } return pos }
  8224. function domTextBetween(cm, from, to, fromLine, toLine) {
  8225. var text = "", closing = false, lineSep = cm.doc.lineSeparator(), extraLinebreak = false;
  8226. function recognizeMarker(id) { return function (marker) { return marker.id == id; } }
  8227. function close() {
  8228. if (closing) {
  8229. text += lineSep;
  8230. if (extraLinebreak) { text += lineSep; }
  8231. closing = extraLinebreak = false;
  8232. }
  8233. }
  8234. function addText(str) {
  8235. if (str) {
  8236. close();
  8237. text += str;
  8238. }
  8239. }
  8240. function walk(node) {
  8241. if (node.nodeType == 1) {
  8242. var cmText = node.getAttribute("cm-text");
  8243. if (cmText) {
  8244. addText(cmText);
  8245. return
  8246. }
  8247. var markerID = node.getAttribute("cm-marker"), range$$1;
  8248. if (markerID) {
  8249. var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID));
  8250. if (found.length && (range$$1 = found[0].find(0)))
  8251. { addText(getBetween(cm.doc, range$$1.from, range$$1.to).join(lineSep)); }
  8252. return
  8253. }
  8254. if (node.getAttribute("contenteditable") == "false") { return }
  8255. var isBlock = /^(pre|div|p|li|table|br)$/i.test(node.nodeName);
  8256. if (!/^br$/i.test(node.nodeName) && node.textContent.length == 0) { return }
  8257. if (isBlock) { close(); }
  8258. for (var i = 0; i < node.childNodes.length; i++)
  8259. { walk(node.childNodes[i]); }
  8260. if (/^(pre|p)$/i.test(node.nodeName)) { extraLinebreak = true; }
  8261. if (isBlock) { closing = true; }
  8262. } else if (node.nodeType == 3) {
  8263. addText(node.nodeValue.replace(/\u200b/g, "").replace(/\u00a0/g, " "));
  8264. }
  8265. }
  8266. for (;;) {
  8267. walk(from);
  8268. if (from == to) { break }
  8269. from = from.nextSibling;
  8270. extraLinebreak = false;
  8271. }
  8272. return text
  8273. }
  8274. function domToPos(cm, node, offset) {
  8275. var lineNode;
  8276. if (node == cm.display.lineDiv) {
  8277. lineNode = cm.display.lineDiv.childNodes[offset];
  8278. if (!lineNode) { return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true) }
  8279. node = null; offset = 0;
  8280. } else {
  8281. for (lineNode = node;; lineNode = lineNode.parentNode) {
  8282. if (!lineNode || lineNode == cm.display.lineDiv) { return null }
  8283. if (lineNode.parentNode && lineNode.parentNode == cm.display.lineDiv) { break }
  8284. }
  8285. }
  8286. for (var i = 0; i < cm.display.view.length; i++) {
  8287. var lineView = cm.display.view[i];
  8288. if (lineView.node == lineNode)
  8289. { return locateNodeInLineView(lineView, node, offset) }
  8290. }
  8291. }
  8292. function locateNodeInLineView(lineView, node, offset) {
  8293. var wrapper = lineView.text.firstChild, bad = false;
  8294. if (!node || !contains(wrapper, node)) { return badPos(Pos(lineNo(lineView.line), 0), true) }
  8295. if (node == wrapper) {
  8296. bad = true;
  8297. node = wrapper.childNodes[offset];
  8298. offset = 0;
  8299. if (!node) {
  8300. var line = lineView.rest ? lst(lineView.rest) : lineView.line;
  8301. return badPos(Pos(lineNo(line), line.text.length), bad)
  8302. }
  8303. }
  8304. var textNode = node.nodeType == 3 ? node : null, topNode = node;
  8305. if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) {
  8306. textNode = node.firstChild;
  8307. if (offset) { offset = textNode.nodeValue.length; }
  8308. }
  8309. while (topNode.parentNode != wrapper) { topNode = topNode.parentNode; }
  8310. var measure = lineView.measure, maps = measure.maps;
  8311. function find(textNode, topNode, offset) {
  8312. for (var i = -1; i < (maps ? maps.length : 0); i++) {
  8313. var map$$1 = i < 0 ? measure.map : maps[i];
  8314. for (var j = 0; j < map$$1.length; j += 3) {
  8315. var curNode = map$$1[j + 2];
  8316. if (curNode == textNode || curNode == topNode) {
  8317. var line = lineNo(i < 0 ? lineView.line : lineView.rest[i]);
  8318. var ch = map$$1[j] + offset;
  8319. if (offset < 0 || curNode != textNode) { ch = map$$1[j + (offset ? 1 : 0)]; }
  8320. return Pos(line, ch)
  8321. }
  8322. }
  8323. }
  8324. }
  8325. var found = find(textNode, topNode, offset);
  8326. if (found) { return badPos(found, bad) }
  8327. // FIXME this is all really shaky. might handle the few cases it needs to handle, but likely to cause problems
  8328. for (var after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) {
  8329. found = find(after, after.firstChild, 0);
  8330. if (found)
  8331. { return badPos(Pos(found.line, found.ch - dist), bad) }
  8332. else
  8333. { dist += after.textContent.length; }
  8334. }
  8335. for (var before = topNode.previousSibling, dist$1 = offset; before; before = before.previousSibling) {
  8336. found = find(before, before.firstChild, -1);
  8337. if (found)
  8338. { return badPos(Pos(found.line, found.ch + dist$1), bad) }
  8339. else
  8340. { dist$1 += before.textContent.length; }
  8341. }
  8342. }
  8343. // TEXTAREA INPUT STYLE
  8344. var TextareaInput = function(cm) {
  8345. this.cm = cm;
  8346. // See input.poll and input.reset
  8347. this.prevInput = "";
  8348. // Flag that indicates whether we expect input to appear real soon
  8349. // now (after some event like 'keypress' or 'input') and are
  8350. // polling intensively.
  8351. this.pollingFast = false;
  8352. // Self-resetting timeout for the poller
  8353. this.polling = new Delayed();
  8354. // Used to work around IE issue with selection being forgotten when focus moves away from textarea
  8355. this.hasSelection = false;
  8356. this.composing = null;
  8357. };
  8358. TextareaInput.prototype.init = function (display) {
  8359. var this$1 = this;
  8360. var input = this, cm = this.cm;
  8361. this.createField(display);
  8362. var te = this.textarea;
  8363. display.wrapper.insertBefore(this.wrapper, display.wrapper.firstChild);
  8364. // Needed to hide big blue blinking cursor on Mobile Safari (doesn't seem to work in iOS 8 anymore)
  8365. if (ios) { te.style.width = "0px"; }
  8366. on(te, "input", function () {
  8367. if (ie && ie_version >= 9 && this$1.hasSelection) { this$1.hasSelection = null; }
  8368. input.poll();
  8369. });
  8370. on(te, "paste", function (e) {
  8371. if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { return }
  8372. cm.state.pasteIncoming = +new Date;
  8373. input.fastPoll();
  8374. });
  8375. function prepareCopyCut(e) {
  8376. if (signalDOMEvent(cm, e)) { return }
  8377. if (cm.somethingSelected()) {
  8378. setLastCopied({lineWise: false, text: cm.getSelections()});
  8379. } else if (!cm.options.lineWiseCopyCut) {
  8380. return
  8381. } else {
  8382. var ranges = copyableRanges(cm);
  8383. setLastCopied({lineWise: true, text: ranges.text});
  8384. if (e.type == "cut") {
  8385. cm.setSelections(ranges.ranges, null, sel_dontScroll);
  8386. } else {
  8387. input.prevInput = "";
  8388. te.value = ranges.text.join("\n");
  8389. selectInput(te);
  8390. }
  8391. }
  8392. if (e.type == "cut") { cm.state.cutIncoming = +new Date; }
  8393. }
  8394. on(te, "cut", prepareCopyCut);
  8395. on(te, "copy", prepareCopyCut);
  8396. on(display.scroller, "paste", function (e) {
  8397. if (eventInWidget(display, e) || signalDOMEvent(cm, e)) { return }
  8398. if (!te.dispatchEvent) {
  8399. cm.state.pasteIncoming = +new Date;
  8400. input.focus();
  8401. return
  8402. }
  8403. // Pass the `paste` event to the textarea so it's handled by its event listener.
  8404. var event = new Event("paste");
  8405. event.clipboardData = e.clipboardData;
  8406. te.dispatchEvent(event);
  8407. });
  8408. // Prevent normal selection in the editor (we handle our own)
  8409. on(display.lineSpace, "selectstart", function (e) {
  8410. if (!eventInWidget(display, e)) { e_preventDefault(e); }
  8411. });
  8412. on(te, "compositionstart", function () {
  8413. var start = cm.getCursor("from");
  8414. if (input.composing) { input.composing.range.clear(); }
  8415. input.composing = {
  8416. start: start,
  8417. range: cm.markText(start, cm.getCursor("to"), {className: "CodeMirror-composing"})
  8418. };
  8419. });
  8420. on(te, "compositionend", function () {
  8421. if (input.composing) {
  8422. input.poll();
  8423. input.composing.range.clear();
  8424. input.composing = null;
  8425. }
  8426. });
  8427. };
  8428. TextareaInput.prototype.createField = function (_display) {
  8429. // Wraps and hides input textarea
  8430. this.wrapper = hiddenTextarea();
  8431. // The semihidden textarea that is focused when the editor is
  8432. // focused, and receives input.
  8433. this.textarea = this.wrapper.firstChild;
  8434. };
  8435. TextareaInput.prototype.prepareSelection = function () {
  8436. // Redraw the selection and/or cursor
  8437. var cm = this.cm, display = cm.display, doc = cm.doc;
  8438. var result = prepareSelection(cm);
  8439. // Move the hidden textarea near the cursor to prevent scrolling artifacts
  8440. if (cm.options.moveInputWithCursor) {
  8441. var headPos = cursorCoords(cm, doc.sel.primary().head, "div");
  8442. var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect();
  8443. result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10,
  8444. headPos.top + lineOff.top - wrapOff.top));
  8445. result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10,
  8446. headPos.left + lineOff.left - wrapOff.left));
  8447. }
  8448. return result
  8449. };
  8450. TextareaInput.prototype.showSelection = function (drawn) {
  8451. var cm = this.cm, display = cm.display;
  8452. removeChildrenAndAdd(display.cursorDiv, drawn.cursors);
  8453. removeChildrenAndAdd(display.selectionDiv, drawn.selection);
  8454. if (drawn.teTop != null) {
  8455. this.wrapper.style.top = drawn.teTop + "px";
  8456. this.wrapper.style.left = drawn.teLeft + "px";
  8457. }
  8458. };
  8459. // Reset the input to correspond to the selection (or to be empty,
  8460. // when not typing and nothing is selected)
  8461. TextareaInput.prototype.reset = function (typing) {
  8462. if (this.contextMenuPending || this.composing) { return }
  8463. var cm = this.cm;
  8464. if (cm.somethingSelected()) {
  8465. this.prevInput = "";
  8466. var content = cm.getSelection();
  8467. this.textarea.value = content;
  8468. if (cm.state.focused) { selectInput(this.textarea); }
  8469. if (ie && ie_version >= 9) { this.hasSelection = content; }
  8470. } else if (!typing) {
  8471. this.prevInput = this.textarea.value = "";
  8472. if (ie && ie_version >= 9) { this.hasSelection = null; }
  8473. }
  8474. };
  8475. TextareaInput.prototype.getField = function () { return this.textarea };
  8476. TextareaInput.prototype.supportsTouch = function () { return false };
  8477. TextareaInput.prototype.focus = function () {
  8478. if (this.cm.options.readOnly != "nocursor" && (!mobile || activeElt() != this.textarea)) {
  8479. try { this.textarea.focus(); }
  8480. catch (e) {} // IE8 will throw if the textarea is display: none or not in DOM
  8481. }
  8482. };
  8483. TextareaInput.prototype.blur = function () { this.textarea.blur(); };
  8484. TextareaInput.prototype.resetPosition = function () {
  8485. this.wrapper.style.top = this.wrapper.style.left = 0;
  8486. };
  8487. TextareaInput.prototype.receivedFocus = function () { this.slowPoll(); };
  8488. // Poll for input changes, using the normal rate of polling. This
  8489. // runs as long as the editor is focused.
  8490. TextareaInput.prototype.slowPoll = function () {
  8491. var this$1 = this;
  8492. if (this.pollingFast) { return }
  8493. this.polling.set(this.cm.options.pollInterval, function () {
  8494. this$1.poll();
  8495. if (this$1.cm.state.focused) { this$1.slowPoll(); }
  8496. });
  8497. };
  8498. // When an event has just come in that is likely to add or change
  8499. // something in the input textarea, we poll faster, to ensure that
  8500. // the change appears on the screen quickly.
  8501. TextareaInput.prototype.fastPoll = function () {
  8502. var missed = false, input = this;
  8503. input.pollingFast = true;
  8504. function p() {
  8505. var changed = input.poll();
  8506. if (!changed && !missed) {missed = true; input.polling.set(60, p);}
  8507. else {input.pollingFast = false; input.slowPoll();}
  8508. }
  8509. input.polling.set(20, p);
  8510. };
  8511. // Read input from the textarea, and update the document to match.
  8512. // When something is selected, it is present in the textarea, and
  8513. // selected (unless it is huge, in which case a placeholder is
  8514. // used). When nothing is selected, the cursor sits after previously
  8515. // seen text (can be empty), which is stored in prevInput (we must
  8516. // not reset the textarea when typing, because that breaks IME).
  8517. TextareaInput.prototype.poll = function () {
  8518. var this$1 = this;
  8519. var cm = this.cm, input = this.textarea, prevInput = this.prevInput;
  8520. // Since this is called a *lot*, try to bail out as cheaply as
  8521. // possible when it is clear that nothing happened. hasSelection
  8522. // will be the case when there is a lot of text in the textarea,
  8523. // in which case reading its value would be expensive.
  8524. if (this.contextMenuPending || !cm.state.focused ||
  8525. (hasSelection(input) && !prevInput && !this.composing) ||
  8526. cm.isReadOnly() || cm.options.disableInput || cm.state.keySeq)
  8527. { return false }
  8528. var text = input.value;
  8529. // If nothing changed, bail.
  8530. if (text == prevInput && !cm.somethingSelected()) { return false }
  8531. // Work around nonsensical selection resetting in IE9/10, and
  8532. // inexplicable appearance of private area unicode characters on
  8533. // some key combos in Mac (#2689).
  8534. if (ie && ie_version >= 9 && this.hasSelection === text ||
  8535. mac && /[\uf700-\uf7ff]/.test(text)) {
  8536. cm.display.input.reset();
  8537. return false
  8538. }
  8539. if (cm.doc.sel == cm.display.selForContextMenu) {
  8540. var first = text.charCodeAt(0);
  8541. if (first == 0x200b && !prevInput) { prevInput = "\u200b"; }
  8542. if (first == 0x21da) { this.reset(); return this.cm.execCommand("undo") }
  8543. }
  8544. // Find the part of the input that is actually new
  8545. var same = 0, l = Math.min(prevInput.length, text.length);
  8546. while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) { ++same; }
  8547. runInOp(cm, function () {
  8548. applyTextInput(cm, text.slice(same), prevInput.length - same,
  8549. null, this$1.composing ? "*compose" : null);
  8550. // Don't leave long text in the textarea, since it makes further polling slow
  8551. if (text.length > 1000 || text.indexOf("\n") > -1) { input.value = this$1.prevInput = ""; }
  8552. else { this$1.prevInput = text; }
  8553. if (this$1.composing) {
  8554. this$1.composing.range.clear();
  8555. this$1.composing.range = cm.markText(this$1.composing.start, cm.getCursor("to"),
  8556. {className: "CodeMirror-composing"});
  8557. }
  8558. });
  8559. return true
  8560. };
  8561. TextareaInput.prototype.ensurePolled = function () {
  8562. if (this.pollingFast && this.poll()) { this.pollingFast = false; }
  8563. };
  8564. TextareaInput.prototype.onKeyPress = function () {
  8565. if (ie && ie_version >= 9) { this.hasSelection = null; }
  8566. this.fastPoll();
  8567. };
  8568. TextareaInput.prototype.onContextMenu = function (e) {
  8569. var input = this, cm = input.cm, display = cm.display, te = input.textarea;
  8570. if (input.contextMenuPending) { input.contextMenuPending(); }
  8571. var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop;
  8572. if (!pos || presto) { return } // Opera is difficult.
  8573. // Reset the current text selection only if the click is done outside of the selection
  8574. // and 'resetSelectionOnContextMenu' option is true.
  8575. var reset = cm.options.resetSelectionOnContextMenu;
  8576. if (reset && cm.doc.sel.contains(pos) == -1)
  8577. { operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll); }
  8578. var oldCSS = te.style.cssText, oldWrapperCSS = input.wrapper.style.cssText;
  8579. var wrapperBox = input.wrapper.offsetParent.getBoundingClientRect();
  8580. input.wrapper.style.cssText = "position: static";
  8581. te.style.cssText = "position: absolute; width: 30px; height: 30px;\n top: " + (e.clientY - wrapperBox.top - 5) + "px; left: " + (e.clientX - wrapperBox.left - 5) + "px;\n z-index: 1000; background: " + (ie ? "rgba(255, 255, 255, .05)" : "transparent") + ";\n outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);";
  8582. var oldScrollY;
  8583. if (webkit) { oldScrollY = window.scrollY; } // Work around Chrome issue (#2712)
  8584. display.input.focus();
  8585. if (webkit) { window.scrollTo(null, oldScrollY); }
  8586. display.input.reset();
  8587. // Adds "Select all" to context menu in FF
  8588. if (!cm.somethingSelected()) { te.value = input.prevInput = " "; }
  8589. input.contextMenuPending = rehide;
  8590. display.selForContextMenu = cm.doc.sel;
  8591. clearTimeout(display.detectingSelectAll);
  8592. // Select-all will be greyed out if there's nothing to select, so
  8593. // this adds a zero-width space so that we can later check whether
  8594. // it got selected.
  8595. function prepareSelectAllHack() {
  8596. if (te.selectionStart != null) {
  8597. var selected = cm.somethingSelected();
  8598. var extval = "\u200b" + (selected ? te.value : "");
  8599. te.value = "\u21da"; // Used to catch context-menu undo
  8600. te.value = extval;
  8601. input.prevInput = selected ? "" : "\u200b";
  8602. te.selectionStart = 1; te.selectionEnd = extval.length;
  8603. // Re-set this, in case some other handler touched the
  8604. // selection in the meantime.
  8605. display.selForContextMenu = cm.doc.sel;
  8606. }
  8607. }
  8608. function rehide() {
  8609. if (input.contextMenuPending != rehide) { return }
  8610. input.contextMenuPending = false;
  8611. input.wrapper.style.cssText = oldWrapperCSS;
  8612. te.style.cssText = oldCSS;
  8613. if (ie && ie_version < 9) { display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos); }
  8614. // Try to detect the user choosing select-all
  8615. if (te.selectionStart != null) {
  8616. if (!ie || (ie && ie_version < 9)) { prepareSelectAllHack(); }
  8617. var i = 0, poll = function () {
  8618. if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0 &&
  8619. te.selectionEnd > 0 && input.prevInput == "\u200b") {
  8620. operation(cm, selectAll)(cm);
  8621. } else if (i++ < 10) {
  8622. display.detectingSelectAll = setTimeout(poll, 500);
  8623. } else {
  8624. display.selForContextMenu = null;
  8625. display.input.reset();
  8626. }
  8627. };
  8628. display.detectingSelectAll = setTimeout(poll, 200);
  8629. }
  8630. }
  8631. if (ie && ie_version >= 9) { prepareSelectAllHack(); }
  8632. if (captureRightClick) {
  8633. e_stop(e);
  8634. var mouseup = function () {
  8635. off(window, "mouseup", mouseup);
  8636. setTimeout(rehide, 20);
  8637. };
  8638. on(window, "mouseup", mouseup);
  8639. } else {
  8640. setTimeout(rehide, 50);
  8641. }
  8642. };
  8643. TextareaInput.prototype.readOnlyChanged = function (val) {
  8644. if (!val) { this.reset(); }
  8645. this.textarea.disabled = val == "nocursor";
  8646. };
  8647. TextareaInput.prototype.setUneditable = function () {};
  8648. TextareaInput.prototype.needsContentAttribute = false;
  8649. function fromTextArea(textarea, options) {
  8650. options = options ? copyObj(options) : {};
  8651. options.value = textarea.value;
  8652. if (!options.tabindex && textarea.tabIndex)
  8653. { options.tabindex = textarea.tabIndex; }
  8654. if (!options.placeholder && textarea.placeholder)
  8655. { options.placeholder = textarea.placeholder; }
  8656. // Set autofocus to true if this textarea is focused, or if it has
  8657. // autofocus and no other element is focused.
  8658. if (options.autofocus == null) {
  8659. var hasFocus = activeElt();
  8660. options.autofocus = hasFocus == textarea ||
  8661. textarea.getAttribute("autofocus") != null && hasFocus == document.body;
  8662. }
  8663. function save() {textarea.value = cm.getValue();}
  8664. var realSubmit;
  8665. if (textarea.form) {
  8666. on(textarea.form, "submit", save);
  8667. // Deplorable hack to make the submit method do the right thing.
  8668. if (!options.leaveSubmitMethodAlone) {
  8669. var form = textarea.form;
  8670. realSubmit = form.submit;
  8671. try {
  8672. var wrappedSubmit = form.submit = function () {
  8673. save();
  8674. form.submit = realSubmit;
  8675. form.submit();
  8676. form.submit = wrappedSubmit;
  8677. };
  8678. } catch(e) {}
  8679. }
  8680. }
  8681. options.finishInit = function (cm) {
  8682. cm.save = save;
  8683. cm.getTextArea = function () { return textarea; };
  8684. cm.toTextArea = function () {
  8685. cm.toTextArea = isNaN; // Prevent this from being ran twice
  8686. save();
  8687. textarea.parentNode.removeChild(cm.getWrapperElement());
  8688. textarea.style.display = "";
  8689. if (textarea.form) {
  8690. off(textarea.form, "submit", save);
  8691. if (typeof textarea.form.submit == "function")
  8692. { textarea.form.submit = realSubmit; }
  8693. }
  8694. };
  8695. };
  8696. textarea.style.display = "none";
  8697. var cm = CodeMirror(function (node) { return textarea.parentNode.insertBefore(node, textarea.nextSibling); },
  8698. options);
  8699. return cm
  8700. }
  8701. function addLegacyProps(CodeMirror) {
  8702. CodeMirror.off = off;
  8703. CodeMirror.on = on;
  8704. CodeMirror.wheelEventPixels = wheelEventPixels;
  8705. CodeMirror.Doc = Doc;
  8706. CodeMirror.splitLines = splitLinesAuto;
  8707. CodeMirror.countColumn = countColumn;
  8708. CodeMirror.findColumn = findColumn;
  8709. CodeMirror.isWordChar = isWordCharBasic;
  8710. CodeMirror.Pass = Pass;
  8711. CodeMirror.signal = signal;
  8712. CodeMirror.Line = Line;
  8713. CodeMirror.changeEnd = changeEnd;
  8714. CodeMirror.scrollbarModel = scrollbarModel;
  8715. CodeMirror.Pos = Pos;
  8716. CodeMirror.cmpPos = cmp;
  8717. CodeMirror.modes = modes;
  8718. CodeMirror.mimeModes = mimeModes;
  8719. CodeMirror.resolveMode = resolveMode;
  8720. CodeMirror.getMode = getMode;
  8721. CodeMirror.modeExtensions = modeExtensions;
  8722. CodeMirror.extendMode = extendMode;
  8723. CodeMirror.copyState = copyState;
  8724. CodeMirror.startState = startState;
  8725. CodeMirror.innerMode = innerMode;
  8726. CodeMirror.commands = commands;
  8727. CodeMirror.keyMap = keyMap;
  8728. CodeMirror.keyName = keyName;
  8729. CodeMirror.isModifierKey = isModifierKey;
  8730. CodeMirror.lookupKey = lookupKey;
  8731. CodeMirror.normalizeKeyMap = normalizeKeyMap;
  8732. CodeMirror.StringStream = StringStream;
  8733. CodeMirror.SharedTextMarker = SharedTextMarker;
  8734. CodeMirror.TextMarker = TextMarker;
  8735. CodeMirror.LineWidget = LineWidget;
  8736. CodeMirror.e_preventDefault = e_preventDefault;
  8737. CodeMirror.e_stopPropagation = e_stopPropagation;
  8738. CodeMirror.e_stop = e_stop;
  8739. CodeMirror.addClass = addClass;
  8740. CodeMirror.contains = contains;
  8741. CodeMirror.rmClass = rmClass;
  8742. CodeMirror.keyNames = keyNames;
  8743. }
  8744. // EDITOR CONSTRUCTOR
  8745. defineOptions(CodeMirror);
  8746. addEditorMethods(CodeMirror);
  8747. // Set up methods on CodeMirror's prototype to redirect to the editor's document.
  8748. var dontDelegate = "iter insert remove copy getEditor constructor".split(" ");
  8749. for (var prop in Doc.prototype) { if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0)
  8750. { CodeMirror.prototype[prop] = (function(method) {
  8751. return function() {return method.apply(this.doc, arguments)}
  8752. })(Doc.prototype[prop]); } }
  8753. eventMixin(Doc);
  8754. CodeMirror.inputStyles = {"textarea": TextareaInput, "contenteditable": ContentEditableInput};
  8755. // Extra arguments are stored as the mode's dependencies, which is
  8756. // used by (legacy) mechanisms like loadmode.js to automatically
  8757. // load a mode. (Preferred mechanism is the require/define calls.)
  8758. CodeMirror.defineMode = function(name/*, mode, …*/) {
  8759. if (!CodeMirror.defaults.mode && name != "null") { CodeMirror.defaults.mode = name; }
  8760. defineMode.apply(this, arguments);
  8761. };
  8762. CodeMirror.defineMIME = defineMIME;
  8763. // Minimal default mode.
  8764. CodeMirror.defineMode("null", function () { return ({token: function (stream) { return stream.skipToEnd(); }}); });
  8765. CodeMirror.defineMIME("text/plain", "null");
  8766. // EXTENSIONS
  8767. CodeMirror.defineExtension = function (name, func) {
  8768. CodeMirror.prototype[name] = func;
  8769. };
  8770. CodeMirror.defineDocExtension = function (name, func) {
  8771. Doc.prototype[name] = func;
  8772. };
  8773. CodeMirror.fromTextArea = fromTextArea;
  8774. addLegacyProps(CodeMirror);
  8775. CodeMirror.version = "5.48.4";
  8776. return CodeMirror;
  8777. })));