codemirror.js 364 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672
  1. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  2. // Distributed under an MIT license: http://codemirror.net/LICENSE
  3. // This is CodeMirror (http://codemirror.net), a code editor
  4. // implemented in JavaScript on top of the browser's DOM.
  5. //
  6. // You can find some technical background for some of the code below
  7. // at http://marijnhaverbeke.nl/blog/#cm-internals .
  8. (function (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};
  173. var sel_mouse = {origin: "*mouse"};
  174. var sel_move = {origin: "+move"};
  175. // The inverse of countColumn -- find the offset that corresponds to
  176. // a particular column.
  177. function findColumn(string, goal, tabSize) {
  178. for (var pos = 0, col = 0;;) {
  179. var nextTab = string.indexOf("\t", pos);
  180. if (nextTab == -1) { nextTab = string.length; }
  181. var skipped = nextTab - pos;
  182. if (nextTab == string.length || col + skipped >= goal)
  183. { return pos + Math.min(skipped, goal - col) }
  184. col += nextTab - pos;
  185. col += tabSize - (col % tabSize);
  186. pos = nextTab + 1;
  187. if (col >= goal) { return pos }
  188. }
  189. }
  190. var spaceStrs = [""];
  191. function spaceStr(n) {
  192. while (spaceStrs.length <= n)
  193. { spaceStrs.push(lst(spaceStrs) + " "); }
  194. return spaceStrs[n]
  195. }
  196. function lst(arr) { return arr[arr.length-1] }
  197. function map(array, f) {
  198. var out = [];
  199. for (var i = 0; i < array.length; i++) { out[i] = f(array[i], i); }
  200. return out
  201. }
  202. function insertSorted(array, value, score) {
  203. var pos = 0, priority = score(value);
  204. while (pos < array.length && score(array[pos]) <= priority) { pos++; }
  205. array.splice(pos, 0, value);
  206. }
  207. function nothing() {}
  208. function createObj(base, props) {
  209. var inst;
  210. if (Object.create) {
  211. inst = Object.create(base);
  212. } else {
  213. nothing.prototype = base;
  214. inst = new nothing();
  215. }
  216. if (props) { copyObj(props, inst); }
  217. return inst
  218. }
  219. var nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;
  220. function isWordCharBasic(ch) {
  221. return /\w/.test(ch) || ch > "\x80" &&
  222. (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch))
  223. }
  224. function isWordChar(ch, helper) {
  225. if (!helper) { return isWordCharBasic(ch) }
  226. if (helper.source.indexOf("\\w") > -1 && isWordCharBasic(ch)) { return true }
  227. return helper.test(ch)
  228. }
  229. function isEmpty(obj) {
  230. for (var n in obj) { if (obj.hasOwnProperty(n) && obj[n]) { return false } }
  231. return true
  232. }
  233. // Extending unicode characters. A series of a non-extending char +
  234. // any number of extending chars is treated as a single unit as far
  235. // as editing and measuring is concerned. This is not fully correct,
  236. // since some scripts/fonts/browsers also treat other configurations
  237. // of code points as a group.
  238. 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]/;
  239. function isExtendingChar(ch) { return ch.charCodeAt(0) >= 768 && extendingChars.test(ch) }
  240. // Returns a number from the range [`0`; `str.length`] unless `pos` is outside that range.
  241. function skipExtendingChars(str, pos, dir) {
  242. while ((dir < 0 ? pos > 0 : pos < str.length) && isExtendingChar(str.charAt(pos))) { pos += dir; }
  243. return pos
  244. }
  245. // Returns the value from the range [`from`; `to`] that satisfies
  246. // `pred` and is closest to `from`. Assumes that at least `to`
  247. // satisfies `pred`. Supports `from` being greater than `to`.
  248. function findFirst(pred, from, to) {
  249. // At any point we are certain `to` satisfies `pred`, don't know
  250. // whether `from` does.
  251. var dir = from > to ? -1 : 1;
  252. for (;;) {
  253. if (from == to) { return from }
  254. var midF = (from + to) / 2, mid = dir < 0 ? Math.ceil(midF) : Math.floor(midF);
  255. if (mid == from) { return pred(mid) ? from : to }
  256. if (pred(mid)) { to = mid; }
  257. else { from = mid + dir; }
  258. }
  259. }
  260. // The display handles the DOM integration, both for input reading
  261. // and content drawing. It holds references to DOM nodes and
  262. // display-related state.
  263. function Display(place, doc, input) {
  264. var d = this;
  265. this.input = input;
  266. // Covers bottom-right square when both scrollbars are present.
  267. d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler");
  268. d.scrollbarFiller.setAttribute("cm-not-content", "true");
  269. // Covers bottom of gutter when coverGutterNextToScrollbar is on
  270. // and h scrollbar is present.
  271. d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler");
  272. d.gutterFiller.setAttribute("cm-not-content", "true");
  273. // Will contain the actual code, positioned to cover the viewport.
  274. d.lineDiv = eltP("div", null, "CodeMirror-code");
  275. // Elements are added to these to represent selection and cursors.
  276. d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1");
  277. d.cursorDiv = elt("div", null, "CodeMirror-cursors");
  278. // A visibility: hidden element used to find the size of things.
  279. d.measure = elt("div", null, "CodeMirror-measure");
  280. // When lines outside of the viewport are measured, they are drawn in this.
  281. d.lineMeasure = elt("div", null, "CodeMirror-measure");
  282. // Wraps everything that needs to exist inside the vertically-padded coordinate system
  283. d.lineSpace = eltP("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv],
  284. null, "position: relative; outline: none");
  285. var lines = eltP("div", [d.lineSpace], "CodeMirror-lines");
  286. // Moved around its parent to cover visible view.
  287. d.mover = elt("div", [lines], null, "position: relative");
  288. // Set to the height of the document, allowing scrolling.
  289. d.sizer = elt("div", [d.mover], "CodeMirror-sizer");
  290. d.sizerWidth = null;
  291. // Behavior of elts with overflow: auto and padding is
  292. // inconsistent across browsers. This is used to ensure the
  293. // scrollable area is big enough.
  294. d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerGap + "px; width: 1px;");
  295. // Will contain the gutters, if any.
  296. d.gutters = elt("div", null, "CodeMirror-gutters");
  297. d.lineGutter = null;
  298. // Actual scrollable element.
  299. d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll");
  300. d.scroller.setAttribute("tabIndex", "-1");
  301. // The element in which the editor lives.
  302. d.wrapper = elt("div", [d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror");
  303. // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported)
  304. if (ie && ie_version < 8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; }
  305. if (!webkit && !(gecko && mobile)) { d.scroller.draggable = true; }
  306. if (place) {
  307. if (place.appendChild) { place.appendChild(d.wrapper); }
  308. else { place(d.wrapper); }
  309. }
  310. // Current rendered range (may be bigger than the view window).
  311. d.viewFrom = d.viewTo = doc.first;
  312. d.reportedViewFrom = d.reportedViewTo = doc.first;
  313. // Information about the rendered lines.
  314. d.view = [];
  315. d.renderedView = null;
  316. // Holds info about a single rendered line when it was rendered
  317. // for measurement, while not in view.
  318. d.externalMeasured = null;
  319. // Empty space (in pixels) above the view
  320. d.viewOffset = 0;
  321. d.lastWrapHeight = d.lastWrapWidth = 0;
  322. d.updateLineNumbers = null;
  323. d.nativeBarWidth = d.barHeight = d.barWidth = 0;
  324. d.scrollbarsClipped = false;
  325. // Used to only resize the line number gutter when necessary (when
  326. // the amount of lines crosses a boundary that makes its width change)
  327. d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null;
  328. // Set to true when a non-horizontal-scrolling line widget is
  329. // added. As an optimization, line widget aligning is skipped when
  330. // this is false.
  331. d.alignWidgets = false;
  332. d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
  333. // Tracks the maximum line length so that the horizontal scrollbar
  334. // can be kept static when scrolling.
  335. d.maxLine = null;
  336. d.maxLineLength = 0;
  337. d.maxLineChanged = false;
  338. // Used for measuring wheel scrolling granularity
  339. d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null;
  340. // True when shift is held down.
  341. d.shift = false;
  342. // Used to track whether anything happened since the context menu
  343. // was opened.
  344. d.selForContextMenu = null;
  345. d.activeTouch = null;
  346. input.init(d);
  347. }
  348. // Find the line object corresponding to the given line number.
  349. function getLine(doc, n) {
  350. n -= doc.first;
  351. if (n < 0 || n >= doc.size) { throw new Error("There is no line " + (n + doc.first) + " in the document.") }
  352. var chunk = doc;
  353. while (!chunk.lines) {
  354. for (var i = 0;; ++i) {
  355. var child = chunk.children[i], sz = child.chunkSize();
  356. if (n < sz) { chunk = child; break }
  357. n -= sz;
  358. }
  359. }
  360. return chunk.lines[n]
  361. }
  362. // Get the part of a document between two positions, as an array of
  363. // strings.
  364. function getBetween(doc, start, end) {
  365. var out = [], n = start.line;
  366. doc.iter(start.line, end.line + 1, function (line) {
  367. var text = line.text;
  368. if (n == end.line) { text = text.slice(0, end.ch); }
  369. if (n == start.line) { text = text.slice(start.ch); }
  370. out.push(text);
  371. ++n;
  372. });
  373. return out
  374. }
  375. // Get the lines between from and to, as array of strings.
  376. function getLines(doc, from, to) {
  377. var out = [];
  378. doc.iter(from, to, function (line) { out.push(line.text); }); // iter aborts when callback returns truthy value
  379. return out
  380. }
  381. // Update the height of a line, propagating the height change
  382. // upwards to parent nodes.
  383. function updateLineHeight(line, height) {
  384. var diff = height - line.height;
  385. if (diff) { for (var n = line; n; n = n.parent) { n.height += diff; } }
  386. }
  387. // Given a line object, find its line number by walking up through
  388. // its parent links.
  389. function lineNo(line) {
  390. if (line.parent == null) { return null }
  391. var cur = line.parent, no = indexOf(cur.lines, line);
  392. for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) {
  393. for (var i = 0;; ++i) {
  394. if (chunk.children[i] == cur) { break }
  395. no += chunk.children[i].chunkSize();
  396. }
  397. }
  398. return no + cur.first
  399. }
  400. // Find the line at the given vertical position, using the height
  401. // information in the document tree.
  402. function lineAtHeight(chunk, h) {
  403. var n = chunk.first;
  404. outer: do {
  405. for (var i$1 = 0; i$1 < chunk.children.length; ++i$1) {
  406. var child = chunk.children[i$1], ch = child.height;
  407. if (h < ch) { chunk = child; continue outer }
  408. h -= ch;
  409. n += child.chunkSize();
  410. }
  411. return n
  412. } while (!chunk.lines)
  413. var i = 0;
  414. for (; i < chunk.lines.length; ++i) {
  415. var line = chunk.lines[i], lh = line.height;
  416. if (h < lh) { break }
  417. h -= lh;
  418. }
  419. return n + i
  420. }
  421. function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size}
  422. function lineNumberFor(options, i) {
  423. return String(options.lineNumberFormatter(i + options.firstLineNumber))
  424. }
  425. // A Pos instance represents a position within the text.
  426. function Pos(line, ch, sticky) {
  427. if ( sticky === void 0 ) sticky = null;
  428. if (!(this instanceof Pos)) { return new Pos(line, ch, sticky) }
  429. this.line = line;
  430. this.ch = ch;
  431. this.sticky = sticky;
  432. }
  433. // Compare two positions, return 0 if they are the same, a negative
  434. // number when a is less, and a positive number otherwise.
  435. function cmp(a, b) { return a.line - b.line || a.ch - b.ch }
  436. function equalCursorPos(a, b) { return a.sticky == b.sticky && cmp(a, b) == 0 }
  437. function copyPos(x) {return Pos(x.line, x.ch)}
  438. function maxPos(a, b) { return cmp(a, b) < 0 ? b : a }
  439. function minPos(a, b) { return cmp(a, b) < 0 ? a : b }
  440. // Most of the external API clips given positions to make sure they
  441. // actually exist within the document.
  442. function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1))}
  443. function clipPos(doc, pos) {
  444. if (pos.line < doc.first) { return Pos(doc.first, 0) }
  445. var last = doc.first + doc.size - 1;
  446. if (pos.line > last) { return Pos(last, getLine(doc, last).text.length) }
  447. return clipToLen(pos, getLine(doc, pos.line).text.length)
  448. }
  449. function clipToLen(pos, linelen) {
  450. var ch = pos.ch;
  451. if (ch == null || ch > linelen) { return Pos(pos.line, linelen) }
  452. else if (ch < 0) { return Pos(pos.line, 0) }
  453. else { return pos }
  454. }
  455. function clipPosArray(doc, array) {
  456. var out = [];
  457. for (var i = 0; i < array.length; i++) { out[i] = clipPos(doc, array[i]); }
  458. return out
  459. }
  460. // Optimize some code when these features are not used.
  461. var sawReadOnlySpans = false;
  462. var sawCollapsedSpans = false;
  463. function seeReadOnlySpans() {
  464. sawReadOnlySpans = true;
  465. }
  466. function seeCollapsedSpans() {
  467. sawCollapsedSpans = true;
  468. }
  469. // TEXTMARKER SPANS
  470. function MarkedSpan(marker, from, to) {
  471. this.marker = marker;
  472. this.from = from; this.to = to;
  473. }
  474. // Search an array of spans for a span matching the given marker.
  475. function getMarkedSpanFor(spans, marker) {
  476. if (spans) { for (var i = 0; i < spans.length; ++i) {
  477. var span = spans[i];
  478. if (span.marker == marker) { return span }
  479. } }
  480. }
  481. // Remove a span from an array, returning undefined if no spans are
  482. // left (we don't store arrays for lines without spans).
  483. function removeMarkedSpan(spans, span) {
  484. var r;
  485. for (var i = 0; i < spans.length; ++i)
  486. { if (spans[i] != span) { (r || (r = [])).push(spans[i]); } }
  487. return r
  488. }
  489. // Add a span to a line.
  490. function addMarkedSpan(line, span) {
  491. line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span];
  492. span.marker.attachLine(line);
  493. }
  494. // Used for the algorithm that adjusts markers for a change in the
  495. // document. These functions cut an array of spans at a given
  496. // character position, returning an array of remaining chunks (or
  497. // undefined if nothing remains).
  498. function markedSpansBefore(old, startCh, isInsert) {
  499. var nw;
  500. if (old) { for (var i = 0; i < old.length; ++i) {
  501. var span = old[i], marker = span.marker;
  502. var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh);
  503. if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) {
  504. var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh);(nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to));
  505. }
  506. } }
  507. return nw
  508. }
  509. function markedSpansAfter(old, endCh, isInsert) {
  510. var nw;
  511. if (old) { for (var i = 0; i < old.length; ++i) {
  512. var span = old[i], marker = span.marker;
  513. var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh);
  514. if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) {
  515. var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh);(nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh,
  516. span.to == null ? null : span.to - endCh));
  517. }
  518. } }
  519. return nw
  520. }
  521. // Given a change object, compute the new set of marker spans that
  522. // cover the line in which the change took place. Removes spans
  523. // entirely within the change, reconnects spans belonging to the
  524. // same marker that appear on both sides of the change, and cuts off
  525. // spans partially within the change. Returns an array of span
  526. // arrays with one element for each line in (after) the change.
  527. function stretchSpansOverChange(doc, change) {
  528. if (change.full) { return null }
  529. var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans;
  530. var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans;
  531. if (!oldFirst && !oldLast) { return null }
  532. var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0;
  533. // Get the spans that 'stick out' on both sides
  534. var first = markedSpansBefore(oldFirst, startCh, isInsert);
  535. var last = markedSpansAfter(oldLast, endCh, isInsert);
  536. // Next, merge those two ends
  537. var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0);
  538. if (first) {
  539. // Fix up .to properties of first
  540. for (var i = 0; i < first.length; ++i) {
  541. var span = first[i];
  542. if (span.to == null) {
  543. var found = getMarkedSpanFor(last, span.marker);
  544. if (!found) { span.to = startCh; }
  545. else if (sameLine) { span.to = found.to == null ? null : found.to + offset; }
  546. }
  547. }
  548. }
  549. if (last) {
  550. // Fix up .from in last (or move them into first in case of sameLine)
  551. for (var i$1 = 0; i$1 < last.length; ++i$1) {
  552. var span$1 = last[i$1];
  553. if (span$1.to != null) { span$1.to += offset; }
  554. if (span$1.from == null) {
  555. var found$1 = getMarkedSpanFor(first, span$1.marker);
  556. if (!found$1) {
  557. span$1.from = offset;
  558. if (sameLine) { (first || (first = [])).push(span$1); }
  559. }
  560. } else {
  561. span$1.from += offset;
  562. if (sameLine) { (first || (first = [])).push(span$1); }
  563. }
  564. }
  565. }
  566. // Make sure we didn't create any zero-length spans
  567. if (first) { first = clearEmptySpans(first); }
  568. if (last && last != first) { last = clearEmptySpans(last); }
  569. var newMarkers = [first];
  570. if (!sameLine) {
  571. // Fill gap with whole-line-spans
  572. var gap = change.text.length - 2, gapMarkers;
  573. if (gap > 0 && first)
  574. { for (var i$2 = 0; i$2 < first.length; ++i$2)
  575. { if (first[i$2].to == null)
  576. { (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i$2].marker, null, null)); } } }
  577. for (var i$3 = 0; i$3 < gap; ++i$3)
  578. { newMarkers.push(gapMarkers); }
  579. newMarkers.push(last);
  580. }
  581. return newMarkers
  582. }
  583. // Remove spans that are empty and don't have a clearWhenEmpty
  584. // option of false.
  585. function clearEmptySpans(spans) {
  586. for (var i = 0; i < spans.length; ++i) {
  587. var span = spans[i];
  588. if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false)
  589. { spans.splice(i--, 1); }
  590. }
  591. if (!spans.length) { return null }
  592. return spans
  593. }
  594. // Used to 'clip' out readOnly ranges when making a change.
  595. function removeReadOnlyRanges(doc, from, to) {
  596. var markers = null;
  597. doc.iter(from.line, to.line + 1, function (line) {
  598. if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) {
  599. var mark = line.markedSpans[i].marker;
  600. if (mark.readOnly && (!markers || indexOf(markers, mark) == -1))
  601. { (markers || (markers = [])).push(mark); }
  602. } }
  603. });
  604. if (!markers) { return null }
  605. var parts = [{from: from, to: to}];
  606. for (var i = 0; i < markers.length; ++i) {
  607. var mk = markers[i], m = mk.find(0);
  608. for (var j = 0; j < parts.length; ++j) {
  609. var p = parts[j];
  610. if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) { continue }
  611. var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to);
  612. if (dfrom < 0 || !mk.inclusiveLeft && !dfrom)
  613. { newParts.push({from: p.from, to: m.from}); }
  614. if (dto > 0 || !mk.inclusiveRight && !dto)
  615. { newParts.push({from: m.to, to: p.to}); }
  616. parts.splice.apply(parts, newParts);
  617. j += newParts.length - 3;
  618. }
  619. }
  620. return parts
  621. }
  622. // Connect or disconnect spans from a line.
  623. function detachMarkedSpans(line) {
  624. var spans = line.markedSpans;
  625. if (!spans) { return }
  626. for (var i = 0; i < spans.length; ++i)
  627. { spans[i].marker.detachLine(line); }
  628. line.markedSpans = null;
  629. }
  630. function attachMarkedSpans(line, spans) {
  631. if (!spans) { return }
  632. for (var i = 0; i < spans.length; ++i)
  633. { spans[i].marker.attachLine(line); }
  634. line.markedSpans = spans;
  635. }
  636. // Helpers used when computing which overlapping collapsed span
  637. // counts as the larger one.
  638. function extraLeft(marker) { return marker.inclusiveLeft ? -1 : 0 }
  639. function extraRight(marker) { return marker.inclusiveRight ? 1 : 0 }
  640. // Returns a number indicating which of two overlapping collapsed
  641. // spans is larger (and thus includes the other). Falls back to
  642. // comparing ids when the spans cover exactly the same range.
  643. function compareCollapsedMarkers(a, b) {
  644. var lenDiff = a.lines.length - b.lines.length;
  645. if (lenDiff != 0) { return lenDiff }
  646. var aPos = a.find(), bPos = b.find();
  647. var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b);
  648. if (fromCmp) { return -fromCmp }
  649. var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b);
  650. if (toCmp) { return toCmp }
  651. return b.id - a.id
  652. }
  653. // Find out whether a line ends or starts in a collapsed span. If
  654. // so, return the marker for that span.
  655. function collapsedSpanAtSide(line, start) {
  656. var sps = sawCollapsedSpans && line.markedSpans, found;
  657. if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) {
  658. sp = sps[i];
  659. if (sp.marker.collapsed && (start ? sp.from : sp.to) == null &&
  660. (!found || compareCollapsedMarkers(found, sp.marker) < 0))
  661. { found = sp.marker; }
  662. } }
  663. return found
  664. }
  665. function collapsedSpanAtStart(line) { return collapsedSpanAtSide(line, true) }
  666. function collapsedSpanAtEnd(line) { return collapsedSpanAtSide(line, false) }
  667. // Test whether there exists a collapsed span that partially
  668. // overlaps (covers the start or end, but not both) of a new span.
  669. // Such overlap is not allowed.
  670. function conflictingCollapsedRange(doc, lineNo$$1, from, to, marker) {
  671. var line = getLine(doc, lineNo$$1);
  672. var sps = sawCollapsedSpans && line.markedSpans;
  673. if (sps) { for (var i = 0; i < sps.length; ++i) {
  674. var sp = sps[i];
  675. if (!sp.marker.collapsed) { continue }
  676. var found = sp.marker.find(0);
  677. var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker);
  678. var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker);
  679. if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) { continue }
  680. if (fromCmp <= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.to, from) >= 0 : cmp(found.to, from) > 0) ||
  681. fromCmp >= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.from, to) <= 0 : cmp(found.from, to) < 0))
  682. { return true }
  683. } }
  684. }
  685. // A visual line is a line as drawn on the screen. Folding, for
  686. // example, can cause multiple logical lines to appear on the same
  687. // visual line. This finds the start of the visual line that the
  688. // given line is part of (usually that is the line itself).
  689. function visualLine(line) {
  690. var merged;
  691. while (merged = collapsedSpanAtStart(line))
  692. { line = merged.find(-1, true).line; }
  693. return line
  694. }
  695. function visualLineEnd(line) {
  696. var merged;
  697. while (merged = collapsedSpanAtEnd(line))
  698. { line = merged.find(1, true).line; }
  699. return line
  700. }
  701. // Returns an array of logical lines that continue the visual line
  702. // started by the argument, or undefined if there are no such lines.
  703. function visualLineContinued(line) {
  704. var merged, lines;
  705. while (merged = collapsedSpanAtEnd(line)) {
  706. line = merged.find(1, true).line
  707. ;(lines || (lines = [])).push(line);
  708. }
  709. return lines
  710. }
  711. // Get the line number of the start of the visual line that the
  712. // given line number is part of.
  713. function visualLineNo(doc, lineN) {
  714. var line = getLine(doc, lineN), vis = visualLine(line);
  715. if (line == vis) { return lineN }
  716. return lineNo(vis)
  717. }
  718. // Get the line number of the start of the next visual line after
  719. // the given line.
  720. function visualLineEndNo(doc, lineN) {
  721. if (lineN > doc.lastLine()) { return lineN }
  722. var line = getLine(doc, lineN), merged;
  723. if (!lineIsHidden(doc, line)) { return lineN }
  724. while (merged = collapsedSpanAtEnd(line))
  725. { line = merged.find(1, true).line; }
  726. return lineNo(line) + 1
  727. }
  728. // Compute whether a line is hidden. Lines count as hidden when they
  729. // are part of a visual line that starts with another line, or when
  730. // they are entirely covered by collapsed, non-widget span.
  731. function lineIsHidden(doc, line) {
  732. var sps = sawCollapsedSpans && line.markedSpans;
  733. if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) {
  734. sp = sps[i];
  735. if (!sp.marker.collapsed) { continue }
  736. if (sp.from == null) { return true }
  737. if (sp.marker.widgetNode) { continue }
  738. if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp))
  739. { return true }
  740. } }
  741. }
  742. function lineIsHiddenInner(doc, line, span) {
  743. if (span.to == null) {
  744. var end = span.marker.find(1, true);
  745. return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker))
  746. }
  747. if (span.marker.inclusiveRight && span.to == line.text.length)
  748. { return true }
  749. for (var sp = (void 0), i = 0; i < line.markedSpans.length; ++i) {
  750. sp = line.markedSpans[i];
  751. if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to &&
  752. (sp.to == null || sp.to != span.from) &&
  753. (sp.marker.inclusiveLeft || span.marker.inclusiveRight) &&
  754. lineIsHiddenInner(doc, line, sp)) { return true }
  755. }
  756. }
  757. // Find the height above the given line.
  758. function heightAtLine(lineObj) {
  759. lineObj = visualLine(lineObj);
  760. var h = 0, chunk = lineObj.parent;
  761. for (var i = 0; i < chunk.lines.length; ++i) {
  762. var line = chunk.lines[i];
  763. if (line == lineObj) { break }
  764. else { h += line.height; }
  765. }
  766. for (var p = chunk.parent; p; chunk = p, p = chunk.parent) {
  767. for (var i$1 = 0; i$1 < p.children.length; ++i$1) {
  768. var cur = p.children[i$1];
  769. if (cur == chunk) { break }
  770. else { h += cur.height; }
  771. }
  772. }
  773. return h
  774. }
  775. // Compute the character length of a line, taking into account
  776. // collapsed ranges (see markText) that might hide parts, and join
  777. // other lines onto it.
  778. function lineLength(line) {
  779. if (line.height == 0) { return 0 }
  780. var len = line.text.length, merged, cur = line;
  781. while (merged = collapsedSpanAtStart(cur)) {
  782. var found = merged.find(0, true);
  783. cur = found.from.line;
  784. len += found.from.ch - found.to.ch;
  785. }
  786. cur = line;
  787. while (merged = collapsedSpanAtEnd(cur)) {
  788. var found$1 = merged.find(0, true);
  789. len -= cur.text.length - found$1.from.ch;
  790. cur = found$1.to.line;
  791. len += cur.text.length - found$1.to.ch;
  792. }
  793. return len
  794. }
  795. // Find the longest line in the document.
  796. function findMaxLine(cm) {
  797. var d = cm.display, doc = cm.doc;
  798. d.maxLine = getLine(doc, doc.first);
  799. d.maxLineLength = lineLength(d.maxLine);
  800. d.maxLineChanged = true;
  801. doc.iter(function (line) {
  802. var len = lineLength(line);
  803. if (len > d.maxLineLength) {
  804. d.maxLineLength = len;
  805. d.maxLine = line;
  806. }
  807. });
  808. }
  809. // BIDI HELPERS
  810. function iterateBidiSections(order, from, to, f) {
  811. if (!order) { return f(from, to, "ltr", 0) }
  812. var found = false;
  813. for (var i = 0; i < order.length; ++i) {
  814. var part = order[i];
  815. if (part.from < to && part.to > from || from == to && part.to == from) {
  816. f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr", i);
  817. found = true;
  818. }
  819. }
  820. if (!found) { f(from, to, "ltr"); }
  821. }
  822. var bidiOther = null;
  823. function getBidiPartAt(order, ch, sticky) {
  824. var found;
  825. bidiOther = null;
  826. for (var i = 0; i < order.length; ++i) {
  827. var cur = order[i];
  828. if (cur.from < ch && cur.to > ch) { return i }
  829. if (cur.to == ch) {
  830. if (cur.from != cur.to && sticky == "before") { found = i; }
  831. else { bidiOther = i; }
  832. }
  833. if (cur.from == ch) {
  834. if (cur.from != cur.to && sticky != "before") { found = i; }
  835. else { bidiOther = i; }
  836. }
  837. }
  838. return found != null ? found : bidiOther
  839. }
  840. // Bidirectional ordering algorithm
  841. // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm
  842. // that this (partially) implements.
  843. // One-char codes used for character types:
  844. // L (L): Left-to-Right
  845. // R (R): Right-to-Left
  846. // r (AL): Right-to-Left Arabic
  847. // 1 (EN): European Number
  848. // + (ES): European Number Separator
  849. // % (ET): European Number Terminator
  850. // n (AN): Arabic Number
  851. // , (CS): Common Number Separator
  852. // m (NSM): Non-Spacing Mark
  853. // b (BN): Boundary Neutral
  854. // s (B): Paragraph Separator
  855. // t (S): Segment Separator
  856. // w (WS): Whitespace
  857. // N (ON): Other Neutrals
  858. // Returns null if characters are ordered as they appear
  859. // (left-to-right), or an array of sections ({from, to, level}
  860. // objects) in the order in which they occur visually.
  861. var bidiOrdering = (function() {
  862. // Character types for codepoints 0 to 0xff
  863. var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN";
  864. // Character types for codepoints 0x600 to 0x6f9
  865. var arabicTypes = "nnnnnnNNr%%r,rNNmmmmmmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmmmnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmnNmmmmmmrrmmNmmmmrr1111111111";
  866. function charType(code) {
  867. if (code <= 0xf7) { return lowTypes.charAt(code) }
  868. else if (0x590 <= code && code <= 0x5f4) { return "R" }
  869. else if (0x600 <= code && code <= 0x6f9) { return arabicTypes.charAt(code - 0x600) }
  870. else if (0x6ee <= code && code <= 0x8ac) { return "r" }
  871. else if (0x2000 <= code && code <= 0x200b) { return "w" }
  872. else if (code == 0x200c) { return "b" }
  873. else { return "L" }
  874. }
  875. var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/;
  876. var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/;
  877. function BidiSpan(level, from, to) {
  878. this.level = level;
  879. this.from = from; this.to = to;
  880. }
  881. return function(str, direction) {
  882. var outerType = direction == "ltr" ? "L" : "R";
  883. if (str.length == 0 || direction == "ltr" && !bidiRE.test(str)) { return false }
  884. var len = str.length, types = [];
  885. for (var i = 0; i < len; ++i)
  886. { types.push(charType(str.charCodeAt(i))); }
  887. // W1. Examine each non-spacing mark (NSM) in the level run, and
  888. // change the type of the NSM to the type of the previous
  889. // character. If the NSM is at the start of the level run, it will
  890. // get the type of sor.
  891. for (var i$1 = 0, prev = outerType; i$1 < len; ++i$1) {
  892. var type = types[i$1];
  893. if (type == "m") { types[i$1] = prev; }
  894. else { prev = type; }
  895. }
  896. // W2. Search backwards from each instance of a European number
  897. // until the first strong type (R, L, AL, or sor) is found. If an
  898. // AL is found, change the type of the European number to Arabic
  899. // number.
  900. // W3. Change all ALs to R.
  901. for (var i$2 = 0, cur = outerType; i$2 < len; ++i$2) {
  902. var type$1 = types[i$2];
  903. if (type$1 == "1" && cur == "r") { types[i$2] = "n"; }
  904. else if (isStrong.test(type$1)) { cur = type$1; if (type$1 == "r") { types[i$2] = "R"; } }
  905. }
  906. // W4. A single European separator between two European numbers
  907. // changes to a European number. A single common separator between
  908. // two numbers of the same type changes to that type.
  909. for (var i$3 = 1, prev$1 = types[0]; i$3 < len - 1; ++i$3) {
  910. var type$2 = types[i$3];
  911. if (type$2 == "+" && prev$1 == "1" && types[i$3+1] == "1") { types[i$3] = "1"; }
  912. else if (type$2 == "," && prev$1 == types[i$3+1] &&
  913. (prev$1 == "1" || prev$1 == "n")) { types[i$3] = prev$1; }
  914. prev$1 = type$2;
  915. }
  916. // W5. A sequence of European terminators adjacent to European
  917. // numbers changes to all European numbers.
  918. // W6. Otherwise, separators and terminators change to Other
  919. // Neutral.
  920. for (var i$4 = 0; i$4 < len; ++i$4) {
  921. var type$3 = types[i$4];
  922. if (type$3 == ",") { types[i$4] = "N"; }
  923. else if (type$3 == "%") {
  924. var end = (void 0);
  925. for (end = i$4 + 1; end < len && types[end] == "%"; ++end) {}
  926. var replace = (i$4 && types[i$4-1] == "!") || (end < len && types[end] == "1") ? "1" : "N";
  927. for (var j = i$4; j < end; ++j) { types[j] = replace; }
  928. i$4 = end - 1;
  929. }
  930. }
  931. // W7. Search backwards from each instance of a European number
  932. // until the first strong type (R, L, or sor) is found. If an L is
  933. // found, then change the type of the European number to L.
  934. for (var i$5 = 0, cur$1 = outerType; i$5 < len; ++i$5) {
  935. var type$4 = types[i$5];
  936. if (cur$1 == "L" && type$4 == "1") { types[i$5] = "L"; }
  937. else if (isStrong.test(type$4)) { cur$1 = type$4; }
  938. }
  939. // N1. A sequence of neutrals takes the direction of the
  940. // surrounding strong text if the text on both sides has the same
  941. // direction. European and Arabic numbers act as if they were R in
  942. // terms of their influence on neutrals. Start-of-level-run (sor)
  943. // and end-of-level-run (eor) are used at level run boundaries.
  944. // N2. Any remaining neutrals take the embedding direction.
  945. for (var i$6 = 0; i$6 < len; ++i$6) {
  946. if (isNeutral.test(types[i$6])) {
  947. var end$1 = (void 0);
  948. for (end$1 = i$6 + 1; end$1 < len && isNeutral.test(types[end$1]); ++end$1) {}
  949. var before = (i$6 ? types[i$6-1] : outerType) == "L";
  950. var after = (end$1 < len ? types[end$1] : outerType) == "L";
  951. var replace$1 = before == after ? (before ? "L" : "R") : outerType;
  952. for (var j$1 = i$6; j$1 < end$1; ++j$1) { types[j$1] = replace$1; }
  953. i$6 = end$1 - 1;
  954. }
  955. }
  956. // Here we depart from the documented algorithm, in order to avoid
  957. // building up an actual levels array. Since there are only three
  958. // levels (0, 1, 2) in an implementation that doesn't take
  959. // explicit embedding into account, we can build up the order on
  960. // the fly, without following the level-based algorithm.
  961. var order = [], m;
  962. for (var i$7 = 0; i$7 < len;) {
  963. if (countsAsLeft.test(types[i$7])) {
  964. var start = i$7;
  965. for (++i$7; i$7 < len && countsAsLeft.test(types[i$7]); ++i$7) {}
  966. order.push(new BidiSpan(0, start, i$7));
  967. } else {
  968. var pos = i$7, at = order.length;
  969. for (++i$7; i$7 < len && types[i$7] != "L"; ++i$7) {}
  970. for (var j$2 = pos; j$2 < i$7;) {
  971. if (countsAsNum.test(types[j$2])) {
  972. if (pos < j$2) { order.splice(at, 0, new BidiSpan(1, pos, j$2)); }
  973. var nstart = j$2;
  974. for (++j$2; j$2 < i$7 && countsAsNum.test(types[j$2]); ++j$2) {}
  975. order.splice(at, 0, new BidiSpan(2, nstart, j$2));
  976. pos = j$2;
  977. } else { ++j$2; }
  978. }
  979. if (pos < i$7) { order.splice(at, 0, new BidiSpan(1, pos, i$7)); }
  980. }
  981. }
  982. if (direction == "ltr") {
  983. if (order[0].level == 1 && (m = str.match(/^\s+/))) {
  984. order[0].from = m[0].length;
  985. order.unshift(new BidiSpan(0, 0, m[0].length));
  986. }
  987. if (lst(order).level == 1 && (m = str.match(/\s+$/))) {
  988. lst(order).to -= m[0].length;
  989. order.push(new BidiSpan(0, len - m[0].length, len));
  990. }
  991. }
  992. return direction == "rtl" ? order.reverse() : order
  993. }
  994. })();
  995. // Get the bidi ordering for the given line (and cache it). Returns
  996. // false for lines that are fully left-to-right, and an array of
  997. // BidiSpan objects otherwise.
  998. function getOrder(line, direction) {
  999. var order = line.order;
  1000. if (order == null) { order = line.order = bidiOrdering(line.text, direction); }
  1001. return order
  1002. }
  1003. // EVENT HANDLING
  1004. // Lightweight event framework. on/off also work on DOM nodes,
  1005. // registering native DOM handlers.
  1006. var noHandlers = [];
  1007. var on = function(emitter, type, f) {
  1008. if (emitter.addEventListener) {
  1009. emitter.addEventListener(type, f, false);
  1010. } else if (emitter.attachEvent) {
  1011. emitter.attachEvent("on" + type, f);
  1012. } else {
  1013. var map$$1 = emitter._handlers || (emitter._handlers = {});
  1014. map$$1[type] = (map$$1[type] || noHandlers).concat(f);
  1015. }
  1016. };
  1017. function getHandlers(emitter, type) {
  1018. return emitter._handlers && emitter._handlers[type] || noHandlers
  1019. }
  1020. function off(emitter, type, f) {
  1021. if (emitter.removeEventListener) {
  1022. emitter.removeEventListener(type, f, false);
  1023. } else if (emitter.detachEvent) {
  1024. emitter.detachEvent("on" + type, f);
  1025. } else {
  1026. var map$$1 = emitter._handlers, arr = map$$1 && map$$1[type];
  1027. if (arr) {
  1028. var index = indexOf(arr, f);
  1029. if (index > -1)
  1030. { map$$1[type] = arr.slice(0, index).concat(arr.slice(index + 1)); }
  1031. }
  1032. }
  1033. }
  1034. function signal(emitter, type /*, values...*/) {
  1035. var handlers = getHandlers(emitter, type);
  1036. if (!handlers.length) { return }
  1037. var args = Array.prototype.slice.call(arguments, 2);
  1038. for (var i = 0; i < handlers.length; ++i) { handlers[i].apply(null, args); }
  1039. }
  1040. // The DOM events that CodeMirror handles can be overridden by
  1041. // registering a (non-DOM) handler on the editor for the event name,
  1042. // and preventDefault-ing the event in that handler.
  1043. function signalDOMEvent(cm, e, override) {
  1044. if (typeof e == "string")
  1045. { e = {type: e, preventDefault: function() { this.defaultPrevented = true; }}; }
  1046. signal(cm, override || e.type, cm, e);
  1047. return e_defaultPrevented(e) || e.codemirrorIgnore
  1048. }
  1049. function signalCursorActivity(cm) {
  1050. var arr = cm._handlers && cm._handlers.cursorActivity;
  1051. if (!arr) { return }
  1052. var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = []);
  1053. for (var i = 0; i < arr.length; ++i) { if (indexOf(set, arr[i]) == -1)
  1054. { set.push(arr[i]); } }
  1055. }
  1056. function hasHandler(emitter, type) {
  1057. return getHandlers(emitter, type).length > 0
  1058. }
  1059. // Add on and off methods to a constructor's prototype, to make
  1060. // registering events on such objects more convenient.
  1061. function eventMixin(ctor) {
  1062. ctor.prototype.on = function(type, f) {on(this, type, f);};
  1063. ctor.prototype.off = function(type, f) {off(this, type, f);};
  1064. }
  1065. // Due to the fact that we still support jurassic IE versions, some
  1066. // compatibility wrappers are needed.
  1067. function e_preventDefault(e) {
  1068. if (e.preventDefault) { e.preventDefault(); }
  1069. else { e.returnValue = false; }
  1070. }
  1071. function e_stopPropagation(e) {
  1072. if (e.stopPropagation) { e.stopPropagation(); }
  1073. else { e.cancelBubble = true; }
  1074. }
  1075. function e_defaultPrevented(e) {
  1076. return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false
  1077. }
  1078. function e_stop(e) {e_preventDefault(e); e_stopPropagation(e);}
  1079. function e_target(e) {return e.target || e.srcElement}
  1080. function e_button(e) {
  1081. var b = e.which;
  1082. if (b == null) {
  1083. if (e.button & 1) { b = 1; }
  1084. else if (e.button & 2) { b = 3; }
  1085. else if (e.button & 4) { b = 2; }
  1086. }
  1087. if (mac && e.ctrlKey && b == 1) { b = 3; }
  1088. return b
  1089. }
  1090. // Detect drag-and-drop
  1091. var dragAndDrop = function() {
  1092. // There is *some* kind of drag-and-drop support in IE6-8, but I
  1093. // couldn't get it to work yet.
  1094. if (ie && ie_version < 9) { return false }
  1095. var div = elt('div');
  1096. return "draggable" in div || "dragDrop" in div
  1097. }();
  1098. var zwspSupported;
  1099. function zeroWidthElement(measure) {
  1100. if (zwspSupported == null) {
  1101. var test = elt("span", "\u200b");
  1102. removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")]));
  1103. if (measure.firstChild.offsetHeight != 0)
  1104. { zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8); }
  1105. }
  1106. var node = zwspSupported ? elt("span", "\u200b") :
  1107. elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px");
  1108. node.setAttribute("cm-text", "");
  1109. return node
  1110. }
  1111. // Feature-detect IE's crummy client rect reporting for bidi text
  1112. var badBidiRects;
  1113. function hasBadBidiRects(measure) {
  1114. if (badBidiRects != null) { return badBidiRects }
  1115. var txt = removeChildrenAndAdd(measure, document.createTextNode("A\u062eA"));
  1116. var r0 = range(txt, 0, 1).getBoundingClientRect();
  1117. var r1 = range(txt, 1, 2).getBoundingClientRect();
  1118. removeChildren(measure);
  1119. if (!r0 || r0.left == r0.right) { return false } // Safari returns null in some cases (#2780)
  1120. return badBidiRects = (r1.right - r0.right < 3)
  1121. }
  1122. // See if "".split is the broken IE version, if so, provide an
  1123. // alternative way to split lines.
  1124. var splitLinesAuto = "\n\nb".split(/\n/).length != 3 ? function (string) {
  1125. var pos = 0, result = [], l = string.length;
  1126. while (pos <= l) {
  1127. var nl = string.indexOf("\n", pos);
  1128. if (nl == -1) { nl = string.length; }
  1129. var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl);
  1130. var rt = line.indexOf("\r");
  1131. if (rt != -1) {
  1132. result.push(line.slice(0, rt));
  1133. pos += rt + 1;
  1134. } else {
  1135. result.push(line);
  1136. pos = nl + 1;
  1137. }
  1138. }
  1139. return result
  1140. } : function (string) { return string.split(/\r\n?|\n/); };
  1141. var hasSelection = window.getSelection ? function (te) {
  1142. try { return te.selectionStart != te.selectionEnd }
  1143. catch(e) { return false }
  1144. } : function (te) {
  1145. var range$$1;
  1146. try {range$$1 = te.ownerDocument.selection.createRange();}
  1147. catch(e) {}
  1148. if (!range$$1 || range$$1.parentElement() != te) { return false }
  1149. return range$$1.compareEndPoints("StartToEnd", range$$1) != 0
  1150. };
  1151. var hasCopyEvent = (function () {
  1152. var e = elt("div");
  1153. if ("oncopy" in e) { return true }
  1154. e.setAttribute("oncopy", "return;");
  1155. return typeof e.oncopy == "function"
  1156. })();
  1157. var badZoomedRects = null;
  1158. function hasBadZoomedRects(measure) {
  1159. if (badZoomedRects != null) { return badZoomedRects }
  1160. var node = removeChildrenAndAdd(measure, elt("span", "x"));
  1161. var normal = node.getBoundingClientRect();
  1162. var fromRange = range(node, 0, 1).getBoundingClientRect();
  1163. return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1
  1164. }
  1165. // Known modes, by name and by MIME
  1166. var modes = {};
  1167. var mimeModes = {};
  1168. // Extra arguments are stored as the mode's dependencies, which is
  1169. // used by (legacy) mechanisms like loadmode.js to automatically
  1170. // load a mode. (Preferred mechanism is the require/define calls.)
  1171. function defineMode(name, mode) {
  1172. if (arguments.length > 2)
  1173. { mode.dependencies = Array.prototype.slice.call(arguments, 2); }
  1174. modes[name] = mode;
  1175. }
  1176. function defineMIME(mime, spec) {
  1177. mimeModes[mime] = spec;
  1178. }
  1179. // Given a MIME type, a {name, ...options} config object, or a name
  1180. // string, return a mode config object.
  1181. function resolveMode(spec) {
  1182. if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) {
  1183. spec = mimeModes[spec];
  1184. } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) {
  1185. var found = mimeModes[spec.name];
  1186. if (typeof found == "string") { found = {name: found}; }
  1187. spec = createObj(found, spec);
  1188. spec.name = found.name;
  1189. } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) {
  1190. return resolveMode("application/xml")
  1191. } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+json$/.test(spec)) {
  1192. return resolveMode("application/json")
  1193. }
  1194. if (typeof spec == "string") { return {name: spec} }
  1195. else { return spec || {name: "null"} }
  1196. }
  1197. // Given a mode spec (anything that resolveMode accepts), find and
  1198. // initialize an actual mode object.
  1199. function getMode(options, spec) {
  1200. spec = resolveMode(spec);
  1201. var mfactory = modes[spec.name];
  1202. if (!mfactory) { return getMode(options, "text/plain") }
  1203. var modeObj = mfactory(options, spec);
  1204. if (modeExtensions.hasOwnProperty(spec.name)) {
  1205. var exts = modeExtensions[spec.name];
  1206. for (var prop in exts) {
  1207. if (!exts.hasOwnProperty(prop)) { continue }
  1208. if (modeObj.hasOwnProperty(prop)) { modeObj["_" + prop] = modeObj[prop]; }
  1209. modeObj[prop] = exts[prop];
  1210. }
  1211. }
  1212. modeObj.name = spec.name;
  1213. if (spec.helperType) { modeObj.helperType = spec.helperType; }
  1214. if (spec.modeProps) { for (var prop$1 in spec.modeProps)
  1215. { modeObj[prop$1] = spec.modeProps[prop$1]; } }
  1216. return modeObj
  1217. }
  1218. // This can be used to attach properties to mode objects from
  1219. // outside the actual mode definition.
  1220. var modeExtensions = {};
  1221. function extendMode(mode, properties) {
  1222. var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {});
  1223. copyObj(properties, exts);
  1224. }
  1225. function copyState(mode, state) {
  1226. if (state === true) { return state }
  1227. if (mode.copyState) { return mode.copyState(state) }
  1228. var nstate = {};
  1229. for (var n in state) {
  1230. var val = state[n];
  1231. if (val instanceof Array) { val = val.concat([]); }
  1232. nstate[n] = val;
  1233. }
  1234. return nstate
  1235. }
  1236. // Given a mode and a state (for that mode), find the inner mode and
  1237. // state at the position that the state refers to.
  1238. function innerMode(mode, state) {
  1239. var info;
  1240. while (mode.innerMode) {
  1241. info = mode.innerMode(state);
  1242. if (!info || info.mode == mode) { break }
  1243. state = info.state;
  1244. mode = info.mode;
  1245. }
  1246. return info || {mode: mode, state: state}
  1247. }
  1248. function startState(mode, a1, a2) {
  1249. return mode.startState ? mode.startState(a1, a2) : true
  1250. }
  1251. // STRING STREAM
  1252. // Fed to the mode parsers, provides helper functions to make
  1253. // parsers more succinct.
  1254. var StringStream = function(string, tabSize, lineOracle) {
  1255. this.pos = this.start = 0;
  1256. this.string = string;
  1257. this.tabSize = tabSize || 8;
  1258. this.lastColumnPos = this.lastColumnValue = 0;
  1259. this.lineStart = 0;
  1260. this.lineOracle = lineOracle;
  1261. };
  1262. StringStream.prototype.eol = function () {return this.pos >= this.string.length};
  1263. StringStream.prototype.sol = function () {return this.pos == this.lineStart};
  1264. StringStream.prototype.peek = function () {return this.string.charAt(this.pos) || undefined};
  1265. StringStream.prototype.next = function () {
  1266. if (this.pos < this.string.length)
  1267. { return this.string.charAt(this.pos++) }
  1268. };
  1269. StringStream.prototype.eat = function (match) {
  1270. var ch = this.string.charAt(this.pos);
  1271. var ok;
  1272. if (typeof match == "string") { ok = ch == match; }
  1273. else { ok = ch && (match.test ? match.test(ch) : match(ch)); }
  1274. if (ok) {++this.pos; return ch}
  1275. };
  1276. StringStream.prototype.eatWhile = function (match) {
  1277. var start = this.pos;
  1278. while (this.eat(match)){}
  1279. return this.pos > start
  1280. };
  1281. StringStream.prototype.eatSpace = function () {
  1282. var this$1 = this;
  1283. var start = this.pos;
  1284. while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) { ++this$1.pos; }
  1285. return this.pos > start
  1286. };
  1287. StringStream.prototype.skipToEnd = function () {this.pos = this.string.length;};
  1288. StringStream.prototype.skipTo = function (ch) {
  1289. var found = this.string.indexOf(ch, this.pos);
  1290. if (found > -1) {this.pos = found; return true}
  1291. };
  1292. StringStream.prototype.backUp = function (n) {this.pos -= n;};
  1293. StringStream.prototype.column = function () {
  1294. if (this.lastColumnPos < this.start) {
  1295. this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue);
  1296. this.lastColumnPos = this.start;
  1297. }
  1298. return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0)
  1299. };
  1300. StringStream.prototype.indentation = function () {
  1301. return countColumn(this.string, null, this.tabSize) -
  1302. (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0)
  1303. };
  1304. StringStream.prototype.match = function (pattern, consume, caseInsensitive) {
  1305. if (typeof pattern == "string") {
  1306. var cased = function (str) { return caseInsensitive ? str.toLowerCase() : str; };
  1307. var substr = this.string.substr(this.pos, pattern.length);
  1308. if (cased(substr) == cased(pattern)) {
  1309. if (consume !== false) { this.pos += pattern.length; }
  1310. return true
  1311. }
  1312. } else {
  1313. var match = this.string.slice(this.pos).match(pattern);
  1314. if (match && match.index > 0) { return null }
  1315. if (match && consume !== false) { this.pos += match[0].length; }
  1316. return match
  1317. }
  1318. };
  1319. StringStream.prototype.current = function (){return this.string.slice(this.start, this.pos)};
  1320. StringStream.prototype.hideFirstChars = function (n, inner) {
  1321. this.lineStart += n;
  1322. try { return inner() }
  1323. finally { this.lineStart -= n; }
  1324. };
  1325. StringStream.prototype.lookAhead = function (n) {
  1326. var oracle = this.lineOracle;
  1327. return oracle && oracle.lookAhead(n)
  1328. };
  1329. StringStream.prototype.baseToken = function () {
  1330. var oracle = this.lineOracle;
  1331. return oracle && oracle.baseToken(this.pos)
  1332. };
  1333. var SavedContext = function(state, lookAhead) {
  1334. this.state = state;
  1335. this.lookAhead = lookAhead;
  1336. };
  1337. var Context = function(doc, state, line, lookAhead) {
  1338. this.state = state;
  1339. this.doc = doc;
  1340. this.line = line;
  1341. this.maxLookAhead = lookAhead || 0;
  1342. this.baseTokens = null;
  1343. this.baseTokenPos = 1;
  1344. };
  1345. Context.prototype.lookAhead = function (n) {
  1346. var line = this.doc.getLine(this.line + n);
  1347. if (line != null && n > this.maxLookAhead) { this.maxLookAhead = n; }
  1348. return line
  1349. };
  1350. Context.prototype.baseToken = function (n) {
  1351. var this$1 = this;
  1352. if (!this.baseTokens) { return null }
  1353. while (this.baseTokens[this.baseTokenPos] <= n)
  1354. { this$1.baseTokenPos += 2; }
  1355. var type = this.baseTokens[this.baseTokenPos + 1];
  1356. return {type: type && type.replace(/( |^)overlay .*/, ""),
  1357. size: this.baseTokens[this.baseTokenPos] - n}
  1358. };
  1359. Context.prototype.nextLine = function () {
  1360. this.line++;
  1361. if (this.maxLookAhead > 0) { this.maxLookAhead--; }
  1362. };
  1363. Context.fromSaved = function (doc, saved, line) {
  1364. if (saved instanceof SavedContext)
  1365. { return new Context(doc, copyState(doc.mode, saved.state), line, saved.lookAhead) }
  1366. else
  1367. { return new Context(doc, copyState(doc.mode, saved), line) }
  1368. };
  1369. Context.prototype.save = function (copy) {
  1370. var state = copy !== false ? copyState(this.doc.mode, this.state) : this.state;
  1371. return this.maxLookAhead > 0 ? new SavedContext(state, this.maxLookAhead) : state
  1372. };
  1373. // Compute a style array (an array starting with a mode generation
  1374. // -- for invalidation -- followed by pairs of end positions and
  1375. // style strings), which is used to highlight the tokens on the
  1376. // line.
  1377. function highlightLine(cm, line, context, forceToEnd) {
  1378. // A styles array always starts with a number identifying the
  1379. // mode/overlays that it is based on (for easy invalidation).
  1380. var st = [cm.state.modeGen], lineClasses = {};
  1381. // Compute the base array of styles
  1382. runMode(cm, line.text, cm.doc.mode, context, function (end, style) { return st.push(end, style); },
  1383. lineClasses, forceToEnd);
  1384. var state = context.state;
  1385. // Run overlays, adjust style array.
  1386. var loop = function ( o ) {
  1387. context.baseTokens = st;
  1388. var overlay = cm.state.overlays[o], i = 1, at = 0;
  1389. context.state = true;
  1390. runMode(cm, line.text, overlay.mode, context, function (end, style) {
  1391. var start = i;
  1392. // Ensure there's a token end at the current position, and that i points at it
  1393. while (at < end) {
  1394. var i_end = st[i];
  1395. if (i_end > end)
  1396. { st.splice(i, 1, end, st[i+1], i_end); }
  1397. i += 2;
  1398. at = Math.min(end, i_end);
  1399. }
  1400. if (!style) { return }
  1401. if (overlay.opaque) {
  1402. st.splice(start, i - start, end, "overlay " + style);
  1403. i = start + 2;
  1404. } else {
  1405. for (; start < i; start += 2) {
  1406. var cur = st[start+1];
  1407. st[start+1] = (cur ? cur + " " : "") + "overlay " + style;
  1408. }
  1409. }
  1410. }, lineClasses);
  1411. context.state = state;
  1412. context.baseTokens = null;
  1413. context.baseTokenPos = 1;
  1414. };
  1415. for (var o = 0; o < cm.state.overlays.length; ++o) loop( o );
  1416. return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null}
  1417. }
  1418. function getLineStyles(cm, line, updateFrontier) {
  1419. if (!line.styles || line.styles[0] != cm.state.modeGen) {
  1420. var context = getContextBefore(cm, lineNo(line));
  1421. var resetState = line.text.length > cm.options.maxHighlightLength && copyState(cm.doc.mode, context.state);
  1422. var result = highlightLine(cm, line, context);
  1423. if (resetState) { context.state = resetState; }
  1424. line.stateAfter = context.save(!resetState);
  1425. line.styles = result.styles;
  1426. if (result.classes) { line.styleClasses = result.classes; }
  1427. else if (line.styleClasses) { line.styleClasses = null; }
  1428. if (updateFrontier === cm.doc.highlightFrontier)
  1429. { cm.doc.modeFrontier = Math.max(cm.doc.modeFrontier, ++cm.doc.highlightFrontier); }
  1430. }
  1431. return line.styles
  1432. }
  1433. function getContextBefore(cm, n, precise) {
  1434. var doc = cm.doc, display = cm.display;
  1435. if (!doc.mode.startState) { return new Context(doc, true, n) }
  1436. var start = findStartLine(cm, n, precise);
  1437. var saved = start > doc.first && getLine(doc, start - 1).stateAfter;
  1438. var context = saved ? Context.fromSaved(doc, saved, start) : new Context(doc, startState(doc.mode), start);
  1439. doc.iter(start, n, function (line) {
  1440. processLine(cm, line.text, context);
  1441. var pos = context.line;
  1442. line.stateAfter = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo ? context.save() : null;
  1443. context.nextLine();
  1444. });
  1445. if (precise) { doc.modeFrontier = context.line; }
  1446. return context
  1447. }
  1448. // Lightweight form of highlight -- proceed over this line and
  1449. // update state, but don't save a style array. Used for lines that
  1450. // aren't currently visible.
  1451. function processLine(cm, text, context, startAt) {
  1452. var mode = cm.doc.mode;
  1453. var stream = new StringStream(text, cm.options.tabSize, context);
  1454. stream.start = stream.pos = startAt || 0;
  1455. if (text == "") { callBlankLine(mode, context.state); }
  1456. while (!stream.eol()) {
  1457. readToken(mode, stream, context.state);
  1458. stream.start = stream.pos;
  1459. }
  1460. }
  1461. function callBlankLine(mode, state) {
  1462. if (mode.blankLine) { return mode.blankLine(state) }
  1463. if (!mode.innerMode) { return }
  1464. var inner = innerMode(mode, state);
  1465. if (inner.mode.blankLine) { return inner.mode.blankLine(inner.state) }
  1466. }
  1467. function readToken(mode, stream, state, inner) {
  1468. for (var i = 0; i < 10; i++) {
  1469. if (inner) { inner[0] = innerMode(mode, state).mode; }
  1470. var style = mode.token(stream, state);
  1471. if (stream.pos > stream.start) { return style }
  1472. }
  1473. throw new Error("Mode " + mode.name + " failed to advance stream.")
  1474. }
  1475. var Token = function(stream, type, state) {
  1476. this.start = stream.start; this.end = stream.pos;
  1477. this.string = stream.current();
  1478. this.type = type || null;
  1479. this.state = state;
  1480. };
  1481. // Utility for getTokenAt and getLineTokens
  1482. function takeToken(cm, pos, precise, asArray) {
  1483. var doc = cm.doc, mode = doc.mode, style;
  1484. pos = clipPos(doc, pos);
  1485. var line = getLine(doc, pos.line), context = getContextBefore(cm, pos.line, precise);
  1486. var stream = new StringStream(line.text, cm.options.tabSize, context), tokens;
  1487. if (asArray) { tokens = []; }
  1488. while ((asArray || stream.pos < pos.ch) && !stream.eol()) {
  1489. stream.start = stream.pos;
  1490. style = readToken(mode, stream, context.state);
  1491. if (asArray) { tokens.push(new Token(stream, style, copyState(doc.mode, context.state))); }
  1492. }
  1493. return asArray ? tokens : new Token(stream, style, context.state)
  1494. }
  1495. function extractLineClasses(type, output) {
  1496. if (type) { for (;;) {
  1497. var lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/);
  1498. if (!lineClass) { break }
  1499. type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length);
  1500. var prop = lineClass[1] ? "bgClass" : "textClass";
  1501. if (output[prop] == null)
  1502. { output[prop] = lineClass[2]; }
  1503. else if (!(new RegExp("(?:^|\s)" + lineClass[2] + "(?:$|\s)")).test(output[prop]))
  1504. { output[prop] += " " + lineClass[2]; }
  1505. } }
  1506. return type
  1507. }
  1508. // Run the given mode's parser over a line, calling f for each token.
  1509. function runMode(cm, text, mode, context, f, lineClasses, forceToEnd) {
  1510. var flattenSpans = mode.flattenSpans;
  1511. if (flattenSpans == null) { flattenSpans = cm.options.flattenSpans; }
  1512. var curStart = 0, curStyle = null;
  1513. var stream = new StringStream(text, cm.options.tabSize, context), style;
  1514. var inner = cm.options.addModeClass && [null];
  1515. if (text == "") { extractLineClasses(callBlankLine(mode, context.state), lineClasses); }
  1516. while (!stream.eol()) {
  1517. if (stream.pos > cm.options.maxHighlightLength) {
  1518. flattenSpans = false;
  1519. if (forceToEnd) { processLine(cm, text, context, stream.pos); }
  1520. stream.pos = text.length;
  1521. style = null;
  1522. } else {
  1523. style = extractLineClasses(readToken(mode, stream, context.state, inner), lineClasses);
  1524. }
  1525. if (inner) {
  1526. var mName = inner[0].name;
  1527. if (mName) { style = "m-" + (style ? mName + " " + style : mName); }
  1528. }
  1529. if (!flattenSpans || curStyle != style) {
  1530. while (curStart < stream.start) {
  1531. curStart = Math.min(stream.start, curStart + 5000);
  1532. f(curStart, curStyle);
  1533. }
  1534. curStyle = style;
  1535. }
  1536. stream.start = stream.pos;
  1537. }
  1538. while (curStart < stream.pos) {
  1539. // Webkit seems to refuse to render text nodes longer than 57444
  1540. // characters, and returns inaccurate measurements in nodes
  1541. // starting around 5000 chars.
  1542. var pos = Math.min(stream.pos, curStart + 5000);
  1543. f(pos, curStyle);
  1544. curStart = pos;
  1545. }
  1546. }
  1547. // Finds the line to start with when starting a parse. Tries to
  1548. // find a line with a stateAfter, so that it can start with a
  1549. // valid state. If that fails, it returns the line with the
  1550. // smallest indentation, which tends to need the least context to
  1551. // parse correctly.
  1552. function findStartLine(cm, n, precise) {
  1553. var minindent, minline, doc = cm.doc;
  1554. var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100);
  1555. for (var search = n; search > lim; --search) {
  1556. if (search <= doc.first) { return doc.first }
  1557. var line = getLine(doc, search - 1), after = line.stateAfter;
  1558. if (after && (!precise || search + (after instanceof SavedContext ? after.lookAhead : 0) <= doc.modeFrontier))
  1559. { return search }
  1560. var indented = countColumn(line.text, null, cm.options.tabSize);
  1561. if (minline == null || minindent > indented) {
  1562. minline = search - 1;
  1563. minindent = indented;
  1564. }
  1565. }
  1566. return minline
  1567. }
  1568. function retreatFrontier(doc, n) {
  1569. doc.modeFrontier = Math.min(doc.modeFrontier, n);
  1570. if (doc.highlightFrontier < n - 10) { return }
  1571. var start = doc.first;
  1572. for (var line = n - 1; line > start; line--) {
  1573. var saved = getLine(doc, line).stateAfter;
  1574. // change is on 3
  1575. // state on line 1 looked ahead 2 -- so saw 3
  1576. // test 1 + 2 < 3 should cover this
  1577. if (saved && (!(saved instanceof SavedContext) || line + saved.lookAhead < n)) {
  1578. start = line + 1;
  1579. break
  1580. }
  1581. }
  1582. doc.highlightFrontier = Math.min(doc.highlightFrontier, start);
  1583. }
  1584. // LINE DATA STRUCTURE
  1585. // Line objects. These hold state related to a line, including
  1586. // highlighting info (the styles array).
  1587. var Line = function(text, markedSpans, estimateHeight) {
  1588. this.text = text;
  1589. attachMarkedSpans(this, markedSpans);
  1590. this.height = estimateHeight ? estimateHeight(this) : 1;
  1591. };
  1592. Line.prototype.lineNo = function () { return lineNo(this) };
  1593. eventMixin(Line);
  1594. // Change the content (text, markers) of a line. Automatically
  1595. // invalidates cached information and tries to re-estimate the
  1596. // line's height.
  1597. function updateLine(line, text, markedSpans, estimateHeight) {
  1598. line.text = text;
  1599. if (line.stateAfter) { line.stateAfter = null; }
  1600. if (line.styles) { line.styles = null; }
  1601. if (line.order != null) { line.order = null; }
  1602. detachMarkedSpans(line);
  1603. attachMarkedSpans(line, markedSpans);
  1604. var estHeight = estimateHeight ? estimateHeight(line) : 1;
  1605. if (estHeight != line.height) { updateLineHeight(line, estHeight); }
  1606. }
  1607. // Detach a line from the document tree and its markers.
  1608. function cleanUpLine(line) {
  1609. line.parent = null;
  1610. detachMarkedSpans(line);
  1611. }
  1612. // Convert a style as returned by a mode (either null, or a string
  1613. // containing one or more styles) to a CSS style. This is cached,
  1614. // and also looks for line-wide styles.
  1615. var styleToClassCache = {};
  1616. var styleToClassCacheWithMode = {};
  1617. function interpretTokenStyle(style, options) {
  1618. if (!style || /^\s*$/.test(style)) { return null }
  1619. var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache;
  1620. return cache[style] ||
  1621. (cache[style] = style.replace(/\S+/g, "cm-$&"))
  1622. }
  1623. // Render the DOM representation of the text of a line. Also builds
  1624. // up a 'line map', which points at the DOM nodes that represent
  1625. // specific stretches of text, and is used by the measuring code.
  1626. // The returned object contains the DOM node, this map, and
  1627. // information about line-wide styles that were set by the mode.
  1628. function buildLineContent(cm, lineView) {
  1629. // The padding-right forces the element to have a 'border', which
  1630. // is needed on Webkit to be able to get line-level bounding
  1631. // rectangles for it (in measureChar).
  1632. var content = eltP("span", null, null, webkit ? "padding-right: .1px" : null);
  1633. var builder = {pre: eltP("pre", [content], "CodeMirror-line"), content: content,
  1634. col: 0, pos: 0, cm: cm,
  1635. trailingSpace: false,
  1636. splitSpaces: (ie || webkit) && cm.getOption("lineWrapping")};
  1637. lineView.measure = {};
  1638. // Iterate over the logical lines that make up this visual line.
  1639. for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) {
  1640. var line = i ? lineView.rest[i - 1] : lineView.line, order = (void 0);
  1641. builder.pos = 0;
  1642. builder.addToken = buildToken;
  1643. // Optionally wire in some hacks into the token-rendering
  1644. // algorithm, to deal with browser quirks.
  1645. if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line, cm.doc.direction)))
  1646. { builder.addToken = buildTokenBadBidi(builder.addToken, order); }
  1647. builder.map = [];
  1648. var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line);
  1649. insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate));
  1650. if (line.styleClasses) {
  1651. if (line.styleClasses.bgClass)
  1652. { builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || ""); }
  1653. if (line.styleClasses.textClass)
  1654. { builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || ""); }
  1655. }
  1656. // Ensure at least a single node is present, for measuring.
  1657. if (builder.map.length == 0)
  1658. { builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure))); }
  1659. // Store the map and a cache object for the current logical line
  1660. if (i == 0) {
  1661. lineView.measure.map = builder.map;
  1662. lineView.measure.cache = {};
  1663. } else {
  1664. (lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map)
  1665. ;(lineView.measure.caches || (lineView.measure.caches = [])).push({});
  1666. }
  1667. }
  1668. // See issue #2901
  1669. if (webkit) {
  1670. var last = builder.content.lastChild;
  1671. if (/\bcm-tab\b/.test(last.className) || (last.querySelector && last.querySelector(".cm-tab")))
  1672. { builder.content.className = "cm-tab-wrap-hack"; }
  1673. }
  1674. signal(cm, "renderLine", cm, lineView.line, builder.pre);
  1675. if (builder.pre.className)
  1676. { builder.textClass = joinClasses(builder.pre.className, builder.textClass || ""); }
  1677. return builder
  1678. }
  1679. function defaultSpecialCharPlaceholder(ch) {
  1680. var token = elt("span", "\u2022", "cm-invalidchar");
  1681. token.title = "\\u" + ch.charCodeAt(0).toString(16);
  1682. token.setAttribute("aria-label", token.title);
  1683. return token
  1684. }
  1685. // Build up the DOM representation for a single token, and add it to
  1686. // the line map. Takes care to render special characters separately.
  1687. function buildToken(builder, text, style, startStyle, endStyle, title, css) {
  1688. if (!text) { return }
  1689. var displayText = builder.splitSpaces ? splitSpaces(text, builder.trailingSpace) : text;
  1690. var special = builder.cm.state.specialChars, mustWrap = false;
  1691. var content;
  1692. if (!special.test(text)) {
  1693. builder.col += text.length;
  1694. content = document.createTextNode(displayText);
  1695. builder.map.push(builder.pos, builder.pos + text.length, content);
  1696. if (ie && ie_version < 9) { mustWrap = true; }
  1697. builder.pos += text.length;
  1698. } else {
  1699. content = document.createDocumentFragment();
  1700. var pos = 0;
  1701. while (true) {
  1702. special.lastIndex = pos;
  1703. var m = special.exec(text);
  1704. var skipped = m ? m.index - pos : text.length - pos;
  1705. if (skipped) {
  1706. var txt = document.createTextNode(displayText.slice(pos, pos + skipped));
  1707. if (ie && ie_version < 9) { content.appendChild(elt("span", [txt])); }
  1708. else { content.appendChild(txt); }
  1709. builder.map.push(builder.pos, builder.pos + skipped, txt);
  1710. builder.col += skipped;
  1711. builder.pos += skipped;
  1712. }
  1713. if (!m) { break }
  1714. pos += skipped + 1;
  1715. var txt$1 = (void 0);
  1716. if (m[0] == "\t") {
  1717. var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize;
  1718. txt$1 = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab"));
  1719. txt$1.setAttribute("role", "presentation");
  1720. txt$1.setAttribute("cm-text", "\t");
  1721. builder.col += tabWidth;
  1722. } else if (m[0] == "\r" || m[0] == "\n") {
  1723. txt$1 = content.appendChild(elt("span", m[0] == "\r" ? "\u240d" : "\u2424", "cm-invalidchar"));
  1724. txt$1.setAttribute("cm-text", m[0]);
  1725. builder.col += 1;
  1726. } else {
  1727. txt$1 = builder.cm.options.specialCharPlaceholder(m[0]);
  1728. txt$1.setAttribute("cm-text", m[0]);
  1729. if (ie && ie_version < 9) { content.appendChild(elt("span", [txt$1])); }
  1730. else { content.appendChild(txt$1); }
  1731. builder.col += 1;
  1732. }
  1733. builder.map.push(builder.pos, builder.pos + 1, txt$1);
  1734. builder.pos++;
  1735. }
  1736. }
  1737. builder.trailingSpace = displayText.charCodeAt(text.length - 1) == 32;
  1738. if (style || startStyle || endStyle || mustWrap || css) {
  1739. var fullStyle = style || "";
  1740. if (startStyle) { fullStyle += startStyle; }
  1741. if (endStyle) { fullStyle += endStyle; }
  1742. var token = elt("span", [content], fullStyle, css);
  1743. if (title) { token.title = title; }
  1744. return builder.content.appendChild(token)
  1745. }
  1746. builder.content.appendChild(content);
  1747. }
  1748. function splitSpaces(text, trailingBefore) {
  1749. if (text.length > 1 && !/ /.test(text)) { return text }
  1750. var spaceBefore = trailingBefore, result = "";
  1751. for (var i = 0; i < text.length; i++) {
  1752. var ch = text.charAt(i);
  1753. if (ch == " " && spaceBefore && (i == text.length - 1 || text.charCodeAt(i + 1) == 32))
  1754. { ch = "\u00a0"; }
  1755. result += ch;
  1756. spaceBefore = ch == " ";
  1757. }
  1758. return result
  1759. }
  1760. // Work around nonsense dimensions being reported for stretches of
  1761. // right-to-left text.
  1762. function buildTokenBadBidi(inner, order) {
  1763. return function (builder, text, style, startStyle, endStyle, title, css) {
  1764. style = style ? style + " cm-force-border" : "cm-force-border";
  1765. var start = builder.pos, end = start + text.length;
  1766. for (;;) {
  1767. // Find the part that overlaps with the start of this text
  1768. var part = (void 0);
  1769. for (var i = 0; i < order.length; i++) {
  1770. part = order[i];
  1771. if (part.to > start && part.from <= start) { break }
  1772. }
  1773. if (part.to >= end) { return inner(builder, text, style, startStyle, endStyle, title, css) }
  1774. inner(builder, text.slice(0, part.to - start), style, startStyle, null, title, css);
  1775. startStyle = null;
  1776. text = text.slice(part.to - start);
  1777. start = part.to;
  1778. }
  1779. }
  1780. }
  1781. function buildCollapsedSpan(builder, size, marker, ignoreWidget) {
  1782. var widget = !ignoreWidget && marker.widgetNode;
  1783. if (widget) { builder.map.push(builder.pos, builder.pos + size, widget); }
  1784. if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) {
  1785. if (!widget)
  1786. { widget = builder.content.appendChild(document.createElement("span")); }
  1787. widget.setAttribute("cm-marker", marker.id);
  1788. }
  1789. if (widget) {
  1790. builder.cm.display.input.setUneditable(widget);
  1791. builder.content.appendChild(widget);
  1792. }
  1793. builder.pos += size;
  1794. builder.trailingSpace = false;
  1795. }
  1796. // Outputs a number of spans to make up a line, taking highlighting
  1797. // and marked text into account.
  1798. function insertLineContent(line, builder, styles) {
  1799. var spans = line.markedSpans, allText = line.text, at = 0;
  1800. if (!spans) {
  1801. for (var i$1 = 1; i$1 < styles.length; i$1+=2)
  1802. { builder.addToken(builder, allText.slice(at, at = styles[i$1]), interpretTokenStyle(styles[i$1+1], builder.cm.options)); }
  1803. return
  1804. }
  1805. var len = allText.length, pos = 0, i = 1, text = "", style, css;
  1806. var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, title, collapsed;
  1807. for (;;) {
  1808. if (nextChange == pos) { // Update current marker set
  1809. spanStyle = spanEndStyle = spanStartStyle = title = css = "";
  1810. collapsed = null; nextChange = Infinity;
  1811. var foundBookmarks = [], endStyles = (void 0);
  1812. for (var j = 0; j < spans.length; ++j) {
  1813. var sp = spans[j], m = sp.marker;
  1814. if (m.type == "bookmark" && sp.from == pos && m.widgetNode) {
  1815. foundBookmarks.push(m);
  1816. } else if (sp.from <= pos && (sp.to == null || sp.to > pos || m.collapsed && sp.to == pos && sp.from == pos)) {
  1817. if (sp.to != null && sp.to != pos && nextChange > sp.to) {
  1818. nextChange = sp.to;
  1819. spanEndStyle = "";
  1820. }
  1821. if (m.className) { spanStyle += " " + m.className; }
  1822. if (m.css) { css = (css ? css + ";" : "") + m.css; }
  1823. if (m.startStyle && sp.from == pos) { spanStartStyle += " " + m.startStyle; }
  1824. if (m.endStyle && sp.to == nextChange) { (endStyles || (endStyles = [])).push(m.endStyle, sp.to); }
  1825. if (m.title && !title) { title = m.title; }
  1826. if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0))
  1827. { collapsed = sp; }
  1828. } else if (sp.from > pos && nextChange > sp.from) {
  1829. nextChange = sp.from;
  1830. }
  1831. }
  1832. if (endStyles) { for (var j$1 = 0; j$1 < endStyles.length; j$1 += 2)
  1833. { if (endStyles[j$1 + 1] == nextChange) { spanEndStyle += " " + endStyles[j$1]; } } }
  1834. if (!collapsed || collapsed.from == pos) { for (var j$2 = 0; j$2 < foundBookmarks.length; ++j$2)
  1835. { buildCollapsedSpan(builder, 0, foundBookmarks[j$2]); } }
  1836. if (collapsed && (collapsed.from || 0) == pos) {
  1837. buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos,
  1838. collapsed.marker, collapsed.from == null);
  1839. if (collapsed.to == null) { return }
  1840. if (collapsed.to == pos) { collapsed = false; }
  1841. }
  1842. }
  1843. if (pos >= len) { break }
  1844. var upto = Math.min(len, nextChange);
  1845. while (true) {
  1846. if (text) {
  1847. var end = pos + text.length;
  1848. if (!collapsed) {
  1849. var tokenText = end > upto ? text.slice(0, upto - pos) : text;
  1850. builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle,
  1851. spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", title, css);
  1852. }
  1853. if (end >= upto) {text = text.slice(upto - pos); pos = upto; break}
  1854. pos = end;
  1855. spanStartStyle = "";
  1856. }
  1857. text = allText.slice(at, at = styles[i++]);
  1858. style = interpretTokenStyle(styles[i++], builder.cm.options);
  1859. }
  1860. }
  1861. }
  1862. // These objects are used to represent the visible (currently drawn)
  1863. // part of the document. A LineView may correspond to multiple
  1864. // logical lines, if those are connected by collapsed ranges.
  1865. function LineView(doc, line, lineN) {
  1866. // The starting line
  1867. this.line = line;
  1868. // Continuing lines, if any
  1869. this.rest = visualLineContinued(line);
  1870. // Number of logical lines in this visual line
  1871. this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1;
  1872. this.node = this.text = null;
  1873. this.hidden = lineIsHidden(doc, line);
  1874. }
  1875. // Create a range of LineView objects for the given lines.
  1876. function buildViewArray(cm, from, to) {
  1877. var array = [], nextPos;
  1878. for (var pos = from; pos < to; pos = nextPos) {
  1879. var view = new LineView(cm.doc, getLine(cm.doc, pos), pos);
  1880. nextPos = pos + view.size;
  1881. array.push(view);
  1882. }
  1883. return array
  1884. }
  1885. var operationGroup = null;
  1886. function pushOperation(op) {
  1887. if (operationGroup) {
  1888. operationGroup.ops.push(op);
  1889. } else {
  1890. op.ownsGroup = operationGroup = {
  1891. ops: [op],
  1892. delayedCallbacks: []
  1893. };
  1894. }
  1895. }
  1896. function fireCallbacksForOps(group) {
  1897. // Calls delayed callbacks and cursorActivity handlers until no
  1898. // new ones appear
  1899. var callbacks = group.delayedCallbacks, i = 0;
  1900. do {
  1901. for (; i < callbacks.length; i++)
  1902. { callbacks[i].call(null); }
  1903. for (var j = 0; j < group.ops.length; j++) {
  1904. var op = group.ops[j];
  1905. if (op.cursorActivityHandlers)
  1906. { while (op.cursorActivityCalled < op.cursorActivityHandlers.length)
  1907. { op.cursorActivityHandlers[op.cursorActivityCalled++].call(null, op.cm); } }
  1908. }
  1909. } while (i < callbacks.length)
  1910. }
  1911. function finishOperation(op, endCb) {
  1912. var group = op.ownsGroup;
  1913. if (!group) { return }
  1914. try { fireCallbacksForOps(group); }
  1915. finally {
  1916. operationGroup = null;
  1917. endCb(group);
  1918. }
  1919. }
  1920. var orphanDelayedCallbacks = null;
  1921. // Often, we want to signal events at a point where we are in the
  1922. // middle of some work, but don't want the handler to start calling
  1923. // other methods on the editor, which might be in an inconsistent
  1924. // state or simply not expect any other events to happen.
  1925. // signalLater looks whether there are any handlers, and schedules
  1926. // them to be executed when the last operation ends, or, if no
  1927. // operation is active, when a timeout fires.
  1928. function signalLater(emitter, type /*, values...*/) {
  1929. var arr = getHandlers(emitter, type);
  1930. if (!arr.length) { return }
  1931. var args = Array.prototype.slice.call(arguments, 2), list;
  1932. if (operationGroup) {
  1933. list = operationGroup.delayedCallbacks;
  1934. } else if (orphanDelayedCallbacks) {
  1935. list = orphanDelayedCallbacks;
  1936. } else {
  1937. list = orphanDelayedCallbacks = [];
  1938. setTimeout(fireOrphanDelayed, 0);
  1939. }
  1940. var loop = function ( i ) {
  1941. list.push(function () { return arr[i].apply(null, args); });
  1942. };
  1943. for (var i = 0; i < arr.length; ++i)
  1944. loop( i );
  1945. }
  1946. function fireOrphanDelayed() {
  1947. var delayed = orphanDelayedCallbacks;
  1948. orphanDelayedCallbacks = null;
  1949. for (var i = 0; i < delayed.length; ++i) { delayed[i](); }
  1950. }
  1951. // When an aspect of a line changes, a string is added to
  1952. // lineView.changes. This updates the relevant part of the line's
  1953. // DOM structure.
  1954. function updateLineForChanges(cm, lineView, lineN, dims) {
  1955. for (var j = 0; j < lineView.changes.length; j++) {
  1956. var type = lineView.changes[j];
  1957. if (type == "text") { updateLineText(cm, lineView); }
  1958. else if (type == "gutter") { updateLineGutter(cm, lineView, lineN, dims); }
  1959. else if (type == "class") { updateLineClasses(cm, lineView); }
  1960. else if (type == "widget") { updateLineWidgets(cm, lineView, dims); }
  1961. }
  1962. lineView.changes = null;
  1963. }
  1964. // Lines with gutter elements, widgets or a background class need to
  1965. // be wrapped, and have the extra elements added to the wrapper div
  1966. function ensureLineWrapped(lineView) {
  1967. if (lineView.node == lineView.text) {
  1968. lineView.node = elt("div", null, null, "position: relative");
  1969. if (lineView.text.parentNode)
  1970. { lineView.text.parentNode.replaceChild(lineView.node, lineView.text); }
  1971. lineView.node.appendChild(lineView.text);
  1972. if (ie && ie_version < 8) { lineView.node.style.zIndex = 2; }
  1973. }
  1974. return lineView.node
  1975. }
  1976. function updateLineBackground(cm, lineView) {
  1977. var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass;
  1978. if (cls) { cls += " CodeMirror-linebackground"; }
  1979. if (lineView.background) {
  1980. if (cls) { lineView.background.className = cls; }
  1981. else { lineView.background.parentNode.removeChild(lineView.background); lineView.background = null; }
  1982. } else if (cls) {
  1983. var wrap = ensureLineWrapped(lineView);
  1984. lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild);
  1985. cm.display.input.setUneditable(lineView.background);
  1986. }
  1987. }
  1988. // Wrapper around buildLineContent which will reuse the structure
  1989. // in display.externalMeasured when possible.
  1990. function getLineContent(cm, lineView) {
  1991. var ext = cm.display.externalMeasured;
  1992. if (ext && ext.line == lineView.line) {
  1993. cm.display.externalMeasured = null;
  1994. lineView.measure = ext.measure;
  1995. return ext.built
  1996. }
  1997. return buildLineContent(cm, lineView)
  1998. }
  1999. // Redraw the line's text. Interacts with the background and text
  2000. // classes because the mode may output tokens that influence these
  2001. // classes.
  2002. function updateLineText(cm, lineView) {
  2003. var cls = lineView.text.className;
  2004. var built = getLineContent(cm, lineView);
  2005. if (lineView.text == lineView.node) { lineView.node = built.pre; }
  2006. lineView.text.parentNode.replaceChild(built.pre, lineView.text);
  2007. lineView.text = built.pre;
  2008. if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) {
  2009. lineView.bgClass = built.bgClass;
  2010. lineView.textClass = built.textClass;
  2011. updateLineClasses(cm, lineView);
  2012. } else if (cls) {
  2013. lineView.text.className = cls;
  2014. }
  2015. }
  2016. function updateLineClasses(cm, lineView) {
  2017. updateLineBackground(cm, lineView);
  2018. if (lineView.line.wrapClass)
  2019. { ensureLineWrapped(lineView).className = lineView.line.wrapClass; }
  2020. else if (lineView.node != lineView.text)
  2021. { lineView.node.className = ""; }
  2022. var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass;
  2023. lineView.text.className = textClass || "";
  2024. }
  2025. function updateLineGutter(cm, lineView, lineN, dims) {
  2026. if (lineView.gutter) {
  2027. lineView.node.removeChild(lineView.gutter);
  2028. lineView.gutter = null;
  2029. }
  2030. if (lineView.gutterBackground) {
  2031. lineView.node.removeChild(lineView.gutterBackground);
  2032. lineView.gutterBackground = null;
  2033. }
  2034. if (lineView.line.gutterClass) {
  2035. var wrap = ensureLineWrapped(lineView);
  2036. lineView.gutterBackground = elt("div", null, "CodeMirror-gutter-background " + lineView.line.gutterClass,
  2037. ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px; width: " + (dims.gutterTotalWidth) + "px"));
  2038. cm.display.input.setUneditable(lineView.gutterBackground);
  2039. wrap.insertBefore(lineView.gutterBackground, lineView.text);
  2040. }
  2041. var markers = lineView.line.gutterMarkers;
  2042. if (cm.options.lineNumbers || markers) {
  2043. var wrap$1 = ensureLineWrapped(lineView);
  2044. var gutterWrap = lineView.gutter = elt("div", null, "CodeMirror-gutter-wrapper", ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px"));
  2045. cm.display.input.setUneditable(gutterWrap);
  2046. wrap$1.insertBefore(gutterWrap, lineView.text);
  2047. if (lineView.line.gutterClass)
  2048. { gutterWrap.className += " " + lineView.line.gutterClass; }
  2049. if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"]))
  2050. { lineView.lineNumber = gutterWrap.appendChild(
  2051. elt("div", lineNumberFor(cm.options, lineN),
  2052. "CodeMirror-linenumber CodeMirror-gutter-elt",
  2053. ("left: " + (dims.gutterLeft["CodeMirror-linenumbers"]) + "px; width: " + (cm.display.lineNumInnerWidth) + "px"))); }
  2054. if (markers) { for (var k = 0; k < cm.options.gutters.length; ++k) {
  2055. var id = cm.options.gutters[k], found = markers.hasOwnProperty(id) && markers[id];
  2056. if (found)
  2057. { gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt",
  2058. ("left: " + (dims.gutterLeft[id]) + "px; width: " + (dims.gutterWidth[id]) + "px"))); }
  2059. } }
  2060. }
  2061. }
  2062. function updateLineWidgets(cm, lineView, dims) {
  2063. if (lineView.alignable) { lineView.alignable = null; }
  2064. for (var node = lineView.node.firstChild, next = (void 0); node; node = next) {
  2065. next = node.nextSibling;
  2066. if (node.className == "CodeMirror-linewidget")
  2067. { lineView.node.removeChild(node); }
  2068. }
  2069. insertLineWidgets(cm, lineView, dims);
  2070. }
  2071. // Build a line's DOM representation from scratch
  2072. function buildLineElement(cm, lineView, lineN, dims) {
  2073. var built = getLineContent(cm, lineView);
  2074. lineView.text = lineView.node = built.pre;
  2075. if (built.bgClass) { lineView.bgClass = built.bgClass; }
  2076. if (built.textClass) { lineView.textClass = built.textClass; }
  2077. updateLineClasses(cm, lineView);
  2078. updateLineGutter(cm, lineView, lineN, dims);
  2079. insertLineWidgets(cm, lineView, dims);
  2080. return lineView.node
  2081. }
  2082. // A lineView may contain multiple logical lines (when merged by
  2083. // collapsed spans). The widgets for all of them need to be drawn.
  2084. function insertLineWidgets(cm, lineView, dims) {
  2085. insertLineWidgetsFor(cm, lineView.line, lineView, dims, true);
  2086. if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++)
  2087. { insertLineWidgetsFor(cm, lineView.rest[i], lineView, dims, false); } }
  2088. }
  2089. function insertLineWidgetsFor(cm, line, lineView, dims, allowAbove) {
  2090. if (!line.widgets) { return }
  2091. var wrap = ensureLineWrapped(lineView);
  2092. for (var i = 0, ws = line.widgets; i < ws.length; ++i) {
  2093. var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget");
  2094. if (!widget.handleMouseEvents) { node.setAttribute("cm-ignore-events", "true"); }
  2095. positionLineWidget(widget, node, lineView, dims);
  2096. cm.display.input.setUneditable(node);
  2097. if (allowAbove && widget.above)
  2098. { wrap.insertBefore(node, lineView.gutter || lineView.text); }
  2099. else
  2100. { wrap.appendChild(node); }
  2101. signalLater(widget, "redraw");
  2102. }
  2103. }
  2104. function positionLineWidget(widget, node, lineView, dims) {
  2105. if (widget.noHScroll) {
  2106. (lineView.alignable || (lineView.alignable = [])).push(node);
  2107. var width = dims.wrapperWidth;
  2108. node.style.left = dims.fixedPos + "px";
  2109. if (!widget.coverGutter) {
  2110. width -= dims.gutterTotalWidth;
  2111. node.style.paddingLeft = dims.gutterTotalWidth + "px";
  2112. }
  2113. node.style.width = width + "px";
  2114. }
  2115. if (widget.coverGutter) {
  2116. node.style.zIndex = 5;
  2117. node.style.position = "relative";
  2118. if (!widget.noHScroll) { node.style.marginLeft = -dims.gutterTotalWidth + "px"; }
  2119. }
  2120. }
  2121. function widgetHeight(widget) {
  2122. if (widget.height != null) { return widget.height }
  2123. var cm = widget.doc.cm;
  2124. if (!cm) { return 0 }
  2125. if (!contains(document.body, widget.node)) {
  2126. var parentStyle = "position: relative;";
  2127. if (widget.coverGutter)
  2128. { parentStyle += "margin-left: -" + cm.display.gutters.offsetWidth + "px;"; }
  2129. if (widget.noHScroll)
  2130. { parentStyle += "width: " + cm.display.wrapper.clientWidth + "px;"; }
  2131. removeChildrenAndAdd(cm.display.measure, elt("div", [widget.node], null, parentStyle));
  2132. }
  2133. return widget.height = widget.node.parentNode.offsetHeight
  2134. }
  2135. // Return true when the given mouse event happened in a widget
  2136. function eventInWidget(display, e) {
  2137. for (var n = e_target(e); n != display.wrapper; n = n.parentNode) {
  2138. if (!n || (n.nodeType == 1 && n.getAttribute("cm-ignore-events") == "true") ||
  2139. (n.parentNode == display.sizer && n != display.mover))
  2140. { return true }
  2141. }
  2142. }
  2143. // POSITION MEASUREMENT
  2144. function paddingTop(display) {return display.lineSpace.offsetTop}
  2145. function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight}
  2146. function paddingH(display) {
  2147. if (display.cachedPaddingH) { return display.cachedPaddingH }
  2148. var e = removeChildrenAndAdd(display.measure, elt("pre", "x"));
  2149. var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle;
  2150. var data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)};
  2151. if (!isNaN(data.left) && !isNaN(data.right)) { display.cachedPaddingH = data; }
  2152. return data
  2153. }
  2154. function scrollGap(cm) { return scrollerGap - cm.display.nativeBarWidth }
  2155. function displayWidth(cm) {
  2156. return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth
  2157. }
  2158. function displayHeight(cm) {
  2159. return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight
  2160. }
  2161. // Ensure the lineView.wrapping.heights array is populated. This is
  2162. // an array of bottom offsets for the lines that make up a drawn
  2163. // line. When lineWrapping is on, there might be more than one
  2164. // height.
  2165. function ensureLineHeights(cm, lineView, rect) {
  2166. var wrapping = cm.options.lineWrapping;
  2167. var curWidth = wrapping && displayWidth(cm);
  2168. if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) {
  2169. var heights = lineView.measure.heights = [];
  2170. if (wrapping) {
  2171. lineView.measure.width = curWidth;
  2172. var rects = lineView.text.firstChild.getClientRects();
  2173. for (var i = 0; i < rects.length - 1; i++) {
  2174. var cur = rects[i], next = rects[i + 1];
  2175. if (Math.abs(cur.bottom - next.bottom) > 2)
  2176. { heights.push((cur.bottom + next.top) / 2 - rect.top); }
  2177. }
  2178. }
  2179. heights.push(rect.bottom - rect.top);
  2180. }
  2181. }
  2182. // Find a line map (mapping character offsets to text nodes) and a
  2183. // measurement cache for the given line number. (A line view might
  2184. // contain multiple lines when collapsed ranges are present.)
  2185. function mapFromLineView(lineView, line, lineN) {
  2186. if (lineView.line == line)
  2187. { return {map: lineView.measure.map, cache: lineView.measure.cache} }
  2188. for (var i = 0; i < lineView.rest.length; i++)
  2189. { if (lineView.rest[i] == line)
  2190. { return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i]} } }
  2191. for (var i$1 = 0; i$1 < lineView.rest.length; i$1++)
  2192. { if (lineNo(lineView.rest[i$1]) > lineN)
  2193. { return {map: lineView.measure.maps[i$1], cache: lineView.measure.caches[i$1], before: true} } }
  2194. }
  2195. // Render a line into the hidden node display.externalMeasured. Used
  2196. // when measurement is needed for a line that's not in the viewport.
  2197. function updateExternalMeasurement(cm, line) {
  2198. line = visualLine(line);
  2199. var lineN = lineNo(line);
  2200. var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN);
  2201. view.lineN = lineN;
  2202. var built = view.built = buildLineContent(cm, view);
  2203. view.text = built.pre;
  2204. removeChildrenAndAdd(cm.display.lineMeasure, built.pre);
  2205. return view
  2206. }
  2207. // Get a {top, bottom, left, right} box (in line-local coordinates)
  2208. // for a given character.
  2209. function measureChar(cm, line, ch, bias) {
  2210. return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias)
  2211. }
  2212. // Find a line view that corresponds to the given line number.
  2213. function findViewForLine(cm, lineN) {
  2214. if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo)
  2215. { return cm.display.view[findViewIndex(cm, lineN)] }
  2216. var ext = cm.display.externalMeasured;
  2217. if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size)
  2218. { return ext }
  2219. }
  2220. // Measurement can be split in two steps, the set-up work that
  2221. // applies to the whole line, and the measurement of the actual
  2222. // character. Functions like coordsChar, that need to do a lot of
  2223. // measurements in a row, can thus ensure that the set-up work is
  2224. // only done once.
  2225. function prepareMeasureForLine(cm, line) {
  2226. var lineN = lineNo(line);
  2227. var view = findViewForLine(cm, lineN);
  2228. if (view && !view.text) {
  2229. view = null;
  2230. } else if (view && view.changes) {
  2231. updateLineForChanges(cm, view, lineN, getDimensions(cm));
  2232. cm.curOp.forceUpdate = true;
  2233. }
  2234. if (!view)
  2235. { view = updateExternalMeasurement(cm, line); }
  2236. var info = mapFromLineView(view, line, lineN);
  2237. return {
  2238. line: line, view: view, rect: null,
  2239. map: info.map, cache: info.cache, before: info.before,
  2240. hasHeights: false
  2241. }
  2242. }
  2243. // Given a prepared measurement object, measures the position of an
  2244. // actual character (or fetches it from the cache).
  2245. function measureCharPrepared(cm, prepared, ch, bias, varHeight) {
  2246. if (prepared.before) { ch = -1; }
  2247. var key = ch + (bias || ""), found;
  2248. if (prepared.cache.hasOwnProperty(key)) {
  2249. found = prepared.cache[key];
  2250. } else {
  2251. if (!prepared.rect)
  2252. { prepared.rect = prepared.view.text.getBoundingClientRect(); }
  2253. if (!prepared.hasHeights) {
  2254. ensureLineHeights(cm, prepared.view, prepared.rect);
  2255. prepared.hasHeights = true;
  2256. }
  2257. found = measureCharInner(cm, prepared, ch, bias);
  2258. if (!found.bogus) { prepared.cache[key] = found; }
  2259. }
  2260. return {left: found.left, right: found.right,
  2261. top: varHeight ? found.rtop : found.top,
  2262. bottom: varHeight ? found.rbottom : found.bottom}
  2263. }
  2264. var nullRect = {left: 0, right: 0, top: 0, bottom: 0};
  2265. function nodeAndOffsetInLineMap(map$$1, ch, bias) {
  2266. var node, start, end, collapse, mStart, mEnd;
  2267. // First, search the line map for the text node corresponding to,
  2268. // or closest to, the target character.
  2269. for (var i = 0; i < map$$1.length; i += 3) {
  2270. mStart = map$$1[i];
  2271. mEnd = map$$1[i + 1];
  2272. if (ch < mStart) {
  2273. start = 0; end = 1;
  2274. collapse = "left";
  2275. } else if (ch < mEnd) {
  2276. start = ch - mStart;
  2277. end = start + 1;
  2278. } else if (i == map$$1.length - 3 || ch == mEnd && map$$1[i + 3] > ch) {
  2279. end = mEnd - mStart;
  2280. start = end - 1;
  2281. if (ch >= mEnd) { collapse = "right"; }
  2282. }
  2283. if (start != null) {
  2284. node = map$$1[i + 2];
  2285. if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right"))
  2286. { collapse = bias; }
  2287. if (bias == "left" && start == 0)
  2288. { while (i && map$$1[i - 2] == map$$1[i - 3] && map$$1[i - 1].insertLeft) {
  2289. node = map$$1[(i -= 3) + 2];
  2290. collapse = "left";
  2291. } }
  2292. if (bias == "right" && start == mEnd - mStart)
  2293. { while (i < map$$1.length - 3 && map$$1[i + 3] == map$$1[i + 4] && !map$$1[i + 5].insertLeft) {
  2294. node = map$$1[(i += 3) + 2];
  2295. collapse = "right";
  2296. } }
  2297. break
  2298. }
  2299. }
  2300. return {node: node, start: start, end: end, collapse: collapse, coverStart: mStart, coverEnd: mEnd}
  2301. }
  2302. function getUsefulRect(rects, bias) {
  2303. var rect = nullRect;
  2304. if (bias == "left") { for (var i = 0; i < rects.length; i++) {
  2305. if ((rect = rects[i]).left != rect.right) { break }
  2306. } } else { for (var i$1 = rects.length - 1; i$1 >= 0; i$1--) {
  2307. if ((rect = rects[i$1]).left != rect.right) { break }
  2308. } }
  2309. return rect
  2310. }
  2311. function measureCharInner(cm, prepared, ch, bias) {
  2312. var place = nodeAndOffsetInLineMap(prepared.map, ch, bias);
  2313. var node = place.node, start = place.start, end = place.end, collapse = place.collapse;
  2314. var rect;
  2315. if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates.
  2316. for (var i$1 = 0; i$1 < 4; i$1++) { // Retry a maximum of 4 times when nonsense rectangles are returned
  2317. while (start && isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) { --start; }
  2318. while (place.coverStart + end < place.coverEnd && isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) { ++end; }
  2319. if (ie && ie_version < 9 && start == 0 && end == place.coverEnd - place.coverStart)
  2320. { rect = node.parentNode.getBoundingClientRect(); }
  2321. else
  2322. { rect = getUsefulRect(range(node, start, end).getClientRects(), bias); }
  2323. if (rect.left || rect.right || start == 0) { break }
  2324. end = start;
  2325. start = start - 1;
  2326. collapse = "right";
  2327. }
  2328. if (ie && ie_version < 11) { rect = maybeUpdateRectForZooming(cm.display.measure, rect); }
  2329. } else { // If it is a widget, simply get the box for the whole widget.
  2330. if (start > 0) { collapse = bias = "right"; }
  2331. var rects;
  2332. if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1)
  2333. { rect = rects[bias == "right" ? rects.length - 1 : 0]; }
  2334. else
  2335. { rect = node.getBoundingClientRect(); }
  2336. }
  2337. if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) {
  2338. var rSpan = node.parentNode.getClientRects()[0];
  2339. if (rSpan)
  2340. { rect = {left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom}; }
  2341. else
  2342. { rect = nullRect; }
  2343. }
  2344. var rtop = rect.top - prepared.rect.top, rbot = rect.bottom - prepared.rect.top;
  2345. var mid = (rtop + rbot) / 2;
  2346. var heights = prepared.view.measure.heights;
  2347. var i = 0;
  2348. for (; i < heights.length - 1; i++)
  2349. { if (mid < heights[i]) { break } }
  2350. var top = i ? heights[i - 1] : 0, bot = heights[i];
  2351. var result = {left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left,
  2352. right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left,
  2353. top: top, bottom: bot};
  2354. if (!rect.left && !rect.right) { result.bogus = true; }
  2355. if (!cm.options.singleCursorHeightPerLine) { result.rtop = rtop; result.rbottom = rbot; }
  2356. return result
  2357. }
  2358. // Work around problem with bounding client rects on ranges being
  2359. // returned incorrectly when zoomed on IE10 and below.
  2360. function maybeUpdateRectForZooming(measure, rect) {
  2361. if (!window.screen || screen.logicalXDPI == null ||
  2362. screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure))
  2363. { return rect }
  2364. var scaleX = screen.logicalXDPI / screen.deviceXDPI;
  2365. var scaleY = screen.logicalYDPI / screen.deviceYDPI;
  2366. return {left: rect.left * scaleX, right: rect.right * scaleX,
  2367. top: rect.top * scaleY, bottom: rect.bottom * scaleY}
  2368. }
  2369. function clearLineMeasurementCacheFor(lineView) {
  2370. if (lineView.measure) {
  2371. lineView.measure.cache = {};
  2372. lineView.measure.heights = null;
  2373. if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++)
  2374. { lineView.measure.caches[i] = {}; } }
  2375. }
  2376. }
  2377. function clearLineMeasurementCache(cm) {
  2378. cm.display.externalMeasure = null;
  2379. removeChildren(cm.display.lineMeasure);
  2380. for (var i = 0; i < cm.display.view.length; i++)
  2381. { clearLineMeasurementCacheFor(cm.display.view[i]); }
  2382. }
  2383. function clearCaches(cm) {
  2384. clearLineMeasurementCache(cm);
  2385. cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null;
  2386. if (!cm.options.lineWrapping) { cm.display.maxLineChanged = true; }
  2387. cm.display.lineNumChars = null;
  2388. }
  2389. function pageScrollX() {
  2390. // Work around https://bugs.chromium.org/p/chromium/issues/detail?id=489206
  2391. // which causes page_Offset and bounding client rects to use
  2392. // different reference viewports and invalidate our calculations.
  2393. if (chrome && android) { return -(document.body.getBoundingClientRect().left - parseInt(getComputedStyle(document.body).marginLeft)) }
  2394. return window.pageXOffset || (document.documentElement || document.body).scrollLeft
  2395. }
  2396. function pageScrollY() {
  2397. if (chrome && android) { return -(document.body.getBoundingClientRect().top - parseInt(getComputedStyle(document.body).marginTop)) }
  2398. return window.pageYOffset || (document.documentElement || document.body).scrollTop
  2399. }
  2400. function widgetTopHeight(lineObj) {
  2401. var height = 0;
  2402. if (lineObj.widgets) { for (var i = 0; i < lineObj.widgets.length; ++i) { if (lineObj.widgets[i].above)
  2403. { height += widgetHeight(lineObj.widgets[i]); } } }
  2404. return height
  2405. }
  2406. // Converts a {top, bottom, left, right} box from line-local
  2407. // coordinates into another coordinate system. Context may be one of
  2408. // "line", "div" (display.lineDiv), "local"./null (editor), "window",
  2409. // or "page".
  2410. function intoCoordSystem(cm, lineObj, rect, context, includeWidgets) {
  2411. if (!includeWidgets) {
  2412. var height = widgetTopHeight(lineObj);
  2413. rect.top += height; rect.bottom += height;
  2414. }
  2415. if (context == "line") { return rect }
  2416. if (!context) { context = "local"; }
  2417. var yOff = heightAtLine(lineObj);
  2418. if (context == "local") { yOff += paddingTop(cm.display); }
  2419. else { yOff -= cm.display.viewOffset; }
  2420. if (context == "page" || context == "window") {
  2421. var lOff = cm.display.lineSpace.getBoundingClientRect();
  2422. yOff += lOff.top + (context == "window" ? 0 : pageScrollY());
  2423. var xOff = lOff.left + (context == "window" ? 0 : pageScrollX());
  2424. rect.left += xOff; rect.right += xOff;
  2425. }
  2426. rect.top += yOff; rect.bottom += yOff;
  2427. return rect
  2428. }
  2429. // Coverts a box from "div" coords to another coordinate system.
  2430. // Context may be "window", "page", "div", or "local"./null.
  2431. function fromCoordSystem(cm, coords, context) {
  2432. if (context == "div") { return coords }
  2433. var left = coords.left, top = coords.top;
  2434. // First move into "page" coordinate system
  2435. if (context == "page") {
  2436. left -= pageScrollX();
  2437. top -= pageScrollY();
  2438. } else if (context == "local" || !context) {
  2439. var localBox = cm.display.sizer.getBoundingClientRect();
  2440. left += localBox.left;
  2441. top += localBox.top;
  2442. }
  2443. var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect();
  2444. return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top}
  2445. }
  2446. function charCoords(cm, pos, context, lineObj, bias) {
  2447. if (!lineObj) { lineObj = getLine(cm.doc, pos.line); }
  2448. return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context)
  2449. }
  2450. // Returns a box for a given cursor position, which may have an
  2451. // 'other' property containing the position of the secondary cursor
  2452. // on a bidi boundary.
  2453. // A cursor Pos(line, char, "before") is on the same visual line as `char - 1`
  2454. // and after `char - 1` in writing order of `char - 1`
  2455. // A cursor Pos(line, char, "after") is on the same visual line as `char`
  2456. // and before `char` in writing order of `char`
  2457. // Examples (upper-case letters are RTL, lower-case are LTR):
  2458. // Pos(0, 1, ...)
  2459. // before after
  2460. // ab a|b a|b
  2461. // aB a|B aB|
  2462. // Ab |Ab A|b
  2463. // AB B|A B|A
  2464. // Every position after the last character on a line is considered to stick
  2465. // to the last character on the line.
  2466. function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) {
  2467. lineObj = lineObj || getLine(cm.doc, pos.line);
  2468. if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj); }
  2469. function get(ch, right) {
  2470. var m = measureCharPrepared(cm, preparedMeasure, ch, right ? "right" : "left", varHeight);
  2471. if (right) { m.left = m.right; } else { m.right = m.left; }
  2472. return intoCoordSystem(cm, lineObj, m, context)
  2473. }
  2474. var order = getOrder(lineObj, cm.doc.direction), ch = pos.ch, sticky = pos.sticky;
  2475. if (ch >= lineObj.text.length) {
  2476. ch = lineObj.text.length;
  2477. sticky = "before";
  2478. } else if (ch <= 0) {
  2479. ch = 0;
  2480. sticky = "after";
  2481. }
  2482. if (!order) { return get(sticky == "before" ? ch - 1 : ch, sticky == "before") }
  2483. function getBidi(ch, partPos, invert) {
  2484. var part = order[partPos], right = part.level == 1;
  2485. return get(invert ? ch - 1 : ch, right != invert)
  2486. }
  2487. var partPos = getBidiPartAt(order, ch, sticky);
  2488. var other = bidiOther;
  2489. var val = getBidi(ch, partPos, sticky == "before");
  2490. if (other != null) { val.other = getBidi(ch, other, sticky != "before"); }
  2491. return val
  2492. }
  2493. // Used to cheaply estimate the coordinates for a position. Used for
  2494. // intermediate scroll updates.
  2495. function estimateCoords(cm, pos) {
  2496. var left = 0;
  2497. pos = clipPos(cm.doc, pos);
  2498. if (!cm.options.lineWrapping) { left = charWidth(cm.display) * pos.ch; }
  2499. var lineObj = getLine(cm.doc, pos.line);
  2500. var top = heightAtLine(lineObj) + paddingTop(cm.display);
  2501. return {left: left, right: left, top: top, bottom: top + lineObj.height}
  2502. }
  2503. // Positions returned by coordsChar contain some extra information.
  2504. // xRel is the relative x position of the input coordinates compared
  2505. // to the found position (so xRel > 0 means the coordinates are to
  2506. // the right of the character position, for example). When outside
  2507. // is true, that means the coordinates lie outside the line's
  2508. // vertical range.
  2509. function PosWithInfo(line, ch, sticky, outside, xRel) {
  2510. var pos = Pos(line, ch, sticky);
  2511. pos.xRel = xRel;
  2512. if (outside) { pos.outside = true; }
  2513. return pos
  2514. }
  2515. // Compute the character position closest to the given coordinates.
  2516. // Input must be lineSpace-local ("div" coordinate system).
  2517. function coordsChar(cm, x, y) {
  2518. var doc = cm.doc;
  2519. y += cm.display.viewOffset;
  2520. if (y < 0) { return PosWithInfo(doc.first, 0, null, true, -1) }
  2521. var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1;
  2522. if (lineN > last)
  2523. { return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, null, true, 1) }
  2524. if (x < 0) { x = 0; }
  2525. var lineObj = getLine(doc, lineN);
  2526. for (;;) {
  2527. var found = coordsCharInner(cm, lineObj, lineN, x, y);
  2528. var merged = collapsedSpanAtEnd(lineObj);
  2529. var mergedPos = merged && merged.find(0, true);
  2530. if (merged && (found.ch > mergedPos.from.ch || found.ch == mergedPos.from.ch && found.xRel > 0))
  2531. { lineN = lineNo(lineObj = mergedPos.to.line); }
  2532. else
  2533. { return found }
  2534. }
  2535. }
  2536. function wrappedLineExtent(cm, lineObj, preparedMeasure, y) {
  2537. y -= widgetTopHeight(lineObj);
  2538. var end = lineObj.text.length;
  2539. var begin = findFirst(function (ch) { return measureCharPrepared(cm, preparedMeasure, ch - 1).bottom <= y; }, end, 0);
  2540. end = findFirst(function (ch) { return measureCharPrepared(cm, preparedMeasure, ch).top > y; }, begin, end);
  2541. return {begin: begin, end: end}
  2542. }
  2543. function wrappedLineExtentChar(cm, lineObj, preparedMeasure, target) {
  2544. if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj); }
  2545. var targetTop = intoCoordSystem(cm, lineObj, measureCharPrepared(cm, preparedMeasure, target), "line").top;
  2546. return wrappedLineExtent(cm, lineObj, preparedMeasure, targetTop)
  2547. }
  2548. // Returns true if the given side of a box is after the given
  2549. // coordinates, in top-to-bottom, left-to-right order.
  2550. function boxIsAfter(box, x, y, left) {
  2551. return box.bottom <= y ? false : box.top > y ? true : (left ? box.left : box.right) > x
  2552. }
  2553. function coordsCharInner(cm, lineObj, lineNo$$1, x, y) {
  2554. // Move y into line-local coordinate space
  2555. y -= heightAtLine(lineObj);
  2556. var preparedMeasure = prepareMeasureForLine(cm, lineObj);
  2557. // When directly calling `measureCharPrepared`, we have to adjust
  2558. // for the widgets at this line.
  2559. var widgetHeight$$1 = widgetTopHeight(lineObj);
  2560. var begin = 0, end = lineObj.text.length, ltr = true;
  2561. var order = getOrder(lineObj, cm.doc.direction);
  2562. // If the line isn't plain left-to-right text, first figure out
  2563. // which bidi section the coordinates fall into.
  2564. if (order) {
  2565. var part = (cm.options.lineWrapping ? coordsBidiPartWrapped : coordsBidiPart)
  2566. (cm, lineObj, lineNo$$1, preparedMeasure, order, x, y);
  2567. ltr = part.level != 1;
  2568. // The awkward -1 offsets are needed because findFirst (called
  2569. // on these below) will treat its first bound as inclusive,
  2570. // second as exclusive, but we want to actually address the
  2571. // characters in the part's range
  2572. begin = ltr ? part.from : part.to - 1;
  2573. end = ltr ? part.to : part.from - 1;
  2574. }
  2575. // A binary search to find the first character whose bounding box
  2576. // starts after the coordinates. If we run across any whose box wrap
  2577. // the coordinates, store that.
  2578. var chAround = null, boxAround = null;
  2579. var ch = findFirst(function (ch) {
  2580. var box = measureCharPrepared(cm, preparedMeasure, ch);
  2581. box.top += widgetHeight$$1; box.bottom += widgetHeight$$1;
  2582. if (!boxIsAfter(box, x, y, false)) { return false }
  2583. if (box.top <= y && box.left <= x) {
  2584. chAround = ch;
  2585. boxAround = box;
  2586. }
  2587. return true
  2588. }, begin, end);
  2589. var baseX, sticky, outside = false;
  2590. // If a box around the coordinates was found, use that
  2591. if (boxAround) {
  2592. // Distinguish coordinates nearer to the left or right side of the box
  2593. var atLeft = x - boxAround.left < boxAround.right - x, atStart = atLeft == ltr;
  2594. ch = chAround + (atStart ? 0 : 1);
  2595. sticky = atStart ? "after" : "before";
  2596. baseX = atLeft ? boxAround.left : boxAround.right;
  2597. } else {
  2598. // (Adjust for extended bound, if necessary.)
  2599. if (!ltr && (ch == end || ch == begin)) { ch++; }
  2600. // To determine which side to associate with, get the box to the
  2601. // left of the character and compare it's vertical position to the
  2602. // coordinates
  2603. sticky = ch == 0 ? "after" : ch == lineObj.text.length ? "before" :
  2604. (measureCharPrepared(cm, preparedMeasure, ch - (ltr ? 1 : 0)).bottom + widgetHeight$$1 <= y) == ltr ?
  2605. "after" : "before";
  2606. // Now get accurate coordinates for this place, in order to get a
  2607. // base X position
  2608. var coords = cursorCoords(cm, Pos(lineNo$$1, ch, sticky), "line", lineObj, preparedMeasure);
  2609. baseX = coords.left;
  2610. outside = y < coords.top || y >= coords.bottom;
  2611. }
  2612. ch = skipExtendingChars(lineObj.text, ch, 1);
  2613. return PosWithInfo(lineNo$$1, ch, sticky, outside, x - baseX)
  2614. }
  2615. function coordsBidiPart(cm, lineObj, lineNo$$1, preparedMeasure, order, x, y) {
  2616. // Bidi parts are sorted left-to-right, and in a non-line-wrapping
  2617. // situation, we can take this ordering to correspond to the visual
  2618. // ordering. This finds the first part whose end is after the given
  2619. // coordinates.
  2620. var index = findFirst(function (i) {
  2621. var part = order[i], ltr = part.level != 1;
  2622. return boxIsAfter(cursorCoords(cm, Pos(lineNo$$1, ltr ? part.to : part.from, ltr ? "before" : "after"),
  2623. "line", lineObj, preparedMeasure), x, y, true)
  2624. }, 0, order.length - 1);
  2625. var part = order[index];
  2626. // If this isn't the first part, the part's start is also after
  2627. // the coordinates, and the coordinates aren't on the same line as
  2628. // that start, move one part back.
  2629. if (index > 0) {
  2630. var ltr = part.level != 1;
  2631. var start = cursorCoords(cm, Pos(lineNo$$1, ltr ? part.from : part.to, ltr ? "after" : "before"),
  2632. "line", lineObj, preparedMeasure);
  2633. if (boxIsAfter(start, x, y, true) && start.top > y)
  2634. { part = order[index - 1]; }
  2635. }
  2636. return part
  2637. }
  2638. function coordsBidiPartWrapped(cm, lineObj, _lineNo, preparedMeasure, order, x, y) {
  2639. // In a wrapped line, rtl text on wrapping boundaries can do things
  2640. // that don't correspond to the ordering in our `order` array at
  2641. // all, so a binary search doesn't work, and we want to return a
  2642. // part that only spans one line so that the binary search in
  2643. // coordsCharInner is safe. As such, we first find the extent of the
  2644. // wrapped line, and then do a flat search in which we discard any
  2645. // spans that aren't on the line.
  2646. var ref = wrappedLineExtent(cm, lineObj, preparedMeasure, y);
  2647. var begin = ref.begin;
  2648. var end = ref.end;
  2649. if (/\s/.test(lineObj.text.charAt(end - 1))) { end--; }
  2650. var part = null, closestDist = null;
  2651. for (var i = 0; i < order.length; i++) {
  2652. var p = order[i];
  2653. if (p.from >= end || p.to <= begin) { continue }
  2654. var ltr = p.level != 1;
  2655. var endX = measureCharPrepared(cm, preparedMeasure, ltr ? Math.min(end, p.to) - 1 : Math.max(begin, p.from)).right;
  2656. // Weigh against spans ending before this, so that they are only
  2657. // picked if nothing ends after
  2658. var dist = endX < x ? x - endX + 1e9 : endX - x;
  2659. if (!part || closestDist > dist) {
  2660. part = p;
  2661. closestDist = dist;
  2662. }
  2663. }
  2664. if (!part) { part = order[order.length - 1]; }
  2665. // Clip the part to the wrapped line.
  2666. if (part.from < begin) { part = {from: begin, to: part.to, level: part.level}; }
  2667. if (part.to > end) { part = {from: part.from, to: end, level: part.level}; }
  2668. return part
  2669. }
  2670. var measureText;
  2671. // Compute the default text height.
  2672. function textHeight(display) {
  2673. if (display.cachedTextHeight != null) { return display.cachedTextHeight }
  2674. if (measureText == null) {
  2675. measureText = elt("pre");
  2676. // Measure a bunch of lines, for browsers that compute
  2677. // fractional heights.
  2678. for (var i = 0; i < 49; ++i) {
  2679. measureText.appendChild(document.createTextNode("x"));
  2680. measureText.appendChild(elt("br"));
  2681. }
  2682. measureText.appendChild(document.createTextNode("x"));
  2683. }
  2684. removeChildrenAndAdd(display.measure, measureText);
  2685. var height = measureText.offsetHeight / 50;
  2686. if (height > 3) { display.cachedTextHeight = height; }
  2687. removeChildren(display.measure);
  2688. return height || 1
  2689. }
  2690. // Compute the default character width.
  2691. function charWidth(display) {
  2692. if (display.cachedCharWidth != null) { return display.cachedCharWidth }
  2693. var anchor = elt("span", "xxxxxxxxxx");
  2694. var pre = elt("pre", [anchor]);
  2695. removeChildrenAndAdd(display.measure, pre);
  2696. var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10;
  2697. if (width > 2) { display.cachedCharWidth = width; }
  2698. return width || 10
  2699. }
  2700. // Do a bulk-read of the DOM positions and sizes needed to draw the
  2701. // view, so that we don't interleave reading and writing to the DOM.
  2702. function getDimensions(cm) {
  2703. var d = cm.display, left = {}, width = {};
  2704. var gutterLeft = d.gutters.clientLeft;
  2705. for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) {
  2706. left[cm.options.gutters[i]] = n.offsetLeft + n.clientLeft + gutterLeft;
  2707. width[cm.options.gutters[i]] = n.clientWidth;
  2708. }
  2709. return {fixedPos: compensateForHScroll(d),
  2710. gutterTotalWidth: d.gutters.offsetWidth,
  2711. gutterLeft: left,
  2712. gutterWidth: width,
  2713. wrapperWidth: d.wrapper.clientWidth}
  2714. }
  2715. // Computes display.scroller.scrollLeft + display.gutters.offsetWidth,
  2716. // but using getBoundingClientRect to get a sub-pixel-accurate
  2717. // result.
  2718. function compensateForHScroll(display) {
  2719. return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left
  2720. }
  2721. // Returns a function that estimates the height of a line, to use as
  2722. // first approximation until the line becomes visible (and is thus
  2723. // properly measurable).
  2724. function estimateHeight(cm) {
  2725. var th = textHeight(cm.display), wrapping = cm.options.lineWrapping;
  2726. var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3);
  2727. return function (line) {
  2728. if (lineIsHidden(cm.doc, line)) { return 0 }
  2729. var widgetsHeight = 0;
  2730. if (line.widgets) { for (var i = 0; i < line.widgets.length; i++) {
  2731. if (line.widgets[i].height) { widgetsHeight += line.widgets[i].height; }
  2732. } }
  2733. if (wrapping)
  2734. { return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th }
  2735. else
  2736. { return widgetsHeight + th }
  2737. }
  2738. }
  2739. function estimateLineHeights(cm) {
  2740. var doc = cm.doc, est = estimateHeight(cm);
  2741. doc.iter(function (line) {
  2742. var estHeight = est(line);
  2743. if (estHeight != line.height) { updateLineHeight(line, estHeight); }
  2744. });
  2745. }
  2746. // Given a mouse event, find the corresponding position. If liberal
  2747. // is false, it checks whether a gutter or scrollbar was clicked,
  2748. // and returns null if it was. forRect is used by rectangular
  2749. // selections, and tries to estimate a character position even for
  2750. // coordinates beyond the right of the text.
  2751. function posFromMouse(cm, e, liberal, forRect) {
  2752. var display = cm.display;
  2753. if (!liberal && e_target(e).getAttribute("cm-not-content") == "true") { return null }
  2754. var x, y, space = display.lineSpace.getBoundingClientRect();
  2755. // Fails unpredictably on IE[67] when mouse is dragged around quickly.
  2756. try { x = e.clientX - space.left; y = e.clientY - space.top; }
  2757. catch (e) { return null }
  2758. var coords = coordsChar(cm, x, y), line;
  2759. if (forRect && coords.xRel == 1 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) {
  2760. var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length;
  2761. coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff));
  2762. }
  2763. return coords
  2764. }
  2765. // Find the view element corresponding to a given line. Return null
  2766. // when the line isn't visible.
  2767. function findViewIndex(cm, n) {
  2768. if (n >= cm.display.viewTo) { return null }
  2769. n -= cm.display.viewFrom;
  2770. if (n < 0) { return null }
  2771. var view = cm.display.view;
  2772. for (var i = 0; i < view.length; i++) {
  2773. n -= view[i].size;
  2774. if (n < 0) { return i }
  2775. }
  2776. }
  2777. function updateSelection(cm) {
  2778. cm.display.input.showSelection(cm.display.input.prepareSelection());
  2779. }
  2780. function prepareSelection(cm, primary) {
  2781. if ( primary === void 0 ) primary = true;
  2782. var doc = cm.doc, result = {};
  2783. var curFragment = result.cursors = document.createDocumentFragment();
  2784. var selFragment = result.selection = document.createDocumentFragment();
  2785. for (var i = 0; i < doc.sel.ranges.length; i++) {
  2786. if (!primary && i == doc.sel.primIndex) { continue }
  2787. var range$$1 = doc.sel.ranges[i];
  2788. if (range$$1.from().line >= cm.display.viewTo || range$$1.to().line < cm.display.viewFrom) { continue }
  2789. var collapsed = range$$1.empty();
  2790. if (collapsed || cm.options.showCursorWhenSelecting)
  2791. { drawSelectionCursor(cm, range$$1.head, curFragment); }
  2792. if (!collapsed)
  2793. { drawSelectionRange(cm, range$$1, selFragment); }
  2794. }
  2795. return result
  2796. }
  2797. // Draws a cursor for the given range
  2798. function drawSelectionCursor(cm, head, output) {
  2799. var pos = cursorCoords(cm, head, "div", null, null, !cm.options.singleCursorHeightPerLine);
  2800. var cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor"));
  2801. cursor.style.left = pos.left + "px";
  2802. cursor.style.top = pos.top + "px";
  2803. cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px";
  2804. if (pos.other) {
  2805. // Secondary cursor, shown when on a 'jump' in bi-directional text
  2806. var otherCursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor"));
  2807. otherCursor.style.display = "";
  2808. otherCursor.style.left = pos.other.left + "px";
  2809. otherCursor.style.top = pos.other.top + "px";
  2810. otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px";
  2811. }
  2812. }
  2813. function cmpCoords(a, b) { return a.top - b.top || a.left - b.left }
  2814. // Draws the given range as a highlighted selection
  2815. function drawSelectionRange(cm, range$$1, output) {
  2816. var display = cm.display, doc = cm.doc;
  2817. var fragment = document.createDocumentFragment();
  2818. var padding = paddingH(cm.display), leftSide = padding.left;
  2819. var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right;
  2820. var docLTR = doc.direction == "ltr";
  2821. function add(left, top, width, bottom) {
  2822. if (top < 0) { top = 0; }
  2823. top = Math.round(top);
  2824. bottom = Math.round(bottom);
  2825. 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")));
  2826. }
  2827. function drawForLine(line, fromArg, toArg) {
  2828. var lineObj = getLine(doc, line);
  2829. var lineLen = lineObj.text.length;
  2830. var start, end;
  2831. function coords(ch, bias) {
  2832. return charCoords(cm, Pos(line, ch), "div", lineObj, bias)
  2833. }
  2834. function wrapX(pos, dir, side) {
  2835. var extent = wrappedLineExtentChar(cm, lineObj, null, pos);
  2836. var prop = (dir == "ltr") == (side == "after") ? "left" : "right";
  2837. var ch = side == "after" ? extent.begin : extent.end - (/\s/.test(lineObj.text.charAt(extent.end - 1)) ? 2 : 1);
  2838. return coords(ch, prop)[prop]
  2839. }
  2840. var order = getOrder(lineObj, doc.direction);
  2841. iterateBidiSections(order, fromArg || 0, toArg == null ? lineLen : toArg, function (from, to, dir, i) {
  2842. var ltr = dir == "ltr";
  2843. var fromPos = coords(from, ltr ? "left" : "right");
  2844. var toPos = coords(to - 1, ltr ? "right" : "left");
  2845. var openStart = fromArg == null && from == 0, openEnd = toArg == null && to == lineLen;
  2846. var first = i == 0, last = !order || i == order.length - 1;
  2847. if (toPos.top - fromPos.top <= 3) { // Single line
  2848. var openLeft = (docLTR ? openStart : openEnd) && first;
  2849. var openRight = (docLTR ? openEnd : openStart) && last;
  2850. var left = openLeft ? leftSide : (ltr ? fromPos : toPos).left;
  2851. var right = openRight ? rightSide : (ltr ? toPos : fromPos).right;
  2852. add(left, fromPos.top, right - left, fromPos.bottom);
  2853. } else { // Multiple lines
  2854. var topLeft, topRight, botLeft, botRight;
  2855. if (ltr) {
  2856. topLeft = docLTR && openStart && first ? leftSide : fromPos.left;
  2857. topRight = docLTR ? rightSide : wrapX(from, dir, "before");
  2858. botLeft = docLTR ? leftSide : wrapX(to, dir, "after");
  2859. botRight = docLTR && openEnd && last ? rightSide : toPos.right;
  2860. } else {
  2861. topLeft = !docLTR ? leftSide : wrapX(from, dir, "before");
  2862. topRight = !docLTR && openStart && first ? rightSide : fromPos.right;
  2863. botLeft = !docLTR && openEnd && last ? leftSide : toPos.left;
  2864. botRight = !docLTR ? rightSide : wrapX(to, dir, "after");
  2865. }
  2866. add(topLeft, fromPos.top, topRight - topLeft, fromPos.bottom);
  2867. if (fromPos.bottom < toPos.top) { add(leftSide, fromPos.bottom, null, toPos.top); }
  2868. add(botLeft, toPos.top, botRight - botLeft, toPos.bottom);
  2869. }
  2870. if (!start || cmpCoords(fromPos, start) < 0) { start = fromPos; }
  2871. if (cmpCoords(toPos, start) < 0) { start = toPos; }
  2872. if (!end || cmpCoords(fromPos, end) < 0) { end = fromPos; }
  2873. if (cmpCoords(toPos, end) < 0) { end = toPos; }
  2874. });
  2875. return {start: start, end: end}
  2876. }
  2877. var sFrom = range$$1.from(), sTo = range$$1.to();
  2878. if (sFrom.line == sTo.line) {
  2879. drawForLine(sFrom.line, sFrom.ch, sTo.ch);
  2880. } else {
  2881. var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line);
  2882. var singleVLine = visualLine(fromLine) == visualLine(toLine);
  2883. var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end;
  2884. var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start;
  2885. if (singleVLine) {
  2886. if (leftEnd.top < rightStart.top - 2) {
  2887. add(leftEnd.right, leftEnd.top, null, leftEnd.bottom);
  2888. add(leftSide, rightStart.top, rightStart.left, rightStart.bottom);
  2889. } else {
  2890. add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom);
  2891. }
  2892. }
  2893. if (leftEnd.bottom < rightStart.top)
  2894. { add(leftSide, leftEnd.bottom, null, rightStart.top); }
  2895. }
  2896. output.appendChild(fragment);
  2897. }
  2898. // Cursor-blinking
  2899. function restartBlink(cm) {
  2900. if (!cm.state.focused) { return }
  2901. var display = cm.display;
  2902. clearInterval(display.blinker);
  2903. var on = true;
  2904. display.cursorDiv.style.visibility = "";
  2905. if (cm.options.cursorBlinkRate > 0)
  2906. { display.blinker = setInterval(function () { return display.cursorDiv.style.visibility = (on = !on) ? "" : "hidden"; },
  2907. cm.options.cursorBlinkRate); }
  2908. else if (cm.options.cursorBlinkRate < 0)
  2909. { display.cursorDiv.style.visibility = "hidden"; }
  2910. }
  2911. function ensureFocus(cm) {
  2912. if (!cm.state.focused) { cm.display.input.focus(); onFocus(cm); }
  2913. }
  2914. function delayBlurEvent(cm) {
  2915. cm.state.delayingBlurEvent = true;
  2916. setTimeout(function () { if (cm.state.delayingBlurEvent) {
  2917. cm.state.delayingBlurEvent = false;
  2918. onBlur(cm);
  2919. } }, 100);
  2920. }
  2921. function onFocus(cm, e) {
  2922. if (cm.state.delayingBlurEvent) { cm.state.delayingBlurEvent = false; }
  2923. if (cm.options.readOnly == "nocursor") { return }
  2924. if (!cm.state.focused) {
  2925. signal(cm, "focus", cm, e);
  2926. cm.state.focused = true;
  2927. addClass(cm.display.wrapper, "CodeMirror-focused");
  2928. // This test prevents this from firing when a context
  2929. // menu is closed (since the input reset would kill the
  2930. // select-all detection hack)
  2931. if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) {
  2932. cm.display.input.reset();
  2933. if (webkit) { setTimeout(function () { return cm.display.input.reset(true); }, 20); } // Issue #1730
  2934. }
  2935. cm.display.input.receivedFocus();
  2936. }
  2937. restartBlink(cm);
  2938. }
  2939. function onBlur(cm, e) {
  2940. if (cm.state.delayingBlurEvent) { return }
  2941. if (cm.state.focused) {
  2942. signal(cm, "blur", cm, e);
  2943. cm.state.focused = false;
  2944. rmClass(cm.display.wrapper, "CodeMirror-focused");
  2945. }
  2946. clearInterval(cm.display.blinker);
  2947. setTimeout(function () { if (!cm.state.focused) { cm.display.shift = false; } }, 150);
  2948. }
  2949. // Read the actual heights of the rendered lines, and update their
  2950. // stored heights to match.
  2951. function updateHeightsInViewport(cm) {
  2952. var display = cm.display;
  2953. var prevBottom = display.lineDiv.offsetTop;
  2954. for (var i = 0; i < display.view.length; i++) {
  2955. var cur = display.view[i], height = (void 0);
  2956. if (cur.hidden) { continue }
  2957. if (ie && ie_version < 8) {
  2958. var bot = cur.node.offsetTop + cur.node.offsetHeight;
  2959. height = bot - prevBottom;
  2960. prevBottom = bot;
  2961. } else {
  2962. var box = cur.node.getBoundingClientRect();
  2963. height = box.bottom - box.top;
  2964. }
  2965. var diff = cur.line.height - height;
  2966. if (height < 2) { height = textHeight(display); }
  2967. if (diff > .005 || diff < -.005) {
  2968. updateLineHeight(cur.line, height);
  2969. updateWidgetHeight(cur.line);
  2970. if (cur.rest) { for (var j = 0; j < cur.rest.length; j++)
  2971. { updateWidgetHeight(cur.rest[j]); } }
  2972. }
  2973. }
  2974. }
  2975. // Read and store the height of line widgets associated with the
  2976. // given line.
  2977. function updateWidgetHeight(line) {
  2978. if (line.widgets) { for (var i = 0; i < line.widgets.length; ++i) {
  2979. var w = line.widgets[i], parent = w.node.parentNode;
  2980. if (parent) { w.height = parent.offsetHeight; }
  2981. } }
  2982. }
  2983. // Compute the lines that are visible in a given viewport (defaults
  2984. // the the current scroll position). viewport may contain top,
  2985. // height, and ensure (see op.scrollToPos) properties.
  2986. function visibleLines(display, doc, viewport) {
  2987. var top = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop;
  2988. top = Math.floor(top - paddingTop(display));
  2989. var bottom = viewport && viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight;
  2990. var from = lineAtHeight(doc, top), to = lineAtHeight(doc, bottom);
  2991. // Ensure is a {from: {line, ch}, to: {line, ch}} object, and
  2992. // forces those lines into the viewport (if possible).
  2993. if (viewport && viewport.ensure) {
  2994. var ensureFrom = viewport.ensure.from.line, ensureTo = viewport.ensure.to.line;
  2995. if (ensureFrom < from) {
  2996. from = ensureFrom;
  2997. to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight);
  2998. } else if (Math.min(ensureTo, doc.lastLine()) >= to) {
  2999. from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight);
  3000. to = ensureTo;
  3001. }
  3002. }
  3003. return {from: from, to: Math.max(to, from + 1)}
  3004. }
  3005. // Re-align line numbers and gutter marks to compensate for
  3006. // horizontal scrolling.
  3007. function alignHorizontally(cm) {
  3008. var display = cm.display, view = display.view;
  3009. if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) { return }
  3010. var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft;
  3011. var gutterW = display.gutters.offsetWidth, left = comp + "px";
  3012. for (var i = 0; i < view.length; i++) { if (!view[i].hidden) {
  3013. if (cm.options.fixedGutter) {
  3014. if (view[i].gutter)
  3015. { view[i].gutter.style.left = left; }
  3016. if (view[i].gutterBackground)
  3017. { view[i].gutterBackground.style.left = left; }
  3018. }
  3019. var align = view[i].alignable;
  3020. if (align) { for (var j = 0; j < align.length; j++)
  3021. { align[j].style.left = left; } }
  3022. } }
  3023. if (cm.options.fixedGutter)
  3024. { display.gutters.style.left = (comp + gutterW) + "px"; }
  3025. }
  3026. // Used to ensure that the line number gutter is still the right
  3027. // size for the current document size. Returns true when an update
  3028. // is needed.
  3029. function maybeUpdateLineNumberWidth(cm) {
  3030. if (!cm.options.lineNumbers) { return false }
  3031. var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display;
  3032. if (last.length != display.lineNumChars) {
  3033. var test = display.measure.appendChild(elt("div", [elt("div", last)],
  3034. "CodeMirror-linenumber CodeMirror-gutter-elt"));
  3035. var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW;
  3036. display.lineGutter.style.width = "";
  3037. display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding) + 1;
  3038. display.lineNumWidth = display.lineNumInnerWidth + padding;
  3039. display.lineNumChars = display.lineNumInnerWidth ? last.length : -1;
  3040. display.lineGutter.style.width = display.lineNumWidth + "px";
  3041. updateGutterSpace(cm);
  3042. return true
  3043. }
  3044. return false
  3045. }
  3046. // SCROLLING THINGS INTO VIEW
  3047. // If an editor sits on the top or bottom of the window, partially
  3048. // scrolled out of view, this ensures that the cursor is visible.
  3049. function maybeScrollWindow(cm, rect) {
  3050. if (signalDOMEvent(cm, "scrollCursorIntoView")) { return }
  3051. var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null;
  3052. if (rect.top + box.top < 0) { doScroll = true; }
  3053. else if (rect.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) { doScroll = false; }
  3054. if (doScroll != null && !phantom) {
  3055. 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;"));
  3056. cm.display.lineSpace.appendChild(scrollNode);
  3057. scrollNode.scrollIntoView(doScroll);
  3058. cm.display.lineSpace.removeChild(scrollNode);
  3059. }
  3060. }
  3061. // Scroll a given position into view (immediately), verifying that
  3062. // it actually became visible (as line heights are accurately
  3063. // measured, the position of something may 'drift' during drawing).
  3064. function scrollPosIntoView(cm, pos, end, margin) {
  3065. if (margin == null) { margin = 0; }
  3066. var rect;
  3067. if (!cm.options.lineWrapping && pos == end) {
  3068. // Set pos and end to the cursor positions around the character pos sticks to
  3069. // If pos.sticky == "before", that is around pos.ch - 1, otherwise around pos.ch
  3070. // If pos == Pos(_, 0, "before"), pos and end are unchanged
  3071. pos = pos.ch ? Pos(pos.line, pos.sticky == "before" ? pos.ch - 1 : pos.ch, "after") : pos;
  3072. end = pos.sticky == "before" ? Pos(pos.line, pos.ch + 1, "before") : pos;
  3073. }
  3074. for (var limit = 0; limit < 5; limit++) {
  3075. var changed = false;
  3076. var coords = cursorCoords(cm, pos);
  3077. var endCoords = !end || end == pos ? coords : cursorCoords(cm, end);
  3078. rect = {left: Math.min(coords.left, endCoords.left),
  3079. top: Math.min(coords.top, endCoords.top) - margin,
  3080. right: Math.max(coords.left, endCoords.left),
  3081. bottom: Math.max(coords.bottom, endCoords.bottom) + margin};
  3082. var scrollPos = calculateScrollPos(cm, rect);
  3083. var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft;
  3084. if (scrollPos.scrollTop != null) {
  3085. updateScrollTop(cm, scrollPos.scrollTop);
  3086. if (Math.abs(cm.doc.scrollTop - startTop) > 1) { changed = true; }
  3087. }
  3088. if (scrollPos.scrollLeft != null) {
  3089. setScrollLeft(cm, scrollPos.scrollLeft);
  3090. if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) { changed = true; }
  3091. }
  3092. if (!changed) { break }
  3093. }
  3094. return rect
  3095. }
  3096. // Scroll a given set of coordinates into view (immediately).
  3097. function scrollIntoView(cm, rect) {
  3098. var scrollPos = calculateScrollPos(cm, rect);
  3099. if (scrollPos.scrollTop != null) { updateScrollTop(cm, scrollPos.scrollTop); }
  3100. if (scrollPos.scrollLeft != null) { setScrollLeft(cm, scrollPos.scrollLeft); }
  3101. }
  3102. // Calculate a new scroll position needed to scroll the given
  3103. // rectangle into view. Returns an object with scrollTop and
  3104. // scrollLeft properties. When these are undefined, the
  3105. // vertical/horizontal position does not need to be adjusted.
  3106. function calculateScrollPos(cm, rect) {
  3107. var display = cm.display, snapMargin = textHeight(cm.display);
  3108. if (rect.top < 0) { rect.top = 0; }
  3109. var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop;
  3110. var screen = displayHeight(cm), result = {};
  3111. if (rect.bottom - rect.top > screen) { rect.bottom = rect.top + screen; }
  3112. var docBottom = cm.doc.height + paddingVert(display);
  3113. var atTop = rect.top < snapMargin, atBottom = rect.bottom > docBottom - snapMargin;
  3114. if (rect.top < screentop) {
  3115. result.scrollTop = atTop ? 0 : rect.top;
  3116. } else if (rect.bottom > screentop + screen) {
  3117. var newTop = Math.min(rect.top, (atBottom ? docBottom : rect.bottom) - screen);
  3118. if (newTop != screentop) { result.scrollTop = newTop; }
  3119. }
  3120. var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft;
  3121. var screenw = displayWidth(cm) - (cm.options.fixedGutter ? display.gutters.offsetWidth : 0);
  3122. var tooWide = rect.right - rect.left > screenw;
  3123. if (tooWide) { rect.right = rect.left + screenw; }
  3124. if (rect.left < 10)
  3125. { result.scrollLeft = 0; }
  3126. else if (rect.left < screenleft)
  3127. { result.scrollLeft = Math.max(0, rect.left - (tooWide ? 0 : 10)); }
  3128. else if (rect.right > screenw + screenleft - 3)
  3129. { result.scrollLeft = rect.right + (tooWide ? 0 : 10) - screenw; }
  3130. return result
  3131. }
  3132. // Store a relative adjustment to the scroll position in the current
  3133. // operation (to be applied when the operation finishes).
  3134. function addToScrollTop(cm, top) {
  3135. if (top == null) { return }
  3136. resolveScrollToPos(cm);
  3137. cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top;
  3138. }
  3139. // Make sure that at the end of the operation the current cursor is
  3140. // shown.
  3141. function ensureCursorVisible(cm) {
  3142. resolveScrollToPos(cm);
  3143. var cur = cm.getCursor();
  3144. cm.curOp.scrollToPos = {from: cur, to: cur, margin: cm.options.cursorScrollMargin};
  3145. }
  3146. function scrollToCoords(cm, x, y) {
  3147. if (x != null || y != null) { resolveScrollToPos(cm); }
  3148. if (x != null) { cm.curOp.scrollLeft = x; }
  3149. if (y != null) { cm.curOp.scrollTop = y; }
  3150. }
  3151. function scrollToRange(cm, range$$1) {
  3152. resolveScrollToPos(cm);
  3153. cm.curOp.scrollToPos = range$$1;
  3154. }
  3155. // When an operation has its scrollToPos property set, and another
  3156. // scroll action is applied before the end of the operation, this
  3157. // 'simulates' scrolling that position into view in a cheap way, so
  3158. // that the effect of intermediate scroll commands is not ignored.
  3159. function resolveScrollToPos(cm) {
  3160. var range$$1 = cm.curOp.scrollToPos;
  3161. if (range$$1) {
  3162. cm.curOp.scrollToPos = null;
  3163. var from = estimateCoords(cm, range$$1.from), to = estimateCoords(cm, range$$1.to);
  3164. scrollToCoordsRange(cm, from, to, range$$1.margin);
  3165. }
  3166. }
  3167. function scrollToCoordsRange(cm, from, to, margin) {
  3168. var sPos = calculateScrollPos(cm, {
  3169. left: Math.min(from.left, to.left),
  3170. top: Math.min(from.top, to.top) - margin,
  3171. right: Math.max(from.right, to.right),
  3172. bottom: Math.max(from.bottom, to.bottom) + margin
  3173. });
  3174. scrollToCoords(cm, sPos.scrollLeft, sPos.scrollTop);
  3175. }
  3176. // Sync the scrollable area and scrollbars, ensure the viewport
  3177. // covers the visible area.
  3178. function updateScrollTop(cm, val) {
  3179. if (Math.abs(cm.doc.scrollTop - val) < 2) { return }
  3180. if (!gecko) { updateDisplaySimple(cm, {top: val}); }
  3181. setScrollTop(cm, val, true);
  3182. if (gecko) { updateDisplaySimple(cm); }
  3183. startWorker(cm, 100);
  3184. }
  3185. function setScrollTop(cm, val, forceScroll) {
  3186. val = Math.min(cm.display.scroller.scrollHeight - cm.display.scroller.clientHeight, val);
  3187. if (cm.display.scroller.scrollTop == val && !forceScroll) { return }
  3188. cm.doc.scrollTop = val;
  3189. cm.display.scrollbars.setScrollTop(val);
  3190. if (cm.display.scroller.scrollTop != val) { cm.display.scroller.scrollTop = val; }
  3191. }
  3192. // Sync scroller and scrollbar, ensure the gutter elements are
  3193. // aligned.
  3194. function setScrollLeft(cm, val, isScroller, forceScroll) {
  3195. val = Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth);
  3196. if ((isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) && !forceScroll) { return }
  3197. cm.doc.scrollLeft = val;
  3198. alignHorizontally(cm);
  3199. if (cm.display.scroller.scrollLeft != val) { cm.display.scroller.scrollLeft = val; }
  3200. cm.display.scrollbars.setScrollLeft(val);
  3201. }
  3202. // SCROLLBARS
  3203. // Prepare DOM reads needed to update the scrollbars. Done in one
  3204. // shot to minimize update/measure roundtrips.
  3205. function measureForScrollbars(cm) {
  3206. var d = cm.display, gutterW = d.gutters.offsetWidth;
  3207. var docH = Math.round(cm.doc.height + paddingVert(cm.display));
  3208. return {
  3209. clientHeight: d.scroller.clientHeight,
  3210. viewHeight: d.wrapper.clientHeight,
  3211. scrollWidth: d.scroller.scrollWidth, clientWidth: d.scroller.clientWidth,
  3212. viewWidth: d.wrapper.clientWidth,
  3213. barLeft: cm.options.fixedGutter ? gutterW : 0,
  3214. docHeight: docH,
  3215. scrollHeight: docH + scrollGap(cm) + d.barHeight,
  3216. nativeBarWidth: d.nativeBarWidth,
  3217. gutterWidth: gutterW
  3218. }
  3219. }
  3220. var NativeScrollbars = function(place, scroll, cm) {
  3221. this.cm = cm;
  3222. var vert = this.vert = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar");
  3223. var horiz = this.horiz = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar");
  3224. place(vert); place(horiz);
  3225. on(vert, "scroll", function () {
  3226. if (vert.clientHeight) { scroll(vert.scrollTop, "vertical"); }
  3227. });
  3228. on(horiz, "scroll", function () {
  3229. if (horiz.clientWidth) { scroll(horiz.scrollLeft, "horizontal"); }
  3230. });
  3231. this.checkedZeroWidth = false;
  3232. // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8).
  3233. if (ie && ie_version < 8) { this.horiz.style.minHeight = this.vert.style.minWidth = "18px"; }
  3234. };
  3235. NativeScrollbars.prototype.update = function (measure) {
  3236. var needsH = measure.scrollWidth > measure.clientWidth + 1;
  3237. var needsV = measure.scrollHeight > measure.clientHeight + 1;
  3238. var sWidth = measure.nativeBarWidth;
  3239. if (needsV) {
  3240. this.vert.style.display = "block";
  3241. this.vert.style.bottom = needsH ? sWidth + "px" : "0";
  3242. var totalHeight = measure.viewHeight - (needsH ? sWidth : 0);
  3243. // A bug in IE8 can cause this value to be negative, so guard it.
  3244. this.vert.firstChild.style.height =
  3245. Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + "px";
  3246. } else {
  3247. this.vert.style.display = "";
  3248. this.vert.firstChild.style.height = "0";
  3249. }
  3250. if (needsH) {
  3251. this.horiz.style.display = "block";
  3252. this.horiz.style.right = needsV ? sWidth + "px" : "0";
  3253. this.horiz.style.left = measure.barLeft + "px";
  3254. var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0);
  3255. this.horiz.firstChild.style.width =
  3256. Math.max(0, measure.scrollWidth - measure.clientWidth + totalWidth) + "px";
  3257. } else {
  3258. this.horiz.style.display = "";
  3259. this.horiz.firstChild.style.width = "0";
  3260. }
  3261. if (!this.checkedZeroWidth && measure.clientHeight > 0) {
  3262. if (sWidth == 0) { this.zeroWidthHack(); }
  3263. this.checkedZeroWidth = true;
  3264. }
  3265. return {right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0}
  3266. };
  3267. NativeScrollbars.prototype.setScrollLeft = function (pos) {
  3268. if (this.horiz.scrollLeft != pos) { this.horiz.scrollLeft = pos; }
  3269. if (this.disableHoriz) { this.enableZeroWidthBar(this.horiz, this.disableHoriz, "horiz"); }
  3270. };
  3271. NativeScrollbars.prototype.setScrollTop = function (pos) {
  3272. if (this.vert.scrollTop != pos) { this.vert.scrollTop = pos; }
  3273. if (this.disableVert) { this.enableZeroWidthBar(this.vert, this.disableVert, "vert"); }
  3274. };
  3275. NativeScrollbars.prototype.zeroWidthHack = function () {
  3276. var w = mac && !mac_geMountainLion ? "12px" : "18px";
  3277. this.horiz.style.height = this.vert.style.width = w;
  3278. this.horiz.style.pointerEvents = this.vert.style.pointerEvents = "none";
  3279. this.disableHoriz = new Delayed;
  3280. this.disableVert = new Delayed;
  3281. };
  3282. NativeScrollbars.prototype.enableZeroWidthBar = function (bar, delay, type) {
  3283. bar.style.pointerEvents = "auto";
  3284. function maybeDisable() {
  3285. // To find out whether the scrollbar is still visible, we
  3286. // check whether the element under the pixel in the bottom
  3287. // right corner of the scrollbar box is the scrollbar box
  3288. // itself (when the bar is still visible) or its filler child
  3289. // (when the bar is hidden). If it is still visible, we keep
  3290. // it enabled, if it's hidden, we disable pointer events.
  3291. var box = bar.getBoundingClientRect();
  3292. var elt$$1 = type == "vert" ? document.elementFromPoint(box.right - 1, (box.top + box.bottom) / 2)
  3293. : document.elementFromPoint((box.right + box.left) / 2, box.bottom - 1);
  3294. if (elt$$1 != bar) { bar.style.pointerEvents = "none"; }
  3295. else { delay.set(1000, maybeDisable); }
  3296. }
  3297. delay.set(1000, maybeDisable);
  3298. };
  3299. NativeScrollbars.prototype.clear = function () {
  3300. var parent = this.horiz.parentNode;
  3301. parent.removeChild(this.horiz);
  3302. parent.removeChild(this.vert);
  3303. };
  3304. var NullScrollbars = function () {};
  3305. NullScrollbars.prototype.update = function () { return {bottom: 0, right: 0} };
  3306. NullScrollbars.prototype.setScrollLeft = function () {};
  3307. NullScrollbars.prototype.setScrollTop = function () {};
  3308. NullScrollbars.prototype.clear = function () {};
  3309. function updateScrollbars(cm, measure) {
  3310. if (!measure) { measure = measureForScrollbars(cm); }
  3311. var startWidth = cm.display.barWidth, startHeight = cm.display.barHeight;
  3312. updateScrollbarsInner(cm, measure);
  3313. for (var i = 0; i < 4 && startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i++) {
  3314. if (startWidth != cm.display.barWidth && cm.options.lineWrapping)
  3315. { updateHeightsInViewport(cm); }
  3316. updateScrollbarsInner(cm, measureForScrollbars(cm));
  3317. startWidth = cm.display.barWidth; startHeight = cm.display.barHeight;
  3318. }
  3319. }
  3320. // Re-synchronize the fake scrollbars with the actual size of the
  3321. // content.
  3322. function updateScrollbarsInner(cm, measure) {
  3323. var d = cm.display;
  3324. var sizes = d.scrollbars.update(measure);
  3325. d.sizer.style.paddingRight = (d.barWidth = sizes.right) + "px";
  3326. d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + "px";
  3327. d.heightForcer.style.borderBottom = sizes.bottom + "px solid transparent";
  3328. if (sizes.right && sizes.bottom) {
  3329. d.scrollbarFiller.style.display = "block";
  3330. d.scrollbarFiller.style.height = sizes.bottom + "px";
  3331. d.scrollbarFiller.style.width = sizes.right + "px";
  3332. } else { d.scrollbarFiller.style.display = ""; }
  3333. if (sizes.bottom && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) {
  3334. d.gutterFiller.style.display = "block";
  3335. d.gutterFiller.style.height = sizes.bottom + "px";
  3336. d.gutterFiller.style.width = measure.gutterWidth + "px";
  3337. } else { d.gutterFiller.style.display = ""; }
  3338. }
  3339. var scrollbarModel = {"native": NativeScrollbars, "null": NullScrollbars};
  3340. function initScrollbars(cm) {
  3341. if (cm.display.scrollbars) {
  3342. cm.display.scrollbars.clear();
  3343. if (cm.display.scrollbars.addClass)
  3344. { rmClass(cm.display.wrapper, cm.display.scrollbars.addClass); }
  3345. }
  3346. cm.display.scrollbars = new scrollbarModel[cm.options.scrollbarStyle](function (node) {
  3347. cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller);
  3348. // Prevent clicks in the scrollbars from killing focus
  3349. on(node, "mousedown", function () {
  3350. if (cm.state.focused) { setTimeout(function () { return cm.display.input.focus(); }, 0); }
  3351. });
  3352. node.setAttribute("cm-not-content", "true");
  3353. }, function (pos, axis) {
  3354. if (axis == "horizontal") { setScrollLeft(cm, pos); }
  3355. else { updateScrollTop(cm, pos); }
  3356. }, cm);
  3357. if (cm.display.scrollbars.addClass)
  3358. { addClass(cm.display.wrapper, cm.display.scrollbars.addClass); }
  3359. }
  3360. // Operations are used to wrap a series of changes to the editor
  3361. // state in such a way that each change won't have to update the
  3362. // cursor and display (which would be awkward, slow, and
  3363. // error-prone). Instead, display updates are batched and then all
  3364. // combined and executed at once.
  3365. var nextOpId = 0;
  3366. // Start a new operation.
  3367. function startOperation(cm) {
  3368. cm.curOp = {
  3369. cm: cm,
  3370. viewChanged: false, // Flag that indicates that lines might need to be redrawn
  3371. startHeight: cm.doc.height, // Used to detect need to update scrollbar
  3372. forceUpdate: false, // Used to force a redraw
  3373. updateInput: null, // Whether to reset the input textarea
  3374. typing: false, // Whether this reset should be careful to leave existing text (for compositing)
  3375. changeObjs: null, // Accumulated changes, for firing change events
  3376. cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on
  3377. cursorActivityCalled: 0, // Tracks which cursorActivity handlers have been called already
  3378. selectionChanged: false, // Whether the selection needs to be redrawn
  3379. updateMaxLine: false, // Set when the widest line needs to be determined anew
  3380. scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet
  3381. scrollToPos: null, // Used to scroll to a specific position
  3382. focus: false,
  3383. id: ++nextOpId // Unique ID
  3384. };
  3385. pushOperation(cm.curOp);
  3386. }
  3387. // Finish an operation, updating the display and signalling delayed events
  3388. function endOperation(cm) {
  3389. var op = cm.curOp;
  3390. finishOperation(op, function (group) {
  3391. for (var i = 0; i < group.ops.length; i++)
  3392. { group.ops[i].cm.curOp = null; }
  3393. endOperations(group);
  3394. });
  3395. }
  3396. // The DOM updates done when an operation finishes are batched so
  3397. // that the minimum number of relayouts are required.
  3398. function endOperations(group) {
  3399. var ops = group.ops;
  3400. for (var i = 0; i < ops.length; i++) // Read DOM
  3401. { endOperation_R1(ops[i]); }
  3402. for (var i$1 = 0; i$1 < ops.length; i$1++) // Write DOM (maybe)
  3403. { endOperation_W1(ops[i$1]); }
  3404. for (var i$2 = 0; i$2 < ops.length; i$2++) // Read DOM
  3405. { endOperation_R2(ops[i$2]); }
  3406. for (var i$3 = 0; i$3 < ops.length; i$3++) // Write DOM (maybe)
  3407. { endOperation_W2(ops[i$3]); }
  3408. for (var i$4 = 0; i$4 < ops.length; i$4++) // Read DOM
  3409. { endOperation_finish(ops[i$4]); }
  3410. }
  3411. function endOperation_R1(op) {
  3412. var cm = op.cm, display = cm.display;
  3413. maybeClipScrollbars(cm);
  3414. if (op.updateMaxLine) { findMaxLine(cm); }
  3415. op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null ||
  3416. op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom ||
  3417. op.scrollToPos.to.line >= display.viewTo) ||
  3418. display.maxLineChanged && cm.options.lineWrapping;
  3419. op.update = op.mustUpdate &&
  3420. new DisplayUpdate(cm, op.mustUpdate && {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate);
  3421. }
  3422. function endOperation_W1(op) {
  3423. op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update);
  3424. }
  3425. function endOperation_R2(op) {
  3426. var cm = op.cm, display = cm.display;
  3427. if (op.updatedDisplay) { updateHeightsInViewport(cm); }
  3428. op.barMeasure = measureForScrollbars(cm);
  3429. // If the max line changed since it was last measured, measure it,
  3430. // and ensure the document's width matches it.
  3431. // updateDisplay_W2 will use these properties to do the actual resizing
  3432. if (display.maxLineChanged && !cm.options.lineWrapping) {
  3433. op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3;
  3434. cm.display.sizerWidth = op.adjustWidthTo;
  3435. op.barMeasure.scrollWidth =
  3436. Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth);
  3437. op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm));
  3438. }
  3439. if (op.updatedDisplay || op.selectionChanged)
  3440. { op.preparedSelection = display.input.prepareSelection(); }
  3441. }
  3442. function endOperation_W2(op) {
  3443. var cm = op.cm;
  3444. if (op.adjustWidthTo != null) {
  3445. cm.display.sizer.style.minWidth = op.adjustWidthTo + "px";
  3446. if (op.maxScrollLeft < cm.doc.scrollLeft)
  3447. { setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true); }
  3448. cm.display.maxLineChanged = false;
  3449. }
  3450. var takeFocus = op.focus && op.focus == activeElt();
  3451. if (op.preparedSelection)
  3452. { cm.display.input.showSelection(op.preparedSelection, takeFocus); }
  3453. if (op.updatedDisplay || op.startHeight != cm.doc.height)
  3454. { updateScrollbars(cm, op.barMeasure); }
  3455. if (op.updatedDisplay)
  3456. { setDocumentHeight(cm, op.barMeasure); }
  3457. if (op.selectionChanged) { restartBlink(cm); }
  3458. if (cm.state.focused && op.updateInput)
  3459. { cm.display.input.reset(op.typing); }
  3460. if (takeFocus) { ensureFocus(op.cm); }
  3461. }
  3462. function endOperation_finish(op) {
  3463. var cm = op.cm, display = cm.display, doc = cm.doc;
  3464. if (op.updatedDisplay) { postUpdateDisplay(cm, op.update); }
  3465. // Abort mouse wheel delta measurement, when scrolling explicitly
  3466. if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos))
  3467. { display.wheelStartX = display.wheelStartY = null; }
  3468. // Propagate the scroll position to the actual DOM scroller
  3469. if (op.scrollTop != null) { setScrollTop(cm, op.scrollTop, op.forceScroll); }
  3470. if (op.scrollLeft != null) { setScrollLeft(cm, op.scrollLeft, true, true); }
  3471. // If we need to scroll a specific position into view, do so.
  3472. if (op.scrollToPos) {
  3473. var rect = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from),
  3474. clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin);
  3475. maybeScrollWindow(cm, rect);
  3476. }
  3477. // Fire events for markers that are hidden/unidden by editing or
  3478. // undoing
  3479. var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers;
  3480. if (hidden) { for (var i = 0; i < hidden.length; ++i)
  3481. { if (!hidden[i].lines.length) { signal(hidden[i], "hide"); } } }
  3482. if (unhidden) { for (var i$1 = 0; i$1 < unhidden.length; ++i$1)
  3483. { if (unhidden[i$1].lines.length) { signal(unhidden[i$1], "unhide"); } } }
  3484. if (display.wrapper.offsetHeight)
  3485. { doc.scrollTop = cm.display.scroller.scrollTop; }
  3486. // Fire change events, and delayed event handlers
  3487. if (op.changeObjs)
  3488. { signal(cm, "changes", cm, op.changeObjs); }
  3489. if (op.update)
  3490. { op.update.finish(); }
  3491. }
  3492. // Run the given function in an operation
  3493. function runInOp(cm, f) {
  3494. if (cm.curOp) { return f() }
  3495. startOperation(cm);
  3496. try { return f() }
  3497. finally { endOperation(cm); }
  3498. }
  3499. // Wraps a function in an operation. Returns the wrapped function.
  3500. function operation(cm, f) {
  3501. return function() {
  3502. if (cm.curOp) { return f.apply(cm, arguments) }
  3503. startOperation(cm);
  3504. try { return f.apply(cm, arguments) }
  3505. finally { endOperation(cm); }
  3506. }
  3507. }
  3508. // Used to add methods to editor and doc instances, wrapping them in
  3509. // operations.
  3510. function methodOp(f) {
  3511. return function() {
  3512. if (this.curOp) { return f.apply(this, arguments) }
  3513. startOperation(this);
  3514. try { return f.apply(this, arguments) }
  3515. finally { endOperation(this); }
  3516. }
  3517. }
  3518. function docMethodOp(f) {
  3519. return function() {
  3520. var cm = this.cm;
  3521. if (!cm || cm.curOp) { return f.apply(this, arguments) }
  3522. startOperation(cm);
  3523. try { return f.apply(this, arguments) }
  3524. finally { endOperation(cm); }
  3525. }
  3526. }
  3527. // Updates the display.view data structure for a given change to the
  3528. // document. From and to are in pre-change coordinates. Lendiff is
  3529. // the amount of lines added or subtracted by the change. This is
  3530. // used for changes that span multiple lines, or change the way
  3531. // lines are divided into visual lines. regLineChange (below)
  3532. // registers single-line changes.
  3533. function regChange(cm, from, to, lendiff) {
  3534. if (from == null) { from = cm.doc.first; }
  3535. if (to == null) { to = cm.doc.first + cm.doc.size; }
  3536. if (!lendiff) { lendiff = 0; }
  3537. var display = cm.display;
  3538. if (lendiff && to < display.viewTo &&
  3539. (display.updateLineNumbers == null || display.updateLineNumbers > from))
  3540. { display.updateLineNumbers = from; }
  3541. cm.curOp.viewChanged = true;
  3542. if (from >= display.viewTo) { // Change after
  3543. if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo)
  3544. { resetView(cm); }
  3545. } else if (to <= display.viewFrom) { // Change before
  3546. if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) {
  3547. resetView(cm);
  3548. } else {
  3549. display.viewFrom += lendiff;
  3550. display.viewTo += lendiff;
  3551. }
  3552. } else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap
  3553. resetView(cm);
  3554. } else if (from <= display.viewFrom) { // Top overlap
  3555. var cut = viewCuttingPoint(cm, to, to + lendiff, 1);
  3556. if (cut) {
  3557. display.view = display.view.slice(cut.index);
  3558. display.viewFrom = cut.lineN;
  3559. display.viewTo += lendiff;
  3560. } else {
  3561. resetView(cm);
  3562. }
  3563. } else if (to >= display.viewTo) { // Bottom overlap
  3564. var cut$1 = viewCuttingPoint(cm, from, from, -1);
  3565. if (cut$1) {
  3566. display.view = display.view.slice(0, cut$1.index);
  3567. display.viewTo = cut$1.lineN;
  3568. } else {
  3569. resetView(cm);
  3570. }
  3571. } else { // Gap in the middle
  3572. var cutTop = viewCuttingPoint(cm, from, from, -1);
  3573. var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1);
  3574. if (cutTop && cutBot) {
  3575. display.view = display.view.slice(0, cutTop.index)
  3576. .concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN))
  3577. .concat(display.view.slice(cutBot.index));
  3578. display.viewTo += lendiff;
  3579. } else {
  3580. resetView(cm);
  3581. }
  3582. }
  3583. var ext = display.externalMeasured;
  3584. if (ext) {
  3585. if (to < ext.lineN)
  3586. { ext.lineN += lendiff; }
  3587. else if (from < ext.lineN + ext.size)
  3588. { display.externalMeasured = null; }
  3589. }
  3590. }
  3591. // Register a change to a single line. Type must be one of "text",
  3592. // "gutter", "class", "widget"
  3593. function regLineChange(cm, line, type) {
  3594. cm.curOp.viewChanged = true;
  3595. var display = cm.display, ext = cm.display.externalMeasured;
  3596. if (ext && line >= ext.lineN && line < ext.lineN + ext.size)
  3597. { display.externalMeasured = null; }
  3598. if (line < display.viewFrom || line >= display.viewTo) { return }
  3599. var lineView = display.view[findViewIndex(cm, line)];
  3600. if (lineView.node == null) { return }
  3601. var arr = lineView.changes || (lineView.changes = []);
  3602. if (indexOf(arr, type) == -1) { arr.push(type); }
  3603. }
  3604. // Clear the view.
  3605. function resetView(cm) {
  3606. cm.display.viewFrom = cm.display.viewTo = cm.doc.first;
  3607. cm.display.view = [];
  3608. cm.display.viewOffset = 0;
  3609. }
  3610. function viewCuttingPoint(cm, oldN, newN, dir) {
  3611. var index = findViewIndex(cm, oldN), diff, view = cm.display.view;
  3612. if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size)
  3613. { return {index: index, lineN: newN} }
  3614. var n = cm.display.viewFrom;
  3615. for (var i = 0; i < index; i++)
  3616. { n += view[i].size; }
  3617. if (n != oldN) {
  3618. if (dir > 0) {
  3619. if (index == view.length - 1) { return null }
  3620. diff = (n + view[index].size) - oldN;
  3621. index++;
  3622. } else {
  3623. diff = n - oldN;
  3624. }
  3625. oldN += diff; newN += diff;
  3626. }
  3627. while (visualLineNo(cm.doc, newN) != newN) {
  3628. if (index == (dir < 0 ? 0 : view.length - 1)) { return null }
  3629. newN += dir * view[index - (dir < 0 ? 1 : 0)].size;
  3630. index += dir;
  3631. }
  3632. return {index: index, lineN: newN}
  3633. }
  3634. // Force the view to cover a given range, adding empty view element
  3635. // or clipping off existing ones as needed.
  3636. function adjustView(cm, from, to) {
  3637. var display = cm.display, view = display.view;
  3638. if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) {
  3639. display.view = buildViewArray(cm, from, to);
  3640. display.viewFrom = from;
  3641. } else {
  3642. if (display.viewFrom > from)
  3643. { display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view); }
  3644. else if (display.viewFrom < from)
  3645. { display.view = display.view.slice(findViewIndex(cm, from)); }
  3646. display.viewFrom = from;
  3647. if (display.viewTo < to)
  3648. { display.view = display.view.concat(buildViewArray(cm, display.viewTo, to)); }
  3649. else if (display.viewTo > to)
  3650. { display.view = display.view.slice(0, findViewIndex(cm, to)); }
  3651. }
  3652. display.viewTo = to;
  3653. }
  3654. // Count the number of lines in the view whose DOM representation is
  3655. // out of date (or nonexistent).
  3656. function countDirtyView(cm) {
  3657. var view = cm.display.view, dirty = 0;
  3658. for (var i = 0; i < view.length; i++) {
  3659. var lineView = view[i];
  3660. if (!lineView.hidden && (!lineView.node || lineView.changes)) { ++dirty; }
  3661. }
  3662. return dirty
  3663. }
  3664. // HIGHLIGHT WORKER
  3665. function startWorker(cm, time) {
  3666. if (cm.doc.highlightFrontier < cm.display.viewTo)
  3667. { cm.state.highlight.set(time, bind(highlightWorker, cm)); }
  3668. }
  3669. function highlightWorker(cm) {
  3670. var doc = cm.doc;
  3671. if (doc.highlightFrontier >= cm.display.viewTo) { return }
  3672. var end = +new Date + cm.options.workTime;
  3673. var context = getContextBefore(cm, doc.highlightFrontier);
  3674. var changedLines = [];
  3675. doc.iter(context.line, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function (line) {
  3676. if (context.line >= cm.display.viewFrom) { // Visible
  3677. var oldStyles = line.styles;
  3678. var resetState = line.text.length > cm.options.maxHighlightLength ? copyState(doc.mode, context.state) : null;
  3679. var highlighted = highlightLine(cm, line, context, true);
  3680. if (resetState) { context.state = resetState; }
  3681. line.styles = highlighted.styles;
  3682. var oldCls = line.styleClasses, newCls = highlighted.classes;
  3683. if (newCls) { line.styleClasses = newCls; }
  3684. else if (oldCls) { line.styleClasses = null; }
  3685. var ischange = !oldStyles || oldStyles.length != line.styles.length ||
  3686. oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass);
  3687. for (var i = 0; !ischange && i < oldStyles.length; ++i) { ischange = oldStyles[i] != line.styles[i]; }
  3688. if (ischange) { changedLines.push(context.line); }
  3689. line.stateAfter = context.save();
  3690. context.nextLine();
  3691. } else {
  3692. if (line.text.length <= cm.options.maxHighlightLength)
  3693. { processLine(cm, line.text, context); }
  3694. line.stateAfter = context.line % 5 == 0 ? context.save() : null;
  3695. context.nextLine();
  3696. }
  3697. if (+new Date > end) {
  3698. startWorker(cm, cm.options.workDelay);
  3699. return true
  3700. }
  3701. });
  3702. doc.highlightFrontier = context.line;
  3703. doc.modeFrontier = Math.max(doc.modeFrontier, context.line);
  3704. if (changedLines.length) { runInOp(cm, function () {
  3705. for (var i = 0; i < changedLines.length; i++)
  3706. { regLineChange(cm, changedLines[i], "text"); }
  3707. }); }
  3708. }
  3709. // DISPLAY DRAWING
  3710. var DisplayUpdate = function(cm, viewport, force) {
  3711. var display = cm.display;
  3712. this.viewport = viewport;
  3713. // Store some values that we'll need later (but don't want to force a relayout for)
  3714. this.visible = visibleLines(display, cm.doc, viewport);
  3715. this.editorIsHidden = !display.wrapper.offsetWidth;
  3716. this.wrapperHeight = display.wrapper.clientHeight;
  3717. this.wrapperWidth = display.wrapper.clientWidth;
  3718. this.oldDisplayWidth = displayWidth(cm);
  3719. this.force = force;
  3720. this.dims = getDimensions(cm);
  3721. this.events = [];
  3722. };
  3723. DisplayUpdate.prototype.signal = function (emitter, type) {
  3724. if (hasHandler(emitter, type))
  3725. { this.events.push(arguments); }
  3726. };
  3727. DisplayUpdate.prototype.finish = function () {
  3728. var this$1 = this;
  3729. for (var i = 0; i < this.events.length; i++)
  3730. { signal.apply(null, this$1.events[i]); }
  3731. };
  3732. function maybeClipScrollbars(cm) {
  3733. var display = cm.display;
  3734. if (!display.scrollbarsClipped && display.scroller.offsetWidth) {
  3735. display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth;
  3736. display.heightForcer.style.height = scrollGap(cm) + "px";
  3737. display.sizer.style.marginBottom = -display.nativeBarWidth + "px";
  3738. display.sizer.style.borderRightWidth = scrollGap(cm) + "px";
  3739. display.scrollbarsClipped = true;
  3740. }
  3741. }
  3742. function selectionSnapshot(cm) {
  3743. if (cm.hasFocus()) { return null }
  3744. var active = activeElt();
  3745. if (!active || !contains(cm.display.lineDiv, active)) { return null }
  3746. var result = {activeElt: active};
  3747. if (window.getSelection) {
  3748. var sel = window.getSelection();
  3749. if (sel.anchorNode && sel.extend && contains(cm.display.lineDiv, sel.anchorNode)) {
  3750. result.anchorNode = sel.anchorNode;
  3751. result.anchorOffset = sel.anchorOffset;
  3752. result.focusNode = sel.focusNode;
  3753. result.focusOffset = sel.focusOffset;
  3754. }
  3755. }
  3756. return result
  3757. }
  3758. function restoreSelection(snapshot) {
  3759. if (!snapshot || !snapshot.activeElt || snapshot.activeElt == activeElt()) { return }
  3760. snapshot.activeElt.focus();
  3761. if (snapshot.anchorNode && contains(document.body, snapshot.anchorNode) && contains(document.body, snapshot.focusNode)) {
  3762. var sel = window.getSelection(), range$$1 = document.createRange();
  3763. range$$1.setEnd(snapshot.anchorNode, snapshot.anchorOffset);
  3764. range$$1.collapse(false);
  3765. sel.removeAllRanges();
  3766. sel.addRange(range$$1);
  3767. sel.extend(snapshot.focusNode, snapshot.focusOffset);
  3768. }
  3769. }
  3770. // Does the actual updating of the line display. Bails out
  3771. // (returning false) when there is nothing to be done and forced is
  3772. // false.
  3773. function updateDisplayIfNeeded(cm, update) {
  3774. var display = cm.display, doc = cm.doc;
  3775. if (update.editorIsHidden) {
  3776. resetView(cm);
  3777. return false
  3778. }
  3779. // Bail out if the visible area is already rendered and nothing changed.
  3780. if (!update.force &&
  3781. update.visible.from >= display.viewFrom && update.visible.to <= display.viewTo &&
  3782. (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) &&
  3783. display.renderedView == display.view && countDirtyView(cm) == 0)
  3784. { return false }
  3785. if (maybeUpdateLineNumberWidth(cm)) {
  3786. resetView(cm);
  3787. update.dims = getDimensions(cm);
  3788. }
  3789. // Compute a suitable new viewport (from & to)
  3790. var end = doc.first + doc.size;
  3791. var from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first);
  3792. var to = Math.min(end, update.visible.to + cm.options.viewportMargin);
  3793. if (display.viewFrom < from && from - display.viewFrom < 20) { from = Math.max(doc.first, display.viewFrom); }
  3794. if (display.viewTo > to && display.viewTo - to < 20) { to = Math.min(end, display.viewTo); }
  3795. if (sawCollapsedSpans) {
  3796. from = visualLineNo(cm.doc, from);
  3797. to = visualLineEndNo(cm.doc, to);
  3798. }
  3799. var different = from != display.viewFrom || to != display.viewTo ||
  3800. display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth;
  3801. adjustView(cm, from, to);
  3802. display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom));
  3803. // Position the mover div to align with the current scroll position
  3804. cm.display.mover.style.top = display.viewOffset + "px";
  3805. var toUpdate = countDirtyView(cm);
  3806. if (!different && toUpdate == 0 && !update.force && display.renderedView == display.view &&
  3807. (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo))
  3808. { return false }
  3809. // For big changes, we hide the enclosing element during the
  3810. // update, since that speeds up the operations on most browsers.
  3811. var selSnapshot = selectionSnapshot(cm);
  3812. if (toUpdate > 4) { display.lineDiv.style.display = "none"; }
  3813. patchDisplay(cm, display.updateLineNumbers, update.dims);
  3814. if (toUpdate > 4) { display.lineDiv.style.display = ""; }
  3815. display.renderedView = display.view;
  3816. // There might have been a widget with a focused element that got
  3817. // hidden or updated, if so re-focus it.
  3818. restoreSelection(selSnapshot);
  3819. // Prevent selection and cursors from interfering with the scroll
  3820. // width and height.
  3821. removeChildren(display.cursorDiv);
  3822. removeChildren(display.selectionDiv);
  3823. display.gutters.style.height = display.sizer.style.minHeight = 0;
  3824. if (different) {
  3825. display.lastWrapHeight = update.wrapperHeight;
  3826. display.lastWrapWidth = update.wrapperWidth;
  3827. startWorker(cm, 400);
  3828. }
  3829. display.updateLineNumbers = null;
  3830. return true
  3831. }
  3832. function postUpdateDisplay(cm, update) {
  3833. var viewport = update.viewport;
  3834. for (var first = true;; first = false) {
  3835. if (!first || !cm.options.lineWrapping || update.oldDisplayWidth == displayWidth(cm)) {
  3836. // Clip forced viewport to actual scrollable area.
  3837. if (viewport && viewport.top != null)
  3838. { viewport = {top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top)}; }
  3839. // Updated line heights might result in the drawn area not
  3840. // actually covering the viewport. Keep looping until it does.
  3841. update.visible = visibleLines(cm.display, cm.doc, viewport);
  3842. if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo)
  3843. { break }
  3844. }
  3845. if (!updateDisplayIfNeeded(cm, update)) { break }
  3846. updateHeightsInViewport(cm);
  3847. var barMeasure = measureForScrollbars(cm);
  3848. updateSelection(cm);
  3849. updateScrollbars(cm, barMeasure);
  3850. setDocumentHeight(cm, barMeasure);
  3851. update.force = false;
  3852. }
  3853. update.signal(cm, "update", cm);
  3854. if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) {
  3855. update.signal(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo);
  3856. cm.display.reportedViewFrom = cm.display.viewFrom; cm.display.reportedViewTo = cm.display.viewTo;
  3857. }
  3858. }
  3859. function updateDisplaySimple(cm, viewport) {
  3860. var update = new DisplayUpdate(cm, viewport);
  3861. if (updateDisplayIfNeeded(cm, update)) {
  3862. updateHeightsInViewport(cm);
  3863. postUpdateDisplay(cm, update);
  3864. var barMeasure = measureForScrollbars(cm);
  3865. updateSelection(cm);
  3866. updateScrollbars(cm, barMeasure);
  3867. setDocumentHeight(cm, barMeasure);
  3868. update.finish();
  3869. }
  3870. }
  3871. // Sync the actual display DOM structure with display.view, removing
  3872. // nodes for lines that are no longer in view, and creating the ones
  3873. // that are not there yet, and updating the ones that are out of
  3874. // date.
  3875. function patchDisplay(cm, updateNumbersFrom, dims) {
  3876. var display = cm.display, lineNumbers = cm.options.lineNumbers;
  3877. var container = display.lineDiv, cur = container.firstChild;
  3878. function rm(node) {
  3879. var next = node.nextSibling;
  3880. // Works around a throw-scroll bug in OS X Webkit
  3881. if (webkit && mac && cm.display.currentWheelTarget == node)
  3882. { node.style.display = "none"; }
  3883. else
  3884. { node.parentNode.removeChild(node); }
  3885. return next
  3886. }
  3887. var view = display.view, lineN = display.viewFrom;
  3888. // Loop over the elements in the view, syncing cur (the DOM nodes
  3889. // in display.lineDiv) with the view as we go.
  3890. for (var i = 0; i < view.length; i++) {
  3891. var lineView = view[i];
  3892. if (lineView.hidden) {
  3893. } else if (!lineView.node || lineView.node.parentNode != container) { // Not drawn yet
  3894. var node = buildLineElement(cm, lineView, lineN, dims);
  3895. container.insertBefore(node, cur);
  3896. } else { // Already drawn
  3897. while (cur != lineView.node) { cur = rm(cur); }
  3898. var updateNumber = lineNumbers && updateNumbersFrom != null &&
  3899. updateNumbersFrom <= lineN && lineView.lineNumber;
  3900. if (lineView.changes) {
  3901. if (indexOf(lineView.changes, "gutter") > -1) { updateNumber = false; }
  3902. updateLineForChanges(cm, lineView, lineN, dims);
  3903. }
  3904. if (updateNumber) {
  3905. removeChildren(lineView.lineNumber);
  3906. lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN)));
  3907. }
  3908. cur = lineView.node.nextSibling;
  3909. }
  3910. lineN += lineView.size;
  3911. }
  3912. while (cur) { cur = rm(cur); }
  3913. }
  3914. function updateGutterSpace(cm) {
  3915. var width = cm.display.gutters.offsetWidth;
  3916. cm.display.sizer.style.marginLeft = width + "px";
  3917. }
  3918. function setDocumentHeight(cm, measure) {
  3919. cm.display.sizer.style.minHeight = measure.docHeight + "px";
  3920. cm.display.heightForcer.style.top = measure.docHeight + "px";
  3921. cm.display.gutters.style.height = (measure.docHeight + cm.display.barHeight + scrollGap(cm)) + "px";
  3922. }
  3923. // Rebuild the gutter elements, ensure the margin to the left of the
  3924. // code matches their width.
  3925. function updateGutters(cm) {
  3926. var gutters = cm.display.gutters, specs = cm.options.gutters;
  3927. removeChildren(gutters);
  3928. var i = 0;
  3929. for (; i < specs.length; ++i) {
  3930. var gutterClass = specs[i];
  3931. var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + gutterClass));
  3932. if (gutterClass == "CodeMirror-linenumbers") {
  3933. cm.display.lineGutter = gElt;
  3934. gElt.style.width = (cm.display.lineNumWidth || 1) + "px";
  3935. }
  3936. }
  3937. gutters.style.display = i ? "" : "none";
  3938. updateGutterSpace(cm);
  3939. }
  3940. // Make sure the gutters options contains the element
  3941. // "CodeMirror-linenumbers" when the lineNumbers option is true.
  3942. function setGuttersForLineNumbers(options) {
  3943. var found = indexOf(options.gutters, "CodeMirror-linenumbers");
  3944. if (found == -1 && options.lineNumbers) {
  3945. options.gutters = options.gutters.concat(["CodeMirror-linenumbers"]);
  3946. } else if (found > -1 && !options.lineNumbers) {
  3947. options.gutters = options.gutters.slice(0);
  3948. options.gutters.splice(found, 1);
  3949. }
  3950. }
  3951. // Since the delta values reported on mouse wheel events are
  3952. // unstandardized between browsers and even browser versions, and
  3953. // generally horribly unpredictable, this code starts by measuring
  3954. // the scroll effect that the first few mouse wheel events have,
  3955. // and, from that, detects the way it can convert deltas to pixel
  3956. // offsets afterwards.
  3957. //
  3958. // The reason we want to know the amount a wheel event will scroll
  3959. // is that it gives us a chance to update the display before the
  3960. // actual scrolling happens, reducing flickering.
  3961. var wheelSamples = 0;
  3962. var wheelPixelsPerUnit = null;
  3963. // Fill in a browser-detected starting value on browsers where we
  3964. // know one. These don't have to be accurate -- the result of them
  3965. // being wrong would just be a slight flicker on the first wheel
  3966. // scroll (if it is large enough).
  3967. if (ie) { wheelPixelsPerUnit = -.53; }
  3968. else if (gecko) { wheelPixelsPerUnit = 15; }
  3969. else if (chrome) { wheelPixelsPerUnit = -.7; }
  3970. else if (safari) { wheelPixelsPerUnit = -1/3; }
  3971. function wheelEventDelta(e) {
  3972. var dx = e.wheelDeltaX, dy = e.wheelDeltaY;
  3973. if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) { dx = e.detail; }
  3974. if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) { dy = e.detail; }
  3975. else if (dy == null) { dy = e.wheelDelta; }
  3976. return {x: dx, y: dy}
  3977. }
  3978. function wheelEventPixels(e) {
  3979. var delta = wheelEventDelta(e);
  3980. delta.x *= wheelPixelsPerUnit;
  3981. delta.y *= wheelPixelsPerUnit;
  3982. return delta
  3983. }
  3984. function onScrollWheel(cm, e) {
  3985. var delta = wheelEventDelta(e), dx = delta.x, dy = delta.y;
  3986. var display = cm.display, scroll = display.scroller;
  3987. // Quit if there's nothing to scroll here
  3988. var canScrollX = scroll.scrollWidth > scroll.clientWidth;
  3989. var canScrollY = scroll.scrollHeight > scroll.clientHeight;
  3990. if (!(dx && canScrollX || dy && canScrollY)) { return }
  3991. // Webkit browsers on OS X abort momentum scrolls when the target
  3992. // of the scroll event is removed from the scrollable element.
  3993. // This hack (see related code in patchDisplay) makes sure the
  3994. // element is kept around.
  3995. if (dy && mac && webkit) {
  3996. outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) {
  3997. for (var i = 0; i < view.length; i++) {
  3998. if (view[i].node == cur) {
  3999. cm.display.currentWheelTarget = cur;
  4000. break outer
  4001. }
  4002. }
  4003. }
  4004. }
  4005. // On some browsers, horizontal scrolling will cause redraws to
  4006. // happen before the gutter has been realigned, causing it to
  4007. // wriggle around in a most unseemly way. When we have an
  4008. // estimated pixels/delta value, we just handle horizontal
  4009. // scrolling entirely here. It'll be slightly off from native, but
  4010. // better than glitching out.
  4011. if (dx && !gecko && !presto && wheelPixelsPerUnit != null) {
  4012. if (dy && canScrollY)
  4013. { updateScrollTop(cm, Math.max(0, scroll.scrollTop + dy * wheelPixelsPerUnit)); }
  4014. setScrollLeft(cm, Math.max(0, scroll.scrollLeft + dx * wheelPixelsPerUnit));
  4015. // Only prevent default scrolling if vertical scrolling is
  4016. // actually possible. Otherwise, it causes vertical scroll
  4017. // jitter on OSX trackpads when deltaX is small and deltaY
  4018. // is large (issue #3579)
  4019. if (!dy || (dy && canScrollY))
  4020. { e_preventDefault(e); }
  4021. display.wheelStartX = null; // Abort measurement, if in progress
  4022. return
  4023. }
  4024. // 'Project' the visible viewport to cover the area that is being
  4025. // scrolled into view (if we know enough to estimate it).
  4026. if (dy && wheelPixelsPerUnit != null) {
  4027. var pixels = dy * wheelPixelsPerUnit;
  4028. var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight;
  4029. if (pixels < 0) { top = Math.max(0, top + pixels - 50); }
  4030. else { bot = Math.min(cm.doc.height, bot + pixels + 50); }
  4031. updateDisplaySimple(cm, {top: top, bottom: bot});
  4032. }
  4033. if (wheelSamples < 20) {
  4034. if (display.wheelStartX == null) {
  4035. display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop;
  4036. display.wheelDX = dx; display.wheelDY = dy;
  4037. setTimeout(function () {
  4038. if (display.wheelStartX == null) { return }
  4039. var movedX = scroll.scrollLeft - display.wheelStartX;
  4040. var movedY = scroll.scrollTop - display.wheelStartY;
  4041. var sample = (movedY && display.wheelDY && movedY / display.wheelDY) ||
  4042. (movedX && display.wheelDX && movedX / display.wheelDX);
  4043. display.wheelStartX = display.wheelStartY = null;
  4044. if (!sample) { return }
  4045. wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1);
  4046. ++wheelSamples;
  4047. }, 200);
  4048. } else {
  4049. display.wheelDX += dx; display.wheelDY += dy;
  4050. }
  4051. }
  4052. }
  4053. // Selection objects are immutable. A new one is created every time
  4054. // the selection changes. A selection is one or more non-overlapping
  4055. // (and non-touching) ranges, sorted, and an integer that indicates
  4056. // which one is the primary selection (the one that's scrolled into
  4057. // view, that getCursor returns, etc).
  4058. var Selection = function(ranges, primIndex) {
  4059. this.ranges = ranges;
  4060. this.primIndex = primIndex;
  4061. };
  4062. Selection.prototype.primary = function () { return this.ranges[this.primIndex] };
  4063. Selection.prototype.equals = function (other) {
  4064. var this$1 = this;
  4065. if (other == this) { return true }
  4066. if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) { return false }
  4067. for (var i = 0; i < this.ranges.length; i++) {
  4068. var here = this$1.ranges[i], there = other.ranges[i];
  4069. if (!equalCursorPos(here.anchor, there.anchor) || !equalCursorPos(here.head, there.head)) { return false }
  4070. }
  4071. return true
  4072. };
  4073. Selection.prototype.deepCopy = function () {
  4074. var this$1 = this;
  4075. var out = [];
  4076. for (var i = 0; i < this.ranges.length; i++)
  4077. { out[i] = new Range(copyPos(this$1.ranges[i].anchor), copyPos(this$1.ranges[i].head)); }
  4078. return new Selection(out, this.primIndex)
  4079. };
  4080. Selection.prototype.somethingSelected = function () {
  4081. var this$1 = this;
  4082. for (var i = 0; i < this.ranges.length; i++)
  4083. { if (!this$1.ranges[i].empty()) { return true } }
  4084. return false
  4085. };
  4086. Selection.prototype.contains = function (pos, end) {
  4087. var this$1 = this;
  4088. if (!end) { end = pos; }
  4089. for (var i = 0; i < this.ranges.length; i++) {
  4090. var range = this$1.ranges[i];
  4091. if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0)
  4092. { return i }
  4093. }
  4094. return -1
  4095. };
  4096. var Range = function(anchor, head) {
  4097. this.anchor = anchor; this.head = head;
  4098. };
  4099. Range.prototype.from = function () { return minPos(this.anchor, this.head) };
  4100. Range.prototype.to = function () { return maxPos(this.anchor, this.head) };
  4101. Range.prototype.empty = function () { return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch };
  4102. // Take an unsorted, potentially overlapping set of ranges, and
  4103. // build a selection out of it. 'Consumes' ranges array (modifying
  4104. // it).
  4105. function normalizeSelection(ranges, primIndex) {
  4106. var prim = ranges[primIndex];
  4107. ranges.sort(function (a, b) { return cmp(a.from(), b.from()); });
  4108. primIndex = indexOf(ranges, prim);
  4109. for (var i = 1; i < ranges.length; i++) {
  4110. var cur = ranges[i], prev = ranges[i - 1];
  4111. if (cmp(prev.to(), cur.from()) >= 0) {
  4112. var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to());
  4113. var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head;
  4114. if (i <= primIndex) { --primIndex; }
  4115. ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to));
  4116. }
  4117. }
  4118. return new Selection(ranges, primIndex)
  4119. }
  4120. function simpleSelection(anchor, head) {
  4121. return new Selection([new Range(anchor, head || anchor)], 0)
  4122. }
  4123. // Compute the position of the end of a change (its 'to' property
  4124. // refers to the pre-change end).
  4125. function changeEnd(change) {
  4126. if (!change.text) { return change.to }
  4127. return Pos(change.from.line + change.text.length - 1,
  4128. lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0))
  4129. }
  4130. // Adjust a position to refer to the post-change position of the
  4131. // same text, or the end of the change if the change covers it.
  4132. function adjustForChange(pos, change) {
  4133. if (cmp(pos, change.from) < 0) { return pos }
  4134. if (cmp(pos, change.to) <= 0) { return changeEnd(change) }
  4135. var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch;
  4136. if (pos.line == change.to.line) { ch += changeEnd(change).ch - change.to.ch; }
  4137. return Pos(line, ch)
  4138. }
  4139. function computeSelAfterChange(doc, change) {
  4140. var out = [];
  4141. for (var i = 0; i < doc.sel.ranges.length; i++) {
  4142. var range = doc.sel.ranges[i];
  4143. out.push(new Range(adjustForChange(range.anchor, change),
  4144. adjustForChange(range.head, change)));
  4145. }
  4146. return normalizeSelection(out, doc.sel.primIndex)
  4147. }
  4148. function offsetPos(pos, old, nw) {
  4149. if (pos.line == old.line)
  4150. { return Pos(nw.line, pos.ch - old.ch + nw.ch) }
  4151. else
  4152. { return Pos(nw.line + (pos.line - old.line), pos.ch) }
  4153. }
  4154. // Used by replaceSelections to allow moving the selection to the
  4155. // start or around the replaced test. Hint may be "start" or "around".
  4156. function computeReplacedSel(doc, changes, hint) {
  4157. var out = [];
  4158. var oldPrev = Pos(doc.first, 0), newPrev = oldPrev;
  4159. for (var i = 0; i < changes.length; i++) {
  4160. var change = changes[i];
  4161. var from = offsetPos(change.from, oldPrev, newPrev);
  4162. var to = offsetPos(changeEnd(change), oldPrev, newPrev);
  4163. oldPrev = change.to;
  4164. newPrev = to;
  4165. if (hint == "around") {
  4166. var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) < 0;
  4167. out[i] = new Range(inv ? to : from, inv ? from : to);
  4168. } else {
  4169. out[i] = new Range(from, from);
  4170. }
  4171. }
  4172. return new Selection(out, doc.sel.primIndex)
  4173. }
  4174. // Used to get the editor into a consistent state again when options change.
  4175. function loadMode(cm) {
  4176. cm.doc.mode = getMode(cm.options, cm.doc.modeOption);
  4177. resetModeState(cm);
  4178. }
  4179. function resetModeState(cm) {
  4180. cm.doc.iter(function (line) {
  4181. if (line.stateAfter) { line.stateAfter = null; }
  4182. if (line.styles) { line.styles = null; }
  4183. });
  4184. cm.doc.modeFrontier = cm.doc.highlightFrontier = cm.doc.first;
  4185. startWorker(cm, 100);
  4186. cm.state.modeGen++;
  4187. if (cm.curOp) { regChange(cm); }
  4188. }
  4189. // DOCUMENT DATA STRUCTURE
  4190. // By default, updates that start and end at the beginning of a line
  4191. // are treated specially, in order to make the association of line
  4192. // widgets and marker elements with the text behave more intuitive.
  4193. function isWholeLineUpdate(doc, change) {
  4194. return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" &&
  4195. (!doc.cm || doc.cm.options.wholeLineUpdateBefore)
  4196. }
  4197. // Perform a change on the document data structure.
  4198. function updateDoc(doc, change, markedSpans, estimateHeight$$1) {
  4199. function spansFor(n) {return markedSpans ? markedSpans[n] : null}
  4200. function update(line, text, spans) {
  4201. updateLine(line, text, spans, estimateHeight$$1);
  4202. signalLater(line, "change", line, change);
  4203. }
  4204. function linesFor(start, end) {
  4205. var result = [];
  4206. for (var i = start; i < end; ++i)
  4207. { result.push(new Line(text[i], spansFor(i), estimateHeight$$1)); }
  4208. return result
  4209. }
  4210. var from = change.from, to = change.to, text = change.text;
  4211. var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line);
  4212. var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line;
  4213. // Adjust the line structure
  4214. if (change.full) {
  4215. doc.insert(0, linesFor(0, text.length));
  4216. doc.remove(text.length, doc.size - text.length);
  4217. } else if (isWholeLineUpdate(doc, change)) {
  4218. // This is a whole-line replace. Treated specially to make
  4219. // sure line objects move the way they are supposed to.
  4220. var added = linesFor(0, text.length - 1);
  4221. update(lastLine, lastLine.text, lastSpans);
  4222. if (nlines) { doc.remove(from.line, nlines); }
  4223. if (added.length) { doc.insert(from.line, added); }
  4224. } else if (firstLine == lastLine) {
  4225. if (text.length == 1) {
  4226. update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans);
  4227. } else {
  4228. var added$1 = linesFor(1, text.length - 1);
  4229. added$1.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight$$1));
  4230. update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
  4231. doc.insert(from.line + 1, added$1);
  4232. }
  4233. } else if (text.length == 1) {
  4234. update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0));
  4235. doc.remove(from.line + 1, nlines);
  4236. } else {
  4237. update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
  4238. update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans);
  4239. var added$2 = linesFor(1, text.length - 1);
  4240. if (nlines > 1) { doc.remove(from.line + 1, nlines - 1); }
  4241. doc.insert(from.line + 1, added$2);
  4242. }
  4243. signalLater(doc, "change", doc, change);
  4244. }
  4245. // Call f for all linked documents.
  4246. function linkedDocs(doc, f, sharedHistOnly) {
  4247. function propagate(doc, skip, sharedHist) {
  4248. if (doc.linked) { for (var i = 0; i < doc.linked.length; ++i) {
  4249. var rel = doc.linked[i];
  4250. if (rel.doc == skip) { continue }
  4251. var shared = sharedHist && rel.sharedHist;
  4252. if (sharedHistOnly && !shared) { continue }
  4253. f(rel.doc, shared);
  4254. propagate(rel.doc, doc, shared);
  4255. } }
  4256. }
  4257. propagate(doc, null, true);
  4258. }
  4259. // Attach a document to an editor.
  4260. function attachDoc(cm, doc) {
  4261. if (doc.cm) { throw new Error("This document is already in use.") }
  4262. cm.doc = doc;
  4263. doc.cm = cm;
  4264. estimateLineHeights(cm);
  4265. loadMode(cm);
  4266. setDirectionClass(cm);
  4267. if (!cm.options.lineWrapping) { findMaxLine(cm); }
  4268. cm.options.mode = doc.modeOption;
  4269. regChange(cm);
  4270. }
  4271. function setDirectionClass(cm) {
  4272. (cm.doc.direction == "rtl" ? addClass : rmClass)(cm.display.lineDiv, "CodeMirror-rtl");
  4273. }
  4274. function directionChanged(cm) {
  4275. runInOp(cm, function () {
  4276. setDirectionClass(cm);
  4277. regChange(cm);
  4278. });
  4279. }
  4280. function History(startGen) {
  4281. // Arrays of change events and selections. Doing something adds an
  4282. // event to done and clears undo. Undoing moves events from done
  4283. // to undone, redoing moves them in the other direction.
  4284. this.done = []; this.undone = [];
  4285. this.undoDepth = Infinity;
  4286. // Used to track when changes can be merged into a single undo
  4287. // event
  4288. this.lastModTime = this.lastSelTime = 0;
  4289. this.lastOp = this.lastSelOp = null;
  4290. this.lastOrigin = this.lastSelOrigin = null;
  4291. // Used by the isClean() method
  4292. this.generation = this.maxGeneration = startGen || 1;
  4293. }
  4294. // Create a history change event from an updateDoc-style change
  4295. // object.
  4296. function historyChangeFromChange(doc, change) {
  4297. var histChange = {from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to)};
  4298. attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);
  4299. linkedDocs(doc, function (doc) { return attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1); }, true);
  4300. return histChange
  4301. }
  4302. // Pop all selection events off the end of a history array. Stop at
  4303. // a change event.
  4304. function clearSelectionEvents(array) {
  4305. while (array.length) {
  4306. var last = lst(array);
  4307. if (last.ranges) { array.pop(); }
  4308. else { break }
  4309. }
  4310. }
  4311. // Find the top change event in the history. Pop off selection
  4312. // events that are in the way.
  4313. function lastChangeEvent(hist, force) {
  4314. if (force) {
  4315. clearSelectionEvents(hist.done);
  4316. return lst(hist.done)
  4317. } else if (hist.done.length && !lst(hist.done).ranges) {
  4318. return lst(hist.done)
  4319. } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) {
  4320. hist.done.pop();
  4321. return lst(hist.done)
  4322. }
  4323. }
  4324. // Register a change in the history. Merges changes that are within
  4325. // a single operation, or are close together with an origin that
  4326. // allows merging (starting with "+") into a single event.
  4327. function addChangeToHistory(doc, change, selAfter, opId) {
  4328. var hist = doc.history;
  4329. hist.undone.length = 0;
  4330. var time = +new Date, cur;
  4331. var last;
  4332. if ((hist.lastOp == opId ||
  4333. hist.lastOrigin == change.origin && change.origin &&
  4334. ((change.origin.charAt(0) == "+" && doc.cm && hist.lastModTime > time - doc.cm.options.historyEventDelay) ||
  4335. change.origin.charAt(0) == "*")) &&
  4336. (cur = lastChangeEvent(hist, hist.lastOp == opId))) {
  4337. // Merge this change into the last event
  4338. last = lst(cur.changes);
  4339. if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) {
  4340. // Optimized case for simple insertion -- don't want to add
  4341. // new changesets for every character typed
  4342. last.to = changeEnd(change);
  4343. } else {
  4344. // Add new sub-event
  4345. cur.changes.push(historyChangeFromChange(doc, change));
  4346. }
  4347. } else {
  4348. // Can not be merged, start a new event.
  4349. var before = lst(hist.done);
  4350. if (!before || !before.ranges)
  4351. { pushSelectionToHistory(doc.sel, hist.done); }
  4352. cur = {changes: [historyChangeFromChange(doc, change)],
  4353. generation: hist.generation};
  4354. hist.done.push(cur);
  4355. while (hist.done.length > hist.undoDepth) {
  4356. hist.done.shift();
  4357. if (!hist.done[0].ranges) { hist.done.shift(); }
  4358. }
  4359. }
  4360. hist.done.push(selAfter);
  4361. hist.generation = ++hist.maxGeneration;
  4362. hist.lastModTime = hist.lastSelTime = time;
  4363. hist.lastOp = hist.lastSelOp = opId;
  4364. hist.lastOrigin = hist.lastSelOrigin = change.origin;
  4365. if (!last) { signal(doc, "historyAdded"); }
  4366. }
  4367. function selectionEventCanBeMerged(doc, origin, prev, sel) {
  4368. var ch = origin.charAt(0);
  4369. return ch == "*" ||
  4370. ch == "+" &&
  4371. prev.ranges.length == sel.ranges.length &&
  4372. prev.somethingSelected() == sel.somethingSelected() &&
  4373. new Date - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500)
  4374. }
  4375. // Called whenever the selection changes, sets the new selection as
  4376. // the pending selection in the history, and pushes the old pending
  4377. // selection into the 'done' array when it was significantly
  4378. // different (in number of selected ranges, emptiness, or time).
  4379. function addSelectionToHistory(doc, sel, opId, options) {
  4380. var hist = doc.history, origin = options && options.origin;
  4381. // A new event is started when the previous origin does not match
  4382. // the current, or the origins don't allow matching. Origins
  4383. // starting with * are always merged, those starting with + are
  4384. // merged when similar and close together in time.
  4385. if (opId == hist.lastSelOp ||
  4386. (origin && hist.lastSelOrigin == origin &&
  4387. (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin ||
  4388. selectionEventCanBeMerged(doc, origin, lst(hist.done), sel))))
  4389. { hist.done[hist.done.length - 1] = sel; }
  4390. else
  4391. { pushSelectionToHistory(sel, hist.done); }
  4392. hist.lastSelTime = +new Date;
  4393. hist.lastSelOrigin = origin;
  4394. hist.lastSelOp = opId;
  4395. if (options && options.clearRedo !== false)
  4396. { clearSelectionEvents(hist.undone); }
  4397. }
  4398. function pushSelectionToHistory(sel, dest) {
  4399. var top = lst(dest);
  4400. if (!(top && top.ranges && top.equals(sel)))
  4401. { dest.push(sel); }
  4402. }
  4403. // Used to store marked span information in the history.
  4404. function attachLocalSpans(doc, change, from, to) {
  4405. var existing = change["spans_" + doc.id], n = 0;
  4406. doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function (line) {
  4407. if (line.markedSpans)
  4408. { (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans; }
  4409. ++n;
  4410. });
  4411. }
  4412. // When un/re-doing restores text containing marked spans, those
  4413. // that have been explicitly cleared should not be restored.
  4414. function removeClearedSpans(spans) {
  4415. if (!spans) { return null }
  4416. var out;
  4417. for (var i = 0; i < spans.length; ++i) {
  4418. if (spans[i].marker.explicitlyCleared) { if (!out) { out = spans.slice(0, i); } }
  4419. else if (out) { out.push(spans[i]); }
  4420. }
  4421. return !out ? spans : out.length ? out : null
  4422. }
  4423. // Retrieve and filter the old marked spans stored in a change event.
  4424. function getOldSpans(doc, change) {
  4425. var found = change["spans_" + doc.id];
  4426. if (!found) { return null }
  4427. var nw = [];
  4428. for (var i = 0; i < change.text.length; ++i)
  4429. { nw.push(removeClearedSpans(found[i])); }
  4430. return nw
  4431. }
  4432. // Used for un/re-doing changes from the history. Combines the
  4433. // result of computing the existing spans with the set of spans that
  4434. // existed in the history (so that deleting around a span and then
  4435. // undoing brings back the span).
  4436. function mergeOldSpans(doc, change) {
  4437. var old = getOldSpans(doc, change);
  4438. var stretched = stretchSpansOverChange(doc, change);
  4439. if (!old) { return stretched }
  4440. if (!stretched) { return old }
  4441. for (var i = 0; i < old.length; ++i) {
  4442. var oldCur = old[i], stretchCur = stretched[i];
  4443. if (oldCur && stretchCur) {
  4444. spans: for (var j = 0; j < stretchCur.length; ++j) {
  4445. var span = stretchCur[j];
  4446. for (var k = 0; k < oldCur.length; ++k)
  4447. { if (oldCur[k].marker == span.marker) { continue spans } }
  4448. oldCur.push(span);
  4449. }
  4450. } else if (stretchCur) {
  4451. old[i] = stretchCur;
  4452. }
  4453. }
  4454. return old
  4455. }
  4456. // Used both to provide a JSON-safe object in .getHistory, and, when
  4457. // detaching a document, to split the history in two
  4458. function copyHistoryArray(events, newGroup, instantiateSel) {
  4459. var copy = [];
  4460. for (var i = 0; i < events.length; ++i) {
  4461. var event = events[i];
  4462. if (event.ranges) {
  4463. copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event);
  4464. continue
  4465. }
  4466. var changes = event.changes, newChanges = [];
  4467. copy.push({changes: newChanges});
  4468. for (var j = 0; j < changes.length; ++j) {
  4469. var change = changes[j], m = (void 0);
  4470. newChanges.push({from: change.from, to: change.to, text: change.text});
  4471. if (newGroup) { for (var prop in change) { if (m = prop.match(/^spans_(\d+)$/)) {
  4472. if (indexOf(newGroup, Number(m[1])) > -1) {
  4473. lst(newChanges)[prop] = change[prop];
  4474. delete change[prop];
  4475. }
  4476. } } }
  4477. }
  4478. }
  4479. return copy
  4480. }
  4481. // The 'scroll' parameter given to many of these indicated whether
  4482. // the new cursor position should be scrolled into view after
  4483. // modifying the selection.
  4484. // If shift is held or the extend flag is set, extends a range to
  4485. // include a given position (and optionally a second position).
  4486. // Otherwise, simply returns the range between the given positions.
  4487. // Used for cursor motion and such.
  4488. function extendRange(range, head, other, extend) {
  4489. if (extend) {
  4490. var anchor = range.anchor;
  4491. if (other) {
  4492. var posBefore = cmp(head, anchor) < 0;
  4493. if (posBefore != (cmp(other, anchor) < 0)) {
  4494. anchor = head;
  4495. head = other;
  4496. } else if (posBefore != (cmp(head, other) < 0)) {
  4497. head = other;
  4498. }
  4499. }
  4500. return new Range(anchor, head)
  4501. } else {
  4502. return new Range(other || head, head)
  4503. }
  4504. }
  4505. // Extend the primary selection range, discard the rest.
  4506. function extendSelection(doc, head, other, options, extend) {
  4507. if (extend == null) { extend = doc.cm && (doc.cm.display.shift || doc.extend); }
  4508. setSelection(doc, new Selection([extendRange(doc.sel.primary(), head, other, extend)], 0), options);
  4509. }
  4510. // Extend all selections (pos is an array of selections with length
  4511. // equal the number of selections)
  4512. function extendSelections(doc, heads, options) {
  4513. var out = [];
  4514. var extend = doc.cm && (doc.cm.display.shift || doc.extend);
  4515. for (var i = 0; i < doc.sel.ranges.length; i++)
  4516. { out[i] = extendRange(doc.sel.ranges[i], heads[i], null, extend); }
  4517. var newSel = normalizeSelection(out, doc.sel.primIndex);
  4518. setSelection(doc, newSel, options);
  4519. }
  4520. // Updates a single range in the selection.
  4521. function replaceOneSelection(doc, i, range, options) {
  4522. var ranges = doc.sel.ranges.slice(0);
  4523. ranges[i] = range;
  4524. setSelection(doc, normalizeSelection(ranges, doc.sel.primIndex), options);
  4525. }
  4526. // Reset the selection to a single range.
  4527. function setSimpleSelection(doc, anchor, head, options) {
  4528. setSelection(doc, simpleSelection(anchor, head), options);
  4529. }
  4530. // Give beforeSelectionChange handlers a change to influence a
  4531. // selection update.
  4532. function filterSelectionChange(doc, sel, options) {
  4533. var obj = {
  4534. ranges: sel.ranges,
  4535. update: function(ranges) {
  4536. var this$1 = this;
  4537. this.ranges = [];
  4538. for (var i = 0; i < ranges.length; i++)
  4539. { this$1.ranges[i] = new Range(clipPos(doc, ranges[i].anchor),
  4540. clipPos(doc, ranges[i].head)); }
  4541. },
  4542. origin: options && options.origin
  4543. };
  4544. signal(doc, "beforeSelectionChange", doc, obj);
  4545. if (doc.cm) { signal(doc.cm, "beforeSelectionChange", doc.cm, obj); }
  4546. if (obj.ranges != sel.ranges) { return normalizeSelection(obj.ranges, obj.ranges.length - 1) }
  4547. else { return sel }
  4548. }
  4549. function setSelectionReplaceHistory(doc, sel, options) {
  4550. var done = doc.history.done, last = lst(done);
  4551. if (last && last.ranges) {
  4552. done[done.length - 1] = sel;
  4553. setSelectionNoUndo(doc, sel, options);
  4554. } else {
  4555. setSelection(doc, sel, options);
  4556. }
  4557. }
  4558. // Set a new selection.
  4559. function setSelection(doc, sel, options) {
  4560. setSelectionNoUndo(doc, sel, options);
  4561. addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options);
  4562. }
  4563. function setSelectionNoUndo(doc, sel, options) {
  4564. if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange"))
  4565. { sel = filterSelectionChange(doc, sel, options); }
  4566. var bias = options && options.bias ||
  4567. (cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1);
  4568. setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true));
  4569. if (!(options && options.scroll === false) && doc.cm)
  4570. { ensureCursorVisible(doc.cm); }
  4571. }
  4572. function setSelectionInner(doc, sel) {
  4573. if (sel.equals(doc.sel)) { return }
  4574. doc.sel = sel;
  4575. if (doc.cm) {
  4576. doc.cm.curOp.updateInput = doc.cm.curOp.selectionChanged = true;
  4577. signalCursorActivity(doc.cm);
  4578. }
  4579. signalLater(doc, "cursorActivity", doc);
  4580. }
  4581. // Verify that the selection does not partially select any atomic
  4582. // marked ranges.
  4583. function reCheckSelection(doc) {
  4584. setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false));
  4585. }
  4586. // Return a selection that does not partially select any atomic
  4587. // ranges.
  4588. function skipAtomicInSelection(doc, sel, bias, mayClear) {
  4589. var out;
  4590. for (var i = 0; i < sel.ranges.length; i++) {
  4591. var range = sel.ranges[i];
  4592. var old = sel.ranges.length == doc.sel.ranges.length && doc.sel.ranges[i];
  4593. var newAnchor = skipAtomic(doc, range.anchor, old && old.anchor, bias, mayClear);
  4594. var newHead = skipAtomic(doc, range.head, old && old.head, bias, mayClear);
  4595. if (out || newAnchor != range.anchor || newHead != range.head) {
  4596. if (!out) { out = sel.ranges.slice(0, i); }
  4597. out[i] = new Range(newAnchor, newHead);
  4598. }
  4599. }
  4600. return out ? normalizeSelection(out, sel.primIndex) : sel
  4601. }
  4602. function skipAtomicInner(doc, pos, oldPos, dir, mayClear) {
  4603. var line = getLine(doc, pos.line);
  4604. if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) {
  4605. var sp = line.markedSpans[i], m = sp.marker;
  4606. if ((sp.from == null || (m.inclusiveLeft ? sp.from <= pos.ch : sp.from < pos.ch)) &&
  4607. (sp.to == null || (m.inclusiveRight ? sp.to >= pos.ch : sp.to > pos.ch))) {
  4608. if (mayClear) {
  4609. signal(m, "beforeCursorEnter");
  4610. if (m.explicitlyCleared) {
  4611. if (!line.markedSpans) { break }
  4612. else {--i; continue}
  4613. }
  4614. }
  4615. if (!m.atomic) { continue }
  4616. if (oldPos) {
  4617. var near = m.find(dir < 0 ? 1 : -1), diff = (void 0);
  4618. if (dir < 0 ? m.inclusiveRight : m.inclusiveLeft)
  4619. { near = movePos(doc, near, -dir, near && near.line == pos.line ? line : null); }
  4620. if (near && near.line == pos.line && (diff = cmp(near, oldPos)) && (dir < 0 ? diff < 0 : diff > 0))
  4621. { return skipAtomicInner(doc, near, pos, dir, mayClear) }
  4622. }
  4623. var far = m.find(dir < 0 ? -1 : 1);
  4624. if (dir < 0 ? m.inclusiveLeft : m.inclusiveRight)
  4625. { far = movePos(doc, far, dir, far.line == pos.line ? line : null); }
  4626. return far ? skipAtomicInner(doc, far, pos, dir, mayClear) : null
  4627. }
  4628. } }
  4629. return pos
  4630. }
  4631. // Ensure a given position is not inside an atomic range.
  4632. function skipAtomic(doc, pos, oldPos, bias, mayClear) {
  4633. var dir = bias || 1;
  4634. var found = skipAtomicInner(doc, pos, oldPos, dir, mayClear) ||
  4635. (!mayClear && skipAtomicInner(doc, pos, oldPos, dir, true)) ||
  4636. skipAtomicInner(doc, pos, oldPos, -dir, mayClear) ||
  4637. (!mayClear && skipAtomicInner(doc, pos, oldPos, -dir, true));
  4638. if (!found) {
  4639. doc.cantEdit = true;
  4640. return Pos(doc.first, 0)
  4641. }
  4642. return found
  4643. }
  4644. function movePos(doc, pos, dir, line) {
  4645. if (dir < 0 && pos.ch == 0) {
  4646. if (pos.line > doc.first) { return clipPos(doc, Pos(pos.line - 1)) }
  4647. else { return null }
  4648. } else if (dir > 0 && pos.ch == (line || getLine(doc, pos.line)).text.length) {
  4649. if (pos.line < doc.first + doc.size - 1) { return Pos(pos.line + 1, 0) }
  4650. else { return null }
  4651. } else {
  4652. return new Pos(pos.line, pos.ch + dir)
  4653. }
  4654. }
  4655. function selectAll(cm) {
  4656. cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll);
  4657. }
  4658. // UPDATING
  4659. // Allow "beforeChange" event handlers to influence a change
  4660. function filterChange(doc, change, update) {
  4661. var obj = {
  4662. canceled: false,
  4663. from: change.from,
  4664. to: change.to,
  4665. text: change.text,
  4666. origin: change.origin,
  4667. cancel: function () { return obj.canceled = true; }
  4668. };
  4669. if (update) { obj.update = function (from, to, text, origin) {
  4670. if (from) { obj.from = clipPos(doc, from); }
  4671. if (to) { obj.to = clipPos(doc, to); }
  4672. if (text) { obj.text = text; }
  4673. if (origin !== undefined) { obj.origin = origin; }
  4674. }; }
  4675. signal(doc, "beforeChange", doc, obj);
  4676. if (doc.cm) { signal(doc.cm, "beforeChange", doc.cm, obj); }
  4677. if (obj.canceled) { return null }
  4678. return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin}
  4679. }
  4680. // Apply a change to a document, and add it to the document's
  4681. // history, and propagating it to all linked documents.
  4682. function makeChange(doc, change, ignoreReadOnly) {
  4683. if (doc.cm) {
  4684. if (!doc.cm.curOp) { return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly) }
  4685. if (doc.cm.state.suppressEdits) { return }
  4686. }
  4687. if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) {
  4688. change = filterChange(doc, change, true);
  4689. if (!change) { return }
  4690. }
  4691. // Possibly split or suppress the update based on the presence
  4692. // of read-only spans in its range.
  4693. var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to);
  4694. if (split) {
  4695. for (var i = split.length - 1; i >= 0; --i)
  4696. { makeChangeInner(doc, {from: split[i].from, to: split[i].to, text: i ? [""] : change.text, origin: change.origin}); }
  4697. } else {
  4698. makeChangeInner(doc, change);
  4699. }
  4700. }
  4701. function makeChangeInner(doc, change) {
  4702. if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) { return }
  4703. var selAfter = computeSelAfterChange(doc, change);
  4704. addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN);
  4705. makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change));
  4706. var rebased = [];
  4707. linkedDocs(doc, function (doc, sharedHist) {
  4708. if (!sharedHist && indexOf(rebased, doc.history) == -1) {
  4709. rebaseHist(doc.history, change);
  4710. rebased.push(doc.history);
  4711. }
  4712. makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change));
  4713. });
  4714. }
  4715. // Revert a change stored in a document's history.
  4716. function makeChangeFromHistory(doc, type, allowSelectionOnly) {
  4717. var suppress = doc.cm && doc.cm.state.suppressEdits;
  4718. if (suppress && !allowSelectionOnly) { return }
  4719. var hist = doc.history, event, selAfter = doc.sel;
  4720. var source = type == "undo" ? hist.done : hist.undone, dest = type == "undo" ? hist.undone : hist.done;
  4721. // Verify that there is a useable event (so that ctrl-z won't
  4722. // needlessly clear selection events)
  4723. var i = 0;
  4724. for (; i < source.length; i++) {
  4725. event = source[i];
  4726. if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges)
  4727. { break }
  4728. }
  4729. if (i == source.length) { return }
  4730. hist.lastOrigin = hist.lastSelOrigin = null;
  4731. for (;;) {
  4732. event = source.pop();
  4733. if (event.ranges) {
  4734. pushSelectionToHistory(event, dest);
  4735. if (allowSelectionOnly && !event.equals(doc.sel)) {
  4736. setSelection(doc, event, {clearRedo: false});
  4737. return
  4738. }
  4739. selAfter = event;
  4740. } else if (suppress) {
  4741. source.push(event);
  4742. return
  4743. } else { break }
  4744. }
  4745. // Build up a reverse change object to add to the opposite history
  4746. // stack (redo when undoing, and vice versa).
  4747. var antiChanges = [];
  4748. pushSelectionToHistory(selAfter, dest);
  4749. dest.push({changes: antiChanges, generation: hist.generation});
  4750. hist.generation = event.generation || ++hist.maxGeneration;
  4751. var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange");
  4752. var loop = function ( i ) {
  4753. var change = event.changes[i];
  4754. change.origin = type;
  4755. if (filter && !filterChange(doc, change, false)) {
  4756. source.length = 0;
  4757. return {}
  4758. }
  4759. antiChanges.push(historyChangeFromChange(doc, change));
  4760. var after = i ? computeSelAfterChange(doc, change) : lst(source);
  4761. makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change));
  4762. if (!i && doc.cm) { doc.cm.scrollIntoView({from: change.from, to: changeEnd(change)}); }
  4763. var rebased = [];
  4764. // Propagate to the linked documents
  4765. linkedDocs(doc, function (doc, sharedHist) {
  4766. if (!sharedHist && indexOf(rebased, doc.history) == -1) {
  4767. rebaseHist(doc.history, change);
  4768. rebased.push(doc.history);
  4769. }
  4770. makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change));
  4771. });
  4772. };
  4773. for (var i$1 = event.changes.length - 1; i$1 >= 0; --i$1) {
  4774. var returned = loop( i$1 );
  4775. if ( returned ) return returned.v;
  4776. }
  4777. }
  4778. // Sub-views need their line numbers shifted when text is added
  4779. // above or below them in the parent document.
  4780. function shiftDoc(doc, distance) {
  4781. if (distance == 0) { return }
  4782. doc.first += distance;
  4783. doc.sel = new Selection(map(doc.sel.ranges, function (range) { return new Range(
  4784. Pos(range.anchor.line + distance, range.anchor.ch),
  4785. Pos(range.head.line + distance, range.head.ch)
  4786. ); }), doc.sel.primIndex);
  4787. if (doc.cm) {
  4788. regChange(doc.cm, doc.first, doc.first - distance, distance);
  4789. for (var d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++)
  4790. { regLineChange(doc.cm, l, "gutter"); }
  4791. }
  4792. }
  4793. // More lower-level change function, handling only a single document
  4794. // (not linked ones).
  4795. function makeChangeSingleDoc(doc, change, selAfter, spans) {
  4796. if (doc.cm && !doc.cm.curOp)
  4797. { return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans) }
  4798. if (change.to.line < doc.first) {
  4799. shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line));
  4800. return
  4801. }
  4802. if (change.from.line > doc.lastLine()) { return }
  4803. // Clip the change to the size of this doc
  4804. if (change.from.line < doc.first) {
  4805. var shift = change.text.length - 1 - (doc.first - change.from.line);
  4806. shiftDoc(doc, shift);
  4807. change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch),
  4808. text: [lst(change.text)], origin: change.origin};
  4809. }
  4810. var last = doc.lastLine();
  4811. if (change.to.line > last) {
  4812. change = {from: change.from, to: Pos(last, getLine(doc, last).text.length),
  4813. text: [change.text[0]], origin: change.origin};
  4814. }
  4815. change.removed = getBetween(doc, change.from, change.to);
  4816. if (!selAfter) { selAfter = computeSelAfterChange(doc, change); }
  4817. if (doc.cm) { makeChangeSingleDocInEditor(doc.cm, change, spans); }
  4818. else { updateDoc(doc, change, spans); }
  4819. setSelectionNoUndo(doc, selAfter, sel_dontScroll);
  4820. }
  4821. // Handle the interaction of a change to a document with the editor
  4822. // that this document is part of.
  4823. function makeChangeSingleDocInEditor(cm, change, spans) {
  4824. var doc = cm.doc, display = cm.display, from = change.from, to = change.to;
  4825. var recomputeMaxLength = false, checkWidthStart = from.line;
  4826. if (!cm.options.lineWrapping) {
  4827. checkWidthStart = lineNo(visualLine(getLine(doc, from.line)));
  4828. doc.iter(checkWidthStart, to.line + 1, function (line) {
  4829. if (line == display.maxLine) {
  4830. recomputeMaxLength = true;
  4831. return true
  4832. }
  4833. });
  4834. }
  4835. if (doc.sel.contains(change.from, change.to) > -1)
  4836. { signalCursorActivity(cm); }
  4837. updateDoc(doc, change, spans, estimateHeight(cm));
  4838. if (!cm.options.lineWrapping) {
  4839. doc.iter(checkWidthStart, from.line + change.text.length, function (line) {
  4840. var len = lineLength(line);
  4841. if (len > display.maxLineLength) {
  4842. display.maxLine = line;
  4843. display.maxLineLength = len;
  4844. display.maxLineChanged = true;
  4845. recomputeMaxLength = false;
  4846. }
  4847. });
  4848. if (recomputeMaxLength) { cm.curOp.updateMaxLine = true; }
  4849. }
  4850. retreatFrontier(doc, from.line);
  4851. startWorker(cm, 400);
  4852. var lendiff = change.text.length - (to.line - from.line) - 1;
  4853. // Remember that these lines changed, for updating the display
  4854. if (change.full)
  4855. { regChange(cm); }
  4856. else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change))
  4857. { regLineChange(cm, from.line, "text"); }
  4858. else
  4859. { regChange(cm, from.line, to.line + 1, lendiff); }
  4860. var changesHandler = hasHandler(cm, "changes"), changeHandler = hasHandler(cm, "change");
  4861. if (changeHandler || changesHandler) {
  4862. var obj = {
  4863. from: from, to: to,
  4864. text: change.text,
  4865. removed: change.removed,
  4866. origin: change.origin
  4867. };
  4868. if (changeHandler) { signalLater(cm, "change", cm, obj); }
  4869. if (changesHandler) { (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj); }
  4870. }
  4871. cm.display.selForContextMenu = null;
  4872. }
  4873. function replaceRange(doc, code, from, to, origin) {
  4874. if (!to) { to = from; }
  4875. if (cmp(to, from) < 0) { var assign;
  4876. (assign = [to, from], from = assign[0], to = assign[1], assign); }
  4877. if (typeof code == "string") { code = doc.splitLines(code); }
  4878. makeChange(doc, {from: from, to: to, text: code, origin: origin});
  4879. }
  4880. // Rebasing/resetting history to deal with externally-sourced changes
  4881. function rebaseHistSelSingle(pos, from, to, diff) {
  4882. if (to < pos.line) {
  4883. pos.line += diff;
  4884. } else if (from < pos.line) {
  4885. pos.line = from;
  4886. pos.ch = 0;
  4887. }
  4888. }
  4889. // Tries to rebase an array of history events given a change in the
  4890. // document. If the change touches the same lines as the event, the
  4891. // event, and everything 'behind' it, is discarded. If the change is
  4892. // before the event, the event's positions are updated. Uses a
  4893. // copy-on-write scheme for the positions, to avoid having to
  4894. // reallocate them all on every rebase, but also avoid problems with
  4895. // shared position objects being unsafely updated.
  4896. function rebaseHistArray(array, from, to, diff) {
  4897. for (var i = 0; i < array.length; ++i) {
  4898. var sub = array[i], ok = true;
  4899. if (sub.ranges) {
  4900. if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true; }
  4901. for (var j = 0; j < sub.ranges.length; j++) {
  4902. rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff);
  4903. rebaseHistSelSingle(sub.ranges[j].head, from, to, diff);
  4904. }
  4905. continue
  4906. }
  4907. for (var j$1 = 0; j$1 < sub.changes.length; ++j$1) {
  4908. var cur = sub.changes[j$1];
  4909. if (to < cur.from.line) {
  4910. cur.from = Pos(cur.from.line + diff, cur.from.ch);
  4911. cur.to = Pos(cur.to.line + diff, cur.to.ch);
  4912. } else if (from <= cur.to.line) {
  4913. ok = false;
  4914. break
  4915. }
  4916. }
  4917. if (!ok) {
  4918. array.splice(0, i + 1);
  4919. i = 0;
  4920. }
  4921. }
  4922. }
  4923. function rebaseHist(hist, change) {
  4924. var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1;
  4925. rebaseHistArray(hist.done, from, to, diff);
  4926. rebaseHistArray(hist.undone, from, to, diff);
  4927. }
  4928. // Utility for applying a change to a line by handle or number,
  4929. // returning the number and optionally registering the line as
  4930. // changed.
  4931. function changeLine(doc, handle, changeType, op) {
  4932. var no = handle, line = handle;
  4933. if (typeof handle == "number") { line = getLine(doc, clipLine(doc, handle)); }
  4934. else { no = lineNo(handle); }
  4935. if (no == null) { return null }
  4936. if (op(line, no) && doc.cm) { regLineChange(doc.cm, no, changeType); }
  4937. return line
  4938. }
  4939. // The document is represented as a BTree consisting of leaves, with
  4940. // chunk of lines in them, and branches, with up to ten leaves or
  4941. // other branch nodes below them. The top node is always a branch
  4942. // node, and is the document object itself (meaning it has
  4943. // additional methods and properties).
  4944. //
  4945. // All nodes have parent links. The tree is used both to go from
  4946. // line numbers to line objects, and to go from objects to numbers.
  4947. // It also indexes by height, and is used to convert between height
  4948. // and line object, and to find the total height of the document.
  4949. //
  4950. // See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html
  4951. function LeafChunk(lines) {
  4952. var this$1 = this;
  4953. this.lines = lines;
  4954. this.parent = null;
  4955. var height = 0;
  4956. for (var i = 0; i < lines.length; ++i) {
  4957. lines[i].parent = this$1;
  4958. height += lines[i].height;
  4959. }
  4960. this.height = height;
  4961. }
  4962. LeafChunk.prototype = {
  4963. chunkSize: function chunkSize() { return this.lines.length },
  4964. // Remove the n lines at offset 'at'.
  4965. removeInner: function removeInner(at, n) {
  4966. var this$1 = this;
  4967. for (var i = at, e = at + n; i < e; ++i) {
  4968. var line = this$1.lines[i];
  4969. this$1.height -= line.height;
  4970. cleanUpLine(line);
  4971. signalLater(line, "delete");
  4972. }
  4973. this.lines.splice(at, n);
  4974. },
  4975. // Helper used to collapse a small branch into a single leaf.
  4976. collapse: function collapse(lines) {
  4977. lines.push.apply(lines, this.lines);
  4978. },
  4979. // Insert the given array of lines at offset 'at', count them as
  4980. // having the given height.
  4981. insertInner: function insertInner(at, lines, height) {
  4982. var this$1 = this;
  4983. this.height += height;
  4984. this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at));
  4985. for (var i = 0; i < lines.length; ++i) { lines[i].parent = this$1; }
  4986. },
  4987. // Used to iterate over a part of the tree.
  4988. iterN: function iterN(at, n, op) {
  4989. var this$1 = this;
  4990. for (var e = at + n; at < e; ++at)
  4991. { if (op(this$1.lines[at])) { return true } }
  4992. }
  4993. };
  4994. function BranchChunk(children) {
  4995. var this$1 = this;
  4996. this.children = children;
  4997. var size = 0, height = 0;
  4998. for (var i = 0; i < children.length; ++i) {
  4999. var ch = children[i];
  5000. size += ch.chunkSize(); height += ch.height;
  5001. ch.parent = this$1;
  5002. }
  5003. this.size = size;
  5004. this.height = height;
  5005. this.parent = null;
  5006. }
  5007. BranchChunk.prototype = {
  5008. chunkSize: function chunkSize() { return this.size },
  5009. removeInner: function removeInner(at, n) {
  5010. var this$1 = this;
  5011. this.size -= n;
  5012. for (var i = 0; i < this.children.length; ++i) {
  5013. var child = this$1.children[i], sz = child.chunkSize();
  5014. if (at < sz) {
  5015. var rm = Math.min(n, sz - at), oldHeight = child.height;
  5016. child.removeInner(at, rm);
  5017. this$1.height -= oldHeight - child.height;
  5018. if (sz == rm) { this$1.children.splice(i--, 1); child.parent = null; }
  5019. if ((n -= rm) == 0) { break }
  5020. at = 0;
  5021. } else { at -= sz; }
  5022. }
  5023. // If the result is smaller than 25 lines, ensure that it is a
  5024. // single leaf node.
  5025. if (this.size - n < 25 &&
  5026. (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) {
  5027. var lines = [];
  5028. this.collapse(lines);
  5029. this.children = [new LeafChunk(lines)];
  5030. this.children[0].parent = this;
  5031. }
  5032. },
  5033. collapse: function collapse(lines) {
  5034. var this$1 = this;
  5035. for (var i = 0; i < this.children.length; ++i) { this$1.children[i].collapse(lines); }
  5036. },
  5037. insertInner: function insertInner(at, lines, height) {
  5038. var this$1 = this;
  5039. this.size += lines.length;
  5040. this.height += height;
  5041. for (var i = 0; i < this.children.length; ++i) {
  5042. var child = this$1.children[i], sz = child.chunkSize();
  5043. if (at <= sz) {
  5044. child.insertInner(at, lines, height);
  5045. if (child.lines && child.lines.length > 50) {
  5046. // To avoid memory thrashing when child.lines is huge (e.g. first view of a large file), it's never spliced.
  5047. // Instead, small slices are taken. They're taken in order because sequential memory accesses are fastest.
  5048. var remaining = child.lines.length % 25 + 25;
  5049. for (var pos = remaining; pos < child.lines.length;) {
  5050. var leaf = new LeafChunk(child.lines.slice(pos, pos += 25));
  5051. child.height -= leaf.height;
  5052. this$1.children.splice(++i, 0, leaf);
  5053. leaf.parent = this$1;
  5054. }
  5055. child.lines = child.lines.slice(0, remaining);
  5056. this$1.maybeSpill();
  5057. }
  5058. break
  5059. }
  5060. at -= sz;
  5061. }
  5062. },
  5063. // When a node has grown, check whether it should be split.
  5064. maybeSpill: function maybeSpill() {
  5065. if (this.children.length <= 10) { return }
  5066. var me = this;
  5067. do {
  5068. var spilled = me.children.splice(me.children.length - 5, 5);
  5069. var sibling = new BranchChunk(spilled);
  5070. if (!me.parent) { // Become the parent node
  5071. var copy = new BranchChunk(me.children);
  5072. copy.parent = me;
  5073. me.children = [copy, sibling];
  5074. me = copy;
  5075. } else {
  5076. me.size -= sibling.size;
  5077. me.height -= sibling.height;
  5078. var myIndex = indexOf(me.parent.children, me);
  5079. me.parent.children.splice(myIndex + 1, 0, sibling);
  5080. }
  5081. sibling.parent = me.parent;
  5082. } while (me.children.length > 10)
  5083. me.parent.maybeSpill();
  5084. },
  5085. iterN: function iterN(at, n, op) {
  5086. var this$1 = this;
  5087. for (var i = 0; i < this.children.length; ++i) {
  5088. var child = this$1.children[i], sz = child.chunkSize();
  5089. if (at < sz) {
  5090. var used = Math.min(n, sz - at);
  5091. if (child.iterN(at, used, op)) { return true }
  5092. if ((n -= used) == 0) { break }
  5093. at = 0;
  5094. } else { at -= sz; }
  5095. }
  5096. }
  5097. };
  5098. // Line widgets are block elements displayed above or below a line.
  5099. var LineWidget = function(doc, node, options) {
  5100. var this$1 = this;
  5101. if (options) { for (var opt in options) { if (options.hasOwnProperty(opt))
  5102. { this$1[opt] = options[opt]; } } }
  5103. this.doc = doc;
  5104. this.node = node;
  5105. };
  5106. LineWidget.prototype.clear = function () {
  5107. var this$1 = this;
  5108. var cm = this.doc.cm, ws = this.line.widgets, line = this.line, no = lineNo(line);
  5109. if (no == null || !ws) { return }
  5110. for (var i = 0; i < ws.length; ++i) { if (ws[i] == this$1) { ws.splice(i--, 1); } }
  5111. if (!ws.length) { line.widgets = null; }
  5112. var height = widgetHeight(this);
  5113. updateLineHeight(line, Math.max(0, line.height - height));
  5114. if (cm) {
  5115. runInOp(cm, function () {
  5116. adjustScrollWhenAboveVisible(cm, line, -height);
  5117. regLineChange(cm, no, "widget");
  5118. });
  5119. signalLater(cm, "lineWidgetCleared", cm, this, no);
  5120. }
  5121. };
  5122. LineWidget.prototype.changed = function () {
  5123. var this$1 = this;
  5124. var oldH = this.height, cm = this.doc.cm, line = this.line;
  5125. this.height = null;
  5126. var diff = widgetHeight(this) - oldH;
  5127. if (!diff) { return }
  5128. updateLineHeight(line, line.height + diff);
  5129. if (cm) {
  5130. runInOp(cm, function () {
  5131. cm.curOp.forceUpdate = true;
  5132. adjustScrollWhenAboveVisible(cm, line, diff);
  5133. signalLater(cm, "lineWidgetChanged", cm, this$1, lineNo(line));
  5134. });
  5135. }
  5136. };
  5137. eventMixin(LineWidget);
  5138. function adjustScrollWhenAboveVisible(cm, line, diff) {
  5139. if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop))
  5140. { addToScrollTop(cm, diff); }
  5141. }
  5142. function addLineWidget(doc, handle, node, options) {
  5143. var widget = new LineWidget(doc, node, options);
  5144. var cm = doc.cm;
  5145. if (cm && widget.noHScroll) { cm.display.alignWidgets = true; }
  5146. changeLine(doc, handle, "widget", function (line) {
  5147. var widgets = line.widgets || (line.widgets = []);
  5148. if (widget.insertAt == null) { widgets.push(widget); }
  5149. else { widgets.splice(Math.min(widgets.length - 1, Math.max(0, widget.insertAt)), 0, widget); }
  5150. widget.line = line;
  5151. if (cm && !lineIsHidden(doc, line)) {
  5152. var aboveVisible = heightAtLine(line) < doc.scrollTop;
  5153. updateLineHeight(line, line.height + widgetHeight(widget));
  5154. if (aboveVisible) { addToScrollTop(cm, widget.height); }
  5155. cm.curOp.forceUpdate = true;
  5156. }
  5157. return true
  5158. });
  5159. if (cm) { signalLater(cm, "lineWidgetAdded", cm, widget, typeof handle == "number" ? handle : lineNo(handle)); }
  5160. return widget
  5161. }
  5162. // TEXTMARKERS
  5163. // Created with markText and setBookmark methods. A TextMarker is a
  5164. // handle that can be used to clear or find a marked position in the
  5165. // document. Line objects hold arrays (markedSpans) containing
  5166. // {from, to, marker} object pointing to such marker objects, and
  5167. // indicating that such a marker is present on that line. Multiple
  5168. // lines may point to the same marker when it spans across lines.
  5169. // The spans will have null for their from/to properties when the
  5170. // marker continues beyond the start/end of the line. Markers have
  5171. // links back to the lines they currently touch.
  5172. // Collapsed markers have unique ids, in order to be able to order
  5173. // them, which is needed for uniquely determining an outer marker
  5174. // when they overlap (they may nest, but not partially overlap).
  5175. var nextMarkerId = 0;
  5176. var TextMarker = function(doc, type) {
  5177. this.lines = [];
  5178. this.type = type;
  5179. this.doc = doc;
  5180. this.id = ++nextMarkerId;
  5181. };
  5182. // Clear the marker.
  5183. TextMarker.prototype.clear = function () {
  5184. var this$1 = this;
  5185. if (this.explicitlyCleared) { return }
  5186. var cm = this.doc.cm, withOp = cm && !cm.curOp;
  5187. if (withOp) { startOperation(cm); }
  5188. if (hasHandler(this, "clear")) {
  5189. var found = this.find();
  5190. if (found) { signalLater(this, "clear", found.from, found.to); }
  5191. }
  5192. var min = null, max = null;
  5193. for (var i = 0; i < this.lines.length; ++i) {
  5194. var line = this$1.lines[i];
  5195. var span = getMarkedSpanFor(line.markedSpans, this$1);
  5196. if (cm && !this$1.collapsed) { regLineChange(cm, lineNo(line), "text"); }
  5197. else if (cm) {
  5198. if (span.to != null) { max = lineNo(line); }
  5199. if (span.from != null) { min = lineNo(line); }
  5200. }
  5201. line.markedSpans = removeMarkedSpan(line.markedSpans, span);
  5202. if (span.from == null && this$1.collapsed && !lineIsHidden(this$1.doc, line) && cm)
  5203. { updateLineHeight(line, textHeight(cm.display)); }
  5204. }
  5205. if (cm && this.collapsed && !cm.options.lineWrapping) { for (var i$1 = 0; i$1 < this.lines.length; ++i$1) {
  5206. var visual = visualLine(this$1.lines[i$1]), len = lineLength(visual);
  5207. if (len > cm.display.maxLineLength) {
  5208. cm.display.maxLine = visual;
  5209. cm.display.maxLineLength = len;
  5210. cm.display.maxLineChanged = true;
  5211. }
  5212. } }
  5213. if (min != null && cm && this.collapsed) { regChange(cm, min, max + 1); }
  5214. this.lines.length = 0;
  5215. this.explicitlyCleared = true;
  5216. if (this.atomic && this.doc.cantEdit) {
  5217. this.doc.cantEdit = false;
  5218. if (cm) { reCheckSelection(cm.doc); }
  5219. }
  5220. if (cm) { signalLater(cm, "markerCleared", cm, this, min, max); }
  5221. if (withOp) { endOperation(cm); }
  5222. if (this.parent) { this.parent.clear(); }
  5223. };
  5224. // Find the position of the marker in the document. Returns a {from,
  5225. // to} object by default. Side can be passed to get a specific side
  5226. // -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the
  5227. // Pos objects returned contain a line object, rather than a line
  5228. // number (used to prevent looking up the same line twice).
  5229. TextMarker.prototype.find = function (side, lineObj) {
  5230. var this$1 = this;
  5231. if (side == null && this.type == "bookmark") { side = 1; }
  5232. var from, to;
  5233. for (var i = 0; i < this.lines.length; ++i) {
  5234. var line = this$1.lines[i];
  5235. var span = getMarkedSpanFor(line.markedSpans, this$1);
  5236. if (span.from != null) {
  5237. from = Pos(lineObj ? line : lineNo(line), span.from);
  5238. if (side == -1) { return from }
  5239. }
  5240. if (span.to != null) {
  5241. to = Pos(lineObj ? line : lineNo(line), span.to);
  5242. if (side == 1) { return to }
  5243. }
  5244. }
  5245. return from && {from: from, to: to}
  5246. };
  5247. // Signals that the marker's widget changed, and surrounding layout
  5248. // should be recomputed.
  5249. TextMarker.prototype.changed = function () {
  5250. var this$1 = this;
  5251. var pos = this.find(-1, true), widget = this, cm = this.doc.cm;
  5252. if (!pos || !cm) { return }
  5253. runInOp(cm, function () {
  5254. var line = pos.line, lineN = lineNo(pos.line);
  5255. var view = findViewForLine(cm, lineN);
  5256. if (view) {
  5257. clearLineMeasurementCacheFor(view);
  5258. cm.curOp.selectionChanged = cm.curOp.forceUpdate = true;
  5259. }
  5260. cm.curOp.updateMaxLine = true;
  5261. if (!lineIsHidden(widget.doc, line) && widget.height != null) {
  5262. var oldHeight = widget.height;
  5263. widget.height = null;
  5264. var dHeight = widgetHeight(widget) - oldHeight;
  5265. if (dHeight)
  5266. { updateLineHeight(line, line.height + dHeight); }
  5267. }
  5268. signalLater(cm, "markerChanged", cm, this$1);
  5269. });
  5270. };
  5271. TextMarker.prototype.attachLine = function (line) {
  5272. if (!this.lines.length && this.doc.cm) {
  5273. var op = this.doc.cm.curOp;
  5274. if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1)
  5275. { (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this); }
  5276. }
  5277. this.lines.push(line);
  5278. };
  5279. TextMarker.prototype.detachLine = function (line) {
  5280. this.lines.splice(indexOf(this.lines, line), 1);
  5281. if (!this.lines.length && this.doc.cm) {
  5282. var op = this.doc.cm.curOp;(op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this);
  5283. }
  5284. };
  5285. eventMixin(TextMarker);
  5286. // Create a marker, wire it up to the right lines, and
  5287. function markText(doc, from, to, options, type) {
  5288. // Shared markers (across linked documents) are handled separately
  5289. // (markTextShared will call out to this again, once per
  5290. // document).
  5291. if (options && options.shared) { return markTextShared(doc, from, to, options, type) }
  5292. // Ensure we are in an operation.
  5293. if (doc.cm && !doc.cm.curOp) { return operation(doc.cm, markText)(doc, from, to, options, type) }
  5294. var marker = new TextMarker(doc, type), diff = cmp(from, to);
  5295. if (options) { copyObj(options, marker, false); }
  5296. // Don't connect empty markers unless clearWhenEmpty is false
  5297. if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false)
  5298. { return marker }
  5299. if (marker.replacedWith) {
  5300. // Showing up as a widget implies collapsed (widget replaces text)
  5301. marker.collapsed = true;
  5302. marker.widgetNode = eltP("span", [marker.replacedWith], "CodeMirror-widget");
  5303. if (!options.handleMouseEvents) { marker.widgetNode.setAttribute("cm-ignore-events", "true"); }
  5304. if (options.insertLeft) { marker.widgetNode.insertLeft = true; }
  5305. }
  5306. if (marker.collapsed) {
  5307. if (conflictingCollapsedRange(doc, from.line, from, to, marker) ||
  5308. from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker))
  5309. { throw new Error("Inserting collapsed marker partially overlapping an existing one") }
  5310. seeCollapsedSpans();
  5311. }
  5312. if (marker.addToHistory)
  5313. { addChangeToHistory(doc, {from: from, to: to, origin: "markText"}, doc.sel, NaN); }
  5314. var curLine = from.line, cm = doc.cm, updateMaxLine;
  5315. doc.iter(curLine, to.line + 1, function (line) {
  5316. if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine)
  5317. { updateMaxLine = true; }
  5318. if (marker.collapsed && curLine != from.line) { updateLineHeight(line, 0); }
  5319. addMarkedSpan(line, new MarkedSpan(marker,
  5320. curLine == from.line ? from.ch : null,
  5321. curLine == to.line ? to.ch : null));
  5322. ++curLine;
  5323. });
  5324. // lineIsHidden depends on the presence of the spans, so needs a second pass
  5325. if (marker.collapsed) { doc.iter(from.line, to.line + 1, function (line) {
  5326. if (lineIsHidden(doc, line)) { updateLineHeight(line, 0); }
  5327. }); }
  5328. if (marker.clearOnEnter) { on(marker, "beforeCursorEnter", function () { return marker.clear(); }); }
  5329. if (marker.readOnly) {
  5330. seeReadOnlySpans();
  5331. if (doc.history.done.length || doc.history.undone.length)
  5332. { doc.clearHistory(); }
  5333. }
  5334. if (marker.collapsed) {
  5335. marker.id = ++nextMarkerId;
  5336. marker.atomic = true;
  5337. }
  5338. if (cm) {
  5339. // Sync editor state
  5340. if (updateMaxLine) { cm.curOp.updateMaxLine = true; }
  5341. if (marker.collapsed)
  5342. { regChange(cm, from.line, to.line + 1); }
  5343. else if (marker.className || marker.title || marker.startStyle || marker.endStyle || marker.css)
  5344. { for (var i = from.line; i <= to.line; i++) { regLineChange(cm, i, "text"); } }
  5345. if (marker.atomic) { reCheckSelection(cm.doc); }
  5346. signalLater(cm, "markerAdded", cm, marker);
  5347. }
  5348. return marker
  5349. }
  5350. // SHARED TEXTMARKERS
  5351. // A shared marker spans multiple linked documents. It is
  5352. // implemented as a meta-marker-object controlling multiple normal
  5353. // markers.
  5354. var SharedTextMarker = function(markers, primary) {
  5355. var this$1 = this;
  5356. this.markers = markers;
  5357. this.primary = primary;
  5358. for (var i = 0; i < markers.length; ++i)
  5359. { markers[i].parent = this$1; }
  5360. };
  5361. SharedTextMarker.prototype.clear = function () {
  5362. var this$1 = this;
  5363. if (this.explicitlyCleared) { return }
  5364. this.explicitlyCleared = true;
  5365. for (var i = 0; i < this.markers.length; ++i)
  5366. { this$1.markers[i].clear(); }
  5367. signalLater(this, "clear");
  5368. };
  5369. SharedTextMarker.prototype.find = function (side, lineObj) {
  5370. return this.primary.find(side, lineObj)
  5371. };
  5372. eventMixin(SharedTextMarker);
  5373. function markTextShared(doc, from, to, options, type) {
  5374. options = copyObj(options);
  5375. options.shared = false;
  5376. var markers = [markText(doc, from, to, options, type)], primary = markers[0];
  5377. var widget = options.widgetNode;
  5378. linkedDocs(doc, function (doc) {
  5379. if (widget) { options.widgetNode = widget.cloneNode(true); }
  5380. markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type));
  5381. for (var i = 0; i < doc.linked.length; ++i)
  5382. { if (doc.linked[i].isParent) { return } }
  5383. primary = lst(markers);
  5384. });
  5385. return new SharedTextMarker(markers, primary)
  5386. }
  5387. function findSharedMarkers(doc) {
  5388. return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())), function (m) { return m.parent; })
  5389. }
  5390. function copySharedMarkers(doc, markers) {
  5391. for (var i = 0; i < markers.length; i++) {
  5392. var marker = markers[i], pos = marker.find();
  5393. var mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to);
  5394. if (cmp(mFrom, mTo)) {
  5395. var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type);
  5396. marker.markers.push(subMark);
  5397. subMark.parent = marker;
  5398. }
  5399. }
  5400. }
  5401. function detachSharedMarkers(markers) {
  5402. var loop = function ( i ) {
  5403. var marker = markers[i], linked = [marker.primary.doc];
  5404. linkedDocs(marker.primary.doc, function (d) { return linked.push(d); });
  5405. for (var j = 0; j < marker.markers.length; j++) {
  5406. var subMarker = marker.markers[j];
  5407. if (indexOf(linked, subMarker.doc) == -1) {
  5408. subMarker.parent = null;
  5409. marker.markers.splice(j--, 1);
  5410. }
  5411. }
  5412. };
  5413. for (var i = 0; i < markers.length; i++) loop( i );
  5414. }
  5415. var nextDocId = 0;
  5416. var Doc = function(text, mode, firstLine, lineSep, direction) {
  5417. if (!(this instanceof Doc)) { return new Doc(text, mode, firstLine, lineSep, direction) }
  5418. if (firstLine == null) { firstLine = 0; }
  5419. BranchChunk.call(this, [new LeafChunk([new Line("", null)])]);
  5420. this.first = firstLine;
  5421. this.scrollTop = this.scrollLeft = 0;
  5422. this.cantEdit = false;
  5423. this.cleanGeneration = 1;
  5424. this.modeFrontier = this.highlightFrontier = firstLine;
  5425. var start = Pos(firstLine, 0);
  5426. this.sel = simpleSelection(start);
  5427. this.history = new History(null);
  5428. this.id = ++nextDocId;
  5429. this.modeOption = mode;
  5430. this.lineSep = lineSep;
  5431. this.direction = (direction == "rtl") ? "rtl" : "ltr";
  5432. this.extend = false;
  5433. if (typeof text == "string") { text = this.splitLines(text); }
  5434. updateDoc(this, {from: start, to: start, text: text});
  5435. setSelection(this, simpleSelection(start), sel_dontScroll);
  5436. };
  5437. Doc.prototype = createObj(BranchChunk.prototype, {
  5438. constructor: Doc,
  5439. // Iterate over the document. Supports two forms -- with only one
  5440. // argument, it calls that for each line in the document. With
  5441. // three, it iterates over the range given by the first two (with
  5442. // the second being non-inclusive).
  5443. iter: function(from, to, op) {
  5444. if (op) { this.iterN(from - this.first, to - from, op); }
  5445. else { this.iterN(this.first, this.first + this.size, from); }
  5446. },
  5447. // Non-public interface for adding and removing lines.
  5448. insert: function(at, lines) {
  5449. var height = 0;
  5450. for (var i = 0; i < lines.length; ++i) { height += lines[i].height; }
  5451. this.insertInner(at - this.first, lines, height);
  5452. },
  5453. remove: function(at, n) { this.removeInner(at - this.first, n); },
  5454. // From here, the methods are part of the public interface. Most
  5455. // are also available from CodeMirror (editor) instances.
  5456. getValue: function(lineSep) {
  5457. var lines = getLines(this, this.first, this.first + this.size);
  5458. if (lineSep === false) { return lines }
  5459. return lines.join(lineSep || this.lineSeparator())
  5460. },
  5461. setValue: docMethodOp(function(code) {
  5462. var top = Pos(this.first, 0), last = this.first + this.size - 1;
  5463. makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length),
  5464. text: this.splitLines(code), origin: "setValue", full: true}, true);
  5465. if (this.cm) { scrollToCoords(this.cm, 0, 0); }
  5466. setSelection(this, simpleSelection(top), sel_dontScroll);
  5467. }),
  5468. replaceRange: function(code, from, to, origin) {
  5469. from = clipPos(this, from);
  5470. to = to ? clipPos(this, to) : from;
  5471. replaceRange(this, code, from, to, origin);
  5472. },
  5473. getRange: function(from, to, lineSep) {
  5474. var lines = getBetween(this, clipPos(this, from), clipPos(this, to));
  5475. if (lineSep === false) { return lines }
  5476. return lines.join(lineSep || this.lineSeparator())
  5477. },
  5478. getLine: function(line) {var l = this.getLineHandle(line); return l && l.text},
  5479. getLineHandle: function(line) {if (isLine(this, line)) { return getLine(this, line) }},
  5480. getLineNumber: function(line) {return lineNo(line)},
  5481. getLineHandleVisualStart: function(line) {
  5482. if (typeof line == "number") { line = getLine(this, line); }
  5483. return visualLine(line)
  5484. },
  5485. lineCount: function() {return this.size},
  5486. firstLine: function() {return this.first},
  5487. lastLine: function() {return this.first + this.size - 1},
  5488. clipPos: function(pos) {return clipPos(this, pos)},
  5489. getCursor: function(start) {
  5490. var range$$1 = this.sel.primary(), pos;
  5491. if (start == null || start == "head") { pos = range$$1.head; }
  5492. else if (start == "anchor") { pos = range$$1.anchor; }
  5493. else if (start == "end" || start == "to" || start === false) { pos = range$$1.to(); }
  5494. else { pos = range$$1.from(); }
  5495. return pos
  5496. },
  5497. listSelections: function() { return this.sel.ranges },
  5498. somethingSelected: function() {return this.sel.somethingSelected()},
  5499. setCursor: docMethodOp(function(line, ch, options) {
  5500. setSimpleSelection(this, clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line), null, options);
  5501. }),
  5502. setSelection: docMethodOp(function(anchor, head, options) {
  5503. setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options);
  5504. }),
  5505. extendSelection: docMethodOp(function(head, other, options) {
  5506. extendSelection(this, clipPos(this, head), other && clipPos(this, other), options);
  5507. }),
  5508. extendSelections: docMethodOp(function(heads, options) {
  5509. extendSelections(this, clipPosArray(this, heads), options);
  5510. }),
  5511. extendSelectionsBy: docMethodOp(function(f, options) {
  5512. var heads = map(this.sel.ranges, f);
  5513. extendSelections(this, clipPosArray(this, heads), options);
  5514. }),
  5515. setSelections: docMethodOp(function(ranges, primary, options) {
  5516. var this$1 = this;
  5517. if (!ranges.length) { return }
  5518. var out = [];
  5519. for (var i = 0; i < ranges.length; i++)
  5520. { out[i] = new Range(clipPos(this$1, ranges[i].anchor),
  5521. clipPos(this$1, ranges[i].head)); }
  5522. if (primary == null) { primary = Math.min(ranges.length - 1, this.sel.primIndex); }
  5523. setSelection(this, normalizeSelection(out, primary), options);
  5524. }),
  5525. addSelection: docMethodOp(function(anchor, head, options) {
  5526. var ranges = this.sel.ranges.slice(0);
  5527. ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor)));
  5528. setSelection(this, normalizeSelection(ranges, ranges.length - 1), options);
  5529. }),
  5530. getSelection: function(lineSep) {
  5531. var this$1 = this;
  5532. var ranges = this.sel.ranges, lines;
  5533. for (var i = 0; i < ranges.length; i++) {
  5534. var sel = getBetween(this$1, ranges[i].from(), ranges[i].to());
  5535. lines = lines ? lines.concat(sel) : sel;
  5536. }
  5537. if (lineSep === false) { return lines }
  5538. else { return lines.join(lineSep || this.lineSeparator()) }
  5539. },
  5540. getSelections: function(lineSep) {
  5541. var this$1 = this;
  5542. var parts = [], ranges = this.sel.ranges;
  5543. for (var i = 0; i < ranges.length; i++) {
  5544. var sel = getBetween(this$1, ranges[i].from(), ranges[i].to());
  5545. if (lineSep !== false) { sel = sel.join(lineSep || this$1.lineSeparator()); }
  5546. parts[i] = sel;
  5547. }
  5548. return parts
  5549. },
  5550. replaceSelection: function(code, collapse, origin) {
  5551. var dup = [];
  5552. for (var i = 0; i < this.sel.ranges.length; i++)
  5553. { dup[i] = code; }
  5554. this.replaceSelections(dup, collapse, origin || "+input");
  5555. },
  5556. replaceSelections: docMethodOp(function(code, collapse, origin) {
  5557. var this$1 = this;
  5558. var changes = [], sel = this.sel;
  5559. for (var i = 0; i < sel.ranges.length; i++) {
  5560. var range$$1 = sel.ranges[i];
  5561. changes[i] = {from: range$$1.from(), to: range$$1.to(), text: this$1.splitLines(code[i]), origin: origin};
  5562. }
  5563. var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse);
  5564. for (var i$1 = changes.length - 1; i$1 >= 0; i$1--)
  5565. { makeChange(this$1, changes[i$1]); }
  5566. if (newSel) { setSelectionReplaceHistory(this, newSel); }
  5567. else if (this.cm) { ensureCursorVisible(this.cm); }
  5568. }),
  5569. undo: docMethodOp(function() {makeChangeFromHistory(this, "undo");}),
  5570. redo: docMethodOp(function() {makeChangeFromHistory(this, "redo");}),
  5571. undoSelection: docMethodOp(function() {makeChangeFromHistory(this, "undo", true);}),
  5572. redoSelection: docMethodOp(function() {makeChangeFromHistory(this, "redo", true);}),
  5573. setExtending: function(val) {this.extend = val;},
  5574. getExtending: function() {return this.extend},
  5575. historySize: function() {
  5576. var hist = this.history, done = 0, undone = 0;
  5577. for (var i = 0; i < hist.done.length; i++) { if (!hist.done[i].ranges) { ++done; } }
  5578. for (var i$1 = 0; i$1 < hist.undone.length; i$1++) { if (!hist.undone[i$1].ranges) { ++undone; } }
  5579. return {undo: done, redo: undone}
  5580. },
  5581. clearHistory: function() {this.history = new History(this.history.maxGeneration);},
  5582. markClean: function() {
  5583. this.cleanGeneration = this.changeGeneration(true);
  5584. },
  5585. changeGeneration: function(forceSplit) {
  5586. if (forceSplit)
  5587. { this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null; }
  5588. return this.history.generation
  5589. },
  5590. isClean: function (gen) {
  5591. return this.history.generation == (gen || this.cleanGeneration)
  5592. },
  5593. getHistory: function() {
  5594. return {done: copyHistoryArray(this.history.done),
  5595. undone: copyHistoryArray(this.history.undone)}
  5596. },
  5597. setHistory: function(histData) {
  5598. var hist = this.history = new History(this.history.maxGeneration);
  5599. hist.done = copyHistoryArray(histData.done.slice(0), null, true);
  5600. hist.undone = copyHistoryArray(histData.undone.slice(0), null, true);
  5601. },
  5602. setGutterMarker: docMethodOp(function(line, gutterID, value) {
  5603. return changeLine(this, line, "gutter", function (line) {
  5604. var markers = line.gutterMarkers || (line.gutterMarkers = {});
  5605. markers[gutterID] = value;
  5606. if (!value && isEmpty(markers)) { line.gutterMarkers = null; }
  5607. return true
  5608. })
  5609. }),
  5610. clearGutter: docMethodOp(function(gutterID) {
  5611. var this$1 = this;
  5612. this.iter(function (line) {
  5613. if (line.gutterMarkers && line.gutterMarkers[gutterID]) {
  5614. changeLine(this$1, line, "gutter", function () {
  5615. line.gutterMarkers[gutterID] = null;
  5616. if (isEmpty(line.gutterMarkers)) { line.gutterMarkers = null; }
  5617. return true
  5618. });
  5619. }
  5620. });
  5621. }),
  5622. lineInfo: function(line) {
  5623. var n;
  5624. if (typeof line == "number") {
  5625. if (!isLine(this, line)) { return null }
  5626. n = line;
  5627. line = getLine(this, line);
  5628. if (!line) { return null }
  5629. } else {
  5630. n = lineNo(line);
  5631. if (n == null) { return null }
  5632. }
  5633. return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers,
  5634. textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass,
  5635. widgets: line.widgets}
  5636. },
  5637. addLineClass: docMethodOp(function(handle, where, cls) {
  5638. return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) {
  5639. var prop = where == "text" ? "textClass"
  5640. : where == "background" ? "bgClass"
  5641. : where == "gutter" ? "gutterClass" : "wrapClass";
  5642. if (!line[prop]) { line[prop] = cls; }
  5643. else if (classTest(cls).test(line[prop])) { return false }
  5644. else { line[prop] += " " + cls; }
  5645. return true
  5646. })
  5647. }),
  5648. removeLineClass: docMethodOp(function(handle, where, cls) {
  5649. return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) {
  5650. var prop = where == "text" ? "textClass"
  5651. : where == "background" ? "bgClass"
  5652. : where == "gutter" ? "gutterClass" : "wrapClass";
  5653. var cur = line[prop];
  5654. if (!cur) { return false }
  5655. else if (cls == null) { line[prop] = null; }
  5656. else {
  5657. var found = cur.match(classTest(cls));
  5658. if (!found) { return false }
  5659. var end = found.index + found[0].length;
  5660. line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null;
  5661. }
  5662. return true
  5663. })
  5664. }),
  5665. addLineWidget: docMethodOp(function(handle, node, options) {
  5666. return addLineWidget(this, handle, node, options)
  5667. }),
  5668. removeLineWidget: function(widget) { widget.clear(); },
  5669. markText: function(from, to, options) {
  5670. return markText(this, clipPos(this, from), clipPos(this, to), options, options && options.type || "range")
  5671. },
  5672. setBookmark: function(pos, options) {
  5673. var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options),
  5674. insertLeft: options && options.insertLeft,
  5675. clearWhenEmpty: false, shared: options && options.shared,
  5676. handleMouseEvents: options && options.handleMouseEvents};
  5677. pos = clipPos(this, pos);
  5678. return markText(this, pos, pos, realOpts, "bookmark")
  5679. },
  5680. findMarksAt: function(pos) {
  5681. pos = clipPos(this, pos);
  5682. var markers = [], spans = getLine(this, pos.line).markedSpans;
  5683. if (spans) { for (var i = 0; i < spans.length; ++i) {
  5684. var span = spans[i];
  5685. if ((span.from == null || span.from <= pos.ch) &&
  5686. (span.to == null || span.to >= pos.ch))
  5687. { markers.push(span.marker.parent || span.marker); }
  5688. } }
  5689. return markers
  5690. },
  5691. findMarks: function(from, to, filter) {
  5692. from = clipPos(this, from); to = clipPos(this, to);
  5693. var found = [], lineNo$$1 = from.line;
  5694. this.iter(from.line, to.line + 1, function (line) {
  5695. var spans = line.markedSpans;
  5696. if (spans) { for (var i = 0; i < spans.length; i++) {
  5697. var span = spans[i];
  5698. if (!(span.to != null && lineNo$$1 == from.line && from.ch >= span.to ||
  5699. span.from == null && lineNo$$1 != from.line ||
  5700. span.from != null && lineNo$$1 == to.line && span.from >= to.ch) &&
  5701. (!filter || filter(span.marker)))
  5702. { found.push(span.marker.parent || span.marker); }
  5703. } }
  5704. ++lineNo$$1;
  5705. });
  5706. return found
  5707. },
  5708. getAllMarks: function() {
  5709. var markers = [];
  5710. this.iter(function (line) {
  5711. var sps = line.markedSpans;
  5712. if (sps) { for (var i = 0; i < sps.length; ++i)
  5713. { if (sps[i].from != null) { markers.push(sps[i].marker); } } }
  5714. });
  5715. return markers
  5716. },
  5717. posFromIndex: function(off) {
  5718. var ch, lineNo$$1 = this.first, sepSize = this.lineSeparator().length;
  5719. this.iter(function (line) {
  5720. var sz = line.text.length + sepSize;
  5721. if (sz > off) { ch = off; return true }
  5722. off -= sz;
  5723. ++lineNo$$1;
  5724. });
  5725. return clipPos(this, Pos(lineNo$$1, ch))
  5726. },
  5727. indexFromPos: function (coords) {
  5728. coords = clipPos(this, coords);
  5729. var index = coords.ch;
  5730. if (coords.line < this.first || coords.ch < 0) { return 0 }
  5731. var sepSize = this.lineSeparator().length;
  5732. this.iter(this.first, coords.line, function (line) { // iter aborts when callback returns a truthy value
  5733. index += line.text.length + sepSize;
  5734. });
  5735. return index
  5736. },
  5737. copy: function(copyHistory) {
  5738. var doc = new Doc(getLines(this, this.first, this.first + this.size),
  5739. this.modeOption, this.first, this.lineSep, this.direction);
  5740. doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft;
  5741. doc.sel = this.sel;
  5742. doc.extend = false;
  5743. if (copyHistory) {
  5744. doc.history.undoDepth = this.history.undoDepth;
  5745. doc.setHistory(this.getHistory());
  5746. }
  5747. return doc
  5748. },
  5749. linkedDoc: function(options) {
  5750. if (!options) { options = {}; }
  5751. var from = this.first, to = this.first + this.size;
  5752. if (options.from != null && options.from > from) { from = options.from; }
  5753. if (options.to != null && options.to < to) { to = options.to; }
  5754. var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from, this.lineSep, this.direction);
  5755. if (options.sharedHist) { copy.history = this.history
  5756. ; }(this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist});
  5757. copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}];
  5758. copySharedMarkers(copy, findSharedMarkers(this));
  5759. return copy
  5760. },
  5761. unlinkDoc: function(other) {
  5762. var this$1 = this;
  5763. if (other instanceof CodeMirror$1) { other = other.doc; }
  5764. if (this.linked) { for (var i = 0; i < this.linked.length; ++i) {
  5765. var link = this$1.linked[i];
  5766. if (link.doc != other) { continue }
  5767. this$1.linked.splice(i, 1);
  5768. other.unlinkDoc(this$1);
  5769. detachSharedMarkers(findSharedMarkers(this$1));
  5770. break
  5771. } }
  5772. // If the histories were shared, split them again
  5773. if (other.history == this.history) {
  5774. var splitIds = [other.id];
  5775. linkedDocs(other, function (doc) { return splitIds.push(doc.id); }, true);
  5776. other.history = new History(null);
  5777. other.history.done = copyHistoryArray(this.history.done, splitIds);
  5778. other.history.undone = copyHistoryArray(this.history.undone, splitIds);
  5779. }
  5780. },
  5781. iterLinkedDocs: function(f) {linkedDocs(this, f);},
  5782. getMode: function() {return this.mode},
  5783. getEditor: function() {return this.cm},
  5784. splitLines: function(str) {
  5785. if (this.lineSep) { return str.split(this.lineSep) }
  5786. return splitLinesAuto(str)
  5787. },
  5788. lineSeparator: function() { return this.lineSep || "\n" },
  5789. setDirection: docMethodOp(function (dir) {
  5790. if (dir != "rtl") { dir = "ltr"; }
  5791. if (dir == this.direction) { return }
  5792. this.direction = dir;
  5793. this.iter(function (line) { return line.order = null; });
  5794. if (this.cm) { directionChanged(this.cm); }
  5795. })
  5796. });
  5797. // Public alias.
  5798. Doc.prototype.eachLine = Doc.prototype.iter;
  5799. // Kludge to work around strange IE behavior where it'll sometimes
  5800. // re-fire a series of drag-related events right after the drop (#1551)
  5801. var lastDrop = 0;
  5802. function onDrop(e) {
  5803. var cm = this;
  5804. clearDragCursor(cm);
  5805. if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e))
  5806. { return }
  5807. e_preventDefault(e);
  5808. if (ie) { lastDrop = +new Date; }
  5809. var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files;
  5810. if (!pos || cm.isReadOnly()) { return }
  5811. // Might be a file drop, in which case we simply extract the text
  5812. // and insert it.
  5813. if (files && files.length && window.FileReader && window.File) {
  5814. var n = files.length, text = Array(n), read = 0;
  5815. var loadFile = function (file, i) {
  5816. if (cm.options.allowDropFileTypes &&
  5817. indexOf(cm.options.allowDropFileTypes, file.type) == -1)
  5818. { return }
  5819. var reader = new FileReader;
  5820. reader.onload = operation(cm, function () {
  5821. var content = reader.result;
  5822. if (/[\x00-\x08\x0e-\x1f]{2}/.test(content)) { content = ""; }
  5823. text[i] = content;
  5824. if (++read == n) {
  5825. pos = clipPos(cm.doc, pos);
  5826. var change = {from: pos, to: pos,
  5827. text: cm.doc.splitLines(text.join(cm.doc.lineSeparator())),
  5828. origin: "paste"};
  5829. makeChange(cm.doc, change);
  5830. setSelectionReplaceHistory(cm.doc, simpleSelection(pos, changeEnd(change)));
  5831. }
  5832. });
  5833. reader.readAsText(file);
  5834. };
  5835. for (var i = 0; i < n; ++i) { loadFile(files[i], i); }
  5836. } else { // Normal drop
  5837. // Don't do a replace if the drop happened inside of the selected text.
  5838. if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) {
  5839. cm.state.draggingText(e);
  5840. // Ensure the editor is re-focused
  5841. setTimeout(function () { return cm.display.input.focus(); }, 20);
  5842. return
  5843. }
  5844. try {
  5845. var text$1 = e.dataTransfer.getData("Text");
  5846. if (text$1) {
  5847. var selected;
  5848. if (cm.state.draggingText && !cm.state.draggingText.copy)
  5849. { selected = cm.listSelections(); }
  5850. setSelectionNoUndo(cm.doc, simpleSelection(pos, pos));
  5851. if (selected) { for (var i$1 = 0; i$1 < selected.length; ++i$1)
  5852. { replaceRange(cm.doc, "", selected[i$1].anchor, selected[i$1].head, "drag"); } }
  5853. cm.replaceSelection(text$1, "around", "paste");
  5854. cm.display.input.focus();
  5855. }
  5856. }
  5857. catch(e){}
  5858. }
  5859. }
  5860. function onDragStart(cm, e) {
  5861. if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return }
  5862. if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) { return }
  5863. e.dataTransfer.setData("Text", cm.getSelection());
  5864. e.dataTransfer.effectAllowed = "copyMove";
  5865. // Use dummy image instead of default browsers image.
  5866. // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there.
  5867. if (e.dataTransfer.setDragImage && !safari) {
  5868. var img = elt("img", null, null, "position: fixed; left: 0; top: 0;");
  5869. img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";
  5870. if (presto) {
  5871. img.width = img.height = 1;
  5872. cm.display.wrapper.appendChild(img);
  5873. // Force a relayout, or Opera won't use our image for some obscure reason
  5874. img._top = img.offsetTop;
  5875. }
  5876. e.dataTransfer.setDragImage(img, 0, 0);
  5877. if (presto) { img.parentNode.removeChild(img); }
  5878. }
  5879. }
  5880. function onDragOver(cm, e) {
  5881. var pos = posFromMouse(cm, e);
  5882. if (!pos) { return }
  5883. var frag = document.createDocumentFragment();
  5884. drawSelectionCursor(cm, pos, frag);
  5885. if (!cm.display.dragCursor) {
  5886. cm.display.dragCursor = elt("div", null, "CodeMirror-cursors CodeMirror-dragcursors");
  5887. cm.display.lineSpace.insertBefore(cm.display.dragCursor, cm.display.cursorDiv);
  5888. }
  5889. removeChildrenAndAdd(cm.display.dragCursor, frag);
  5890. }
  5891. function clearDragCursor(cm) {
  5892. if (cm.display.dragCursor) {
  5893. cm.display.lineSpace.removeChild(cm.display.dragCursor);
  5894. cm.display.dragCursor = null;
  5895. }
  5896. }
  5897. // These must be handled carefully, because naively registering a
  5898. // handler for each editor will cause the editors to never be
  5899. // garbage collected.
  5900. function forEachCodeMirror(f) {
  5901. if (!document.getElementsByClassName) { return }
  5902. var byClass = document.getElementsByClassName("CodeMirror");
  5903. for (var i = 0; i < byClass.length; i++) {
  5904. var cm = byClass[i].CodeMirror;
  5905. if (cm) { f(cm); }
  5906. }
  5907. }
  5908. var globalsRegistered = false;
  5909. function ensureGlobalHandlers() {
  5910. if (globalsRegistered) { return }
  5911. registerGlobalHandlers();
  5912. globalsRegistered = true;
  5913. }
  5914. function registerGlobalHandlers() {
  5915. // When the window resizes, we need to refresh active editors.
  5916. var resizeTimer;
  5917. on(window, "resize", function () {
  5918. if (resizeTimer == null) { resizeTimer = setTimeout(function () {
  5919. resizeTimer = null;
  5920. forEachCodeMirror(onResize);
  5921. }, 100); }
  5922. });
  5923. // When the window loses focus, we want to show the editor as blurred
  5924. on(window, "blur", function () { return forEachCodeMirror(onBlur); });
  5925. }
  5926. // Called when the window resizes
  5927. function onResize(cm) {
  5928. var d = cm.display;
  5929. if (d.lastWrapHeight == d.wrapper.clientHeight && d.lastWrapWidth == d.wrapper.clientWidth)
  5930. { return }
  5931. // Might be a text scaling operation, clear size caches.
  5932. d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
  5933. d.scrollbarsClipped = false;
  5934. cm.setSize();
  5935. }
  5936. var keyNames = {
  5937. 3: "Pause", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt",
  5938. 19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End",
  5939. 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert",
  5940. 46: "Delete", 59: ";", 61: "=", 91: "Mod", 92: "Mod", 93: "Mod",
  5941. 106: "*", 107: "=", 109: "-", 110: ".", 111: "/", 127: "Delete", 145: "ScrollLock",
  5942. 173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\",
  5943. 221: "]", 222: "'", 63232: "Up", 63233: "Down", 63234: "Left", 63235: "Right", 63272: "Delete",
  5944. 63273: "Home", 63275: "End", 63276: "PageUp", 63277: "PageDown", 63302: "Insert"
  5945. };
  5946. // Number keys
  5947. for (var i = 0; i < 10; i++) { keyNames[i + 48] = keyNames[i + 96] = String(i); }
  5948. // Alphabetic keys
  5949. for (var i$1 = 65; i$1 <= 90; i$1++) { keyNames[i$1] = String.fromCharCode(i$1); }
  5950. // Function keys
  5951. for (var i$2 = 1; i$2 <= 12; i$2++) { keyNames[i$2 + 111] = keyNames[i$2 + 63235] = "F" + i$2; }
  5952. var keyMap = {};
  5953. keyMap.basic = {
  5954. "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown",
  5955. "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown",
  5956. "Delete": "delCharAfter", "Backspace": "delCharBefore", "Shift-Backspace": "delCharBefore",
  5957. "Tab": "defaultTab", "Shift-Tab": "indentAuto",
  5958. "Enter": "newlineAndIndent", "Insert": "toggleOverwrite",
  5959. "Esc": "singleSelection"
  5960. };
  5961. // Note that the save and find-related commands aren't defined by
  5962. // default. User code or addons can define them. Unknown commands
  5963. // are simply ignored.
  5964. keyMap.pcDefault = {
  5965. "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo",
  5966. "Ctrl-Home": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Up": "goLineUp", "Ctrl-Down": "goLineDown",
  5967. "Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd",
  5968. "Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find",
  5969. "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll",
  5970. "Ctrl-[": "indentLess", "Ctrl-]": "indentMore",
  5971. "Ctrl-U": "undoSelection", "Shift-Ctrl-U": "redoSelection", "Alt-U": "redoSelection",
  5972. fallthrough: "basic"
  5973. };
  5974. // Very basic readline/emacs-style bindings, which are standard on Mac.
  5975. keyMap.emacsy = {
  5976. "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown",
  5977. "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd",
  5978. "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp", "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore",
  5979. "Alt-D": "delWordAfter", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars",
  5980. "Ctrl-O": "openLine"
  5981. };
  5982. keyMap.macDefault = {
  5983. "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo",
  5984. "Cmd-Home": "goDocStart", "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft",
  5985. "Alt-Right": "goGroupRight", "Cmd-Left": "goLineLeft", "Cmd-Right": "goLineRight", "Alt-Backspace": "delGroupBefore",
  5986. "Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find",
  5987. "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll",
  5988. "Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delWrappedLineLeft", "Cmd-Delete": "delWrappedLineRight",
  5989. "Cmd-U": "undoSelection", "Shift-Cmd-U": "redoSelection", "Ctrl-Up": "goDocStart", "Ctrl-Down": "goDocEnd",
  5990. fallthrough: ["basic", "emacsy"]
  5991. };
  5992. keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault;
  5993. // KEYMAP DISPATCH
  5994. function normalizeKeyName(name) {
  5995. var parts = name.split(/-(?!$)/);
  5996. name = parts[parts.length - 1];
  5997. var alt, ctrl, shift, cmd;
  5998. for (var i = 0; i < parts.length - 1; i++) {
  5999. var mod = parts[i];
  6000. if (/^(cmd|meta|m)$/i.test(mod)) { cmd = true; }
  6001. else if (/^a(lt)?$/i.test(mod)) { alt = true; }
  6002. else if (/^(c|ctrl|control)$/i.test(mod)) { ctrl = true; }
  6003. else if (/^s(hift)?$/i.test(mod)) { shift = true; }
  6004. else { throw new Error("Unrecognized modifier name: " + mod) }
  6005. }
  6006. if (alt) { name = "Alt-" + name; }
  6007. if (ctrl) { name = "Ctrl-" + name; }
  6008. if (cmd) { name = "Cmd-" + name; }
  6009. if (shift) { name = "Shift-" + name; }
  6010. return name
  6011. }
  6012. // This is a kludge to keep keymaps mostly working as raw objects
  6013. // (backwards compatibility) while at the same time support features
  6014. // like normalization and multi-stroke key bindings. It compiles a
  6015. // new normalized keymap, and then updates the old object to reflect
  6016. // this.
  6017. function normalizeKeyMap(keymap) {
  6018. var copy = {};
  6019. for (var keyname in keymap) { if (keymap.hasOwnProperty(keyname)) {
  6020. var value = keymap[keyname];
  6021. if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) { continue }
  6022. if (value == "...") { delete keymap[keyname]; continue }
  6023. var keys = map(keyname.split(" "), normalizeKeyName);
  6024. for (var i = 0; i < keys.length; i++) {
  6025. var val = (void 0), name = (void 0);
  6026. if (i == keys.length - 1) {
  6027. name = keys.join(" ");
  6028. val = value;
  6029. } else {
  6030. name = keys.slice(0, i + 1).join(" ");
  6031. val = "...";
  6032. }
  6033. var prev = copy[name];
  6034. if (!prev) { copy[name] = val; }
  6035. else if (prev != val) { throw new Error("Inconsistent bindings for " + name) }
  6036. }
  6037. delete keymap[keyname];
  6038. } }
  6039. for (var prop in copy) { keymap[prop] = copy[prop]; }
  6040. return keymap
  6041. }
  6042. function lookupKey(key, map$$1, handle, context) {
  6043. map$$1 = getKeyMap(map$$1);
  6044. var found = map$$1.call ? map$$1.call(key, context) : map$$1[key];
  6045. if (found === false) { return "nothing" }
  6046. if (found === "...") { return "multi" }
  6047. if (found != null && handle(found)) { return "handled" }
  6048. if (map$$1.fallthrough) {
  6049. if (Object.prototype.toString.call(map$$1.fallthrough) != "[object Array]")
  6050. { return lookupKey(key, map$$1.fallthrough, handle, context) }
  6051. for (var i = 0; i < map$$1.fallthrough.length; i++) {
  6052. var result = lookupKey(key, map$$1.fallthrough[i], handle, context);
  6053. if (result) { return result }
  6054. }
  6055. }
  6056. }
  6057. // Modifier key presses don't count as 'real' key presses for the
  6058. // purpose of keymap fallthrough.
  6059. function isModifierKey(value) {
  6060. var name = typeof value == "string" ? value : keyNames[value.keyCode];
  6061. return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod"
  6062. }
  6063. function addModifierNames(name, event, noShift) {
  6064. var base = name;
  6065. if (event.altKey && base != "Alt") { name = "Alt-" + name; }
  6066. if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != "Ctrl") { name = "Ctrl-" + name; }
  6067. if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != "Cmd") { name = "Cmd-" + name; }
  6068. if (!noShift && event.shiftKey && base != "Shift") { name = "Shift-" + name; }
  6069. return name
  6070. }
  6071. // Look up the name of a key as indicated by an event object.
  6072. function keyName(event, noShift) {
  6073. if (presto && event.keyCode == 34 && event["char"]) { return false }
  6074. var name = keyNames[event.keyCode];
  6075. if (name == null || event.altGraphKey) { return false }
  6076. // Ctrl-ScrollLock has keyCode 3, same as Ctrl-Pause,
  6077. // so we'll use event.code when available (Chrome 48+, FF 38+, Safari 10.1+)
  6078. if (event.keyCode == 3 && event.code) { name = event.code; }
  6079. return addModifierNames(name, event, noShift)
  6080. }
  6081. function getKeyMap(val) {
  6082. return typeof val == "string" ? keyMap[val] : val
  6083. }
  6084. // Helper for deleting text near the selection(s), used to implement
  6085. // backspace, delete, and similar functionality.
  6086. function deleteNearSelection(cm, compute) {
  6087. var ranges = cm.doc.sel.ranges, kill = [];
  6088. // Build up a set of ranges to kill first, merging overlapping
  6089. // ranges.
  6090. for (var i = 0; i < ranges.length; i++) {
  6091. var toKill = compute(ranges[i]);
  6092. while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) {
  6093. var replaced = kill.pop();
  6094. if (cmp(replaced.from, toKill.from) < 0) {
  6095. toKill.from = replaced.from;
  6096. break
  6097. }
  6098. }
  6099. kill.push(toKill);
  6100. }
  6101. // Next, remove those actual ranges.
  6102. runInOp(cm, function () {
  6103. for (var i = kill.length - 1; i >= 0; i--)
  6104. { replaceRange(cm.doc, "", kill[i].from, kill[i].to, "+delete"); }
  6105. ensureCursorVisible(cm);
  6106. });
  6107. }
  6108. function moveCharLogically(line, ch, dir) {
  6109. var target = skipExtendingChars(line.text, ch + dir, dir);
  6110. return target < 0 || target > line.text.length ? null : target
  6111. }
  6112. function moveLogically(line, start, dir) {
  6113. var ch = moveCharLogically(line, start.ch, dir);
  6114. return ch == null ? null : new Pos(start.line, ch, dir < 0 ? "after" : "before")
  6115. }
  6116. function endOfLine(visually, cm, lineObj, lineNo, dir) {
  6117. if (visually) {
  6118. var order = getOrder(lineObj, cm.doc.direction);
  6119. if (order) {
  6120. var part = dir < 0 ? lst(order) : order[0];
  6121. var moveInStorageOrder = (dir < 0) == (part.level == 1);
  6122. var sticky = moveInStorageOrder ? "after" : "before";
  6123. var ch;
  6124. // With a wrapped rtl chunk (possibly spanning multiple bidi parts),
  6125. // it could be that the last bidi part is not on the last visual line,
  6126. // since visual lines contain content order-consecutive chunks.
  6127. // Thus, in rtl, we are looking for the first (content-order) character
  6128. // in the rtl chunk that is on the last line (that is, the same line
  6129. // as the last (content-order) character).
  6130. if (part.level > 0 || cm.doc.direction == "rtl") {
  6131. var prep = prepareMeasureForLine(cm, lineObj);
  6132. ch = dir < 0 ? lineObj.text.length - 1 : 0;
  6133. var targetTop = measureCharPrepared(cm, prep, ch).top;
  6134. ch = findFirst(function (ch) { return measureCharPrepared(cm, prep, ch).top == targetTop; }, (dir < 0) == (part.level == 1) ? part.from : part.to - 1, ch);
  6135. if (sticky == "before") { ch = moveCharLogically(lineObj, ch, 1); }
  6136. } else { ch = dir < 0 ? part.to : part.from; }
  6137. return new Pos(lineNo, ch, sticky)
  6138. }
  6139. }
  6140. return new Pos(lineNo, dir < 0 ? lineObj.text.length : 0, dir < 0 ? "before" : "after")
  6141. }
  6142. function moveVisually(cm, line, start, dir) {
  6143. var bidi = getOrder(line, cm.doc.direction);
  6144. if (!bidi) { return moveLogically(line, start, dir) }
  6145. if (start.ch >= line.text.length) {
  6146. start.ch = line.text.length;
  6147. start.sticky = "before";
  6148. } else if (start.ch <= 0) {
  6149. start.ch = 0;
  6150. start.sticky = "after";
  6151. }
  6152. var partPos = getBidiPartAt(bidi, start.ch, start.sticky), part = bidi[partPos];
  6153. if (cm.doc.direction == "ltr" && part.level % 2 == 0 && (dir > 0 ? part.to > start.ch : part.from < start.ch)) {
  6154. // Case 1: We move within an ltr part in an ltr editor. Even with wrapped lines,
  6155. // nothing interesting happens.
  6156. return moveLogically(line, start, dir)
  6157. }
  6158. var mv = function (pos, dir) { return moveCharLogically(line, pos instanceof Pos ? pos.ch : pos, dir); };
  6159. var prep;
  6160. var getWrappedLineExtent = function (ch) {
  6161. if (!cm.options.lineWrapping) { return {begin: 0, end: line.text.length} }
  6162. prep = prep || prepareMeasureForLine(cm, line);
  6163. return wrappedLineExtentChar(cm, line, prep, ch)
  6164. };
  6165. var wrappedLineExtent = getWrappedLineExtent(start.sticky == "before" ? mv(start, -1) : start.ch);
  6166. if (cm.doc.direction == "rtl" || part.level == 1) {
  6167. var moveInStorageOrder = (part.level == 1) == (dir < 0);
  6168. var ch = mv(start, moveInStorageOrder ? 1 : -1);
  6169. if (ch != null && (!moveInStorageOrder ? ch >= part.from && ch >= wrappedLineExtent.begin : ch <= part.to && ch <= wrappedLineExtent.end)) {
  6170. // Case 2: We move within an rtl part or in an rtl editor on the same visual line
  6171. var sticky = moveInStorageOrder ? "before" : "after";
  6172. return new Pos(start.line, ch, sticky)
  6173. }
  6174. }
  6175. // Case 3: Could not move within this bidi part in this visual line, so leave
  6176. // the current bidi part
  6177. var searchInVisualLine = function (partPos, dir, wrappedLineExtent) {
  6178. var getRes = function (ch, moveInStorageOrder) { return moveInStorageOrder
  6179. ? new Pos(start.line, mv(ch, 1), "before")
  6180. : new Pos(start.line, ch, "after"); };
  6181. for (; partPos >= 0 && partPos < bidi.length; partPos += dir) {
  6182. var part = bidi[partPos];
  6183. var moveInStorageOrder = (dir > 0) == (part.level != 1);
  6184. var ch = moveInStorageOrder ? wrappedLineExtent.begin : mv(wrappedLineExtent.end, -1);
  6185. if (part.from <= ch && ch < part.to) { return getRes(ch, moveInStorageOrder) }
  6186. ch = moveInStorageOrder ? part.from : mv(part.to, -1);
  6187. if (wrappedLineExtent.begin <= ch && ch < wrappedLineExtent.end) { return getRes(ch, moveInStorageOrder) }
  6188. }
  6189. };
  6190. // Case 3a: Look for other bidi parts on the same visual line
  6191. var res = searchInVisualLine(partPos + dir, dir, wrappedLineExtent);
  6192. if (res) { return res }
  6193. // Case 3b: Look for other bidi parts on the next visual line
  6194. var nextCh = dir > 0 ? wrappedLineExtent.end : mv(wrappedLineExtent.begin, -1);
  6195. if (nextCh != null && !(dir > 0 && nextCh == line.text.length)) {
  6196. res = searchInVisualLine(dir > 0 ? 0 : bidi.length - 1, dir, getWrappedLineExtent(nextCh));
  6197. if (res) { return res }
  6198. }
  6199. // Case 4: Nowhere to move
  6200. return null
  6201. }
  6202. // Commands are parameter-less actions that can be performed on an
  6203. // editor, mostly used for keybindings.
  6204. var commands = {
  6205. selectAll: selectAll,
  6206. singleSelection: function (cm) { return cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll); },
  6207. killLine: function (cm) { return deleteNearSelection(cm, function (range) {
  6208. if (range.empty()) {
  6209. var len = getLine(cm.doc, range.head.line).text.length;
  6210. if (range.head.ch == len && range.head.line < cm.lastLine())
  6211. { return {from: range.head, to: Pos(range.head.line + 1, 0)} }
  6212. else
  6213. { return {from: range.head, to: Pos(range.head.line, len)} }
  6214. } else {
  6215. return {from: range.from(), to: range.to()}
  6216. }
  6217. }); },
  6218. deleteLine: function (cm) { return deleteNearSelection(cm, function (range) { return ({
  6219. from: Pos(range.from().line, 0),
  6220. to: clipPos(cm.doc, Pos(range.to().line + 1, 0))
  6221. }); }); },
  6222. delLineLeft: function (cm) { return deleteNearSelection(cm, function (range) { return ({
  6223. from: Pos(range.from().line, 0), to: range.from()
  6224. }); }); },
  6225. delWrappedLineLeft: function (cm) { return deleteNearSelection(cm, function (range) {
  6226. var top = cm.charCoords(range.head, "div").top + 5;
  6227. var leftPos = cm.coordsChar({left: 0, top: top}, "div");
  6228. return {from: leftPos, to: range.from()}
  6229. }); },
  6230. delWrappedLineRight: function (cm) { return deleteNearSelection(cm, function (range) {
  6231. var top = cm.charCoords(range.head, "div").top + 5;
  6232. var rightPos = cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div");
  6233. return {from: range.from(), to: rightPos }
  6234. }); },
  6235. undo: function (cm) { return cm.undo(); },
  6236. redo: function (cm) { return cm.redo(); },
  6237. undoSelection: function (cm) { return cm.undoSelection(); },
  6238. redoSelection: function (cm) { return cm.redoSelection(); },
  6239. goDocStart: function (cm) { return cm.extendSelection(Pos(cm.firstLine(), 0)); },
  6240. goDocEnd: function (cm) { return cm.extendSelection(Pos(cm.lastLine())); },
  6241. goLineStart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStart(cm, range.head.line); },
  6242. {origin: "+move", bias: 1}
  6243. ); },
  6244. goLineStartSmart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStartSmart(cm, range.head); },
  6245. {origin: "+move", bias: 1}
  6246. ); },
  6247. goLineEnd: function (cm) { return cm.extendSelectionsBy(function (range) { return lineEnd(cm, range.head.line); },
  6248. {origin: "+move", bias: -1}
  6249. ); },
  6250. goLineRight: function (cm) { return cm.extendSelectionsBy(function (range) {
  6251. var top = cm.cursorCoords(range.head, "div").top + 5;
  6252. return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div")
  6253. }, sel_move); },
  6254. goLineLeft: function (cm) { return cm.extendSelectionsBy(function (range) {
  6255. var top = cm.cursorCoords(range.head, "div").top + 5;
  6256. return cm.coordsChar({left: 0, top: top}, "div")
  6257. }, sel_move); },
  6258. goLineLeftSmart: function (cm) { return cm.extendSelectionsBy(function (range) {
  6259. var top = cm.cursorCoords(range.head, "div").top + 5;
  6260. var pos = cm.coordsChar({left: 0, top: top}, "div");
  6261. if (pos.ch < cm.getLine(pos.line).search(/\S/)) { return lineStartSmart(cm, range.head) }
  6262. return pos
  6263. }, sel_move); },
  6264. goLineUp: function (cm) { return cm.moveV(-1, "line"); },
  6265. goLineDown: function (cm) { return cm.moveV(1, "line"); },
  6266. goPageUp: function (cm) { return cm.moveV(-1, "page"); },
  6267. goPageDown: function (cm) { return cm.moveV(1, "page"); },
  6268. goCharLeft: function (cm) { return cm.moveH(-1, "char"); },
  6269. goCharRight: function (cm) { return cm.moveH(1, "char"); },
  6270. goColumnLeft: function (cm) { return cm.moveH(-1, "column"); },
  6271. goColumnRight: function (cm) { return cm.moveH(1, "column"); },
  6272. goWordLeft: function (cm) { return cm.moveH(-1, "word"); },
  6273. goGroupRight: function (cm) { return cm.moveH(1, "group"); },
  6274. goGroupLeft: function (cm) { return cm.moveH(-1, "group"); },
  6275. goWordRight: function (cm) { return cm.moveH(1, "word"); },
  6276. delCharBefore: function (cm) { return cm.deleteH(-1, "char"); },
  6277. delCharAfter: function (cm) { return cm.deleteH(1, "char"); },
  6278. delWordBefore: function (cm) { return cm.deleteH(-1, "word"); },
  6279. delWordAfter: function (cm) { return cm.deleteH(1, "word"); },
  6280. delGroupBefore: function (cm) { return cm.deleteH(-1, "group"); },
  6281. delGroupAfter: function (cm) { return cm.deleteH(1, "group"); },
  6282. indentAuto: function (cm) { return cm.indentSelection("smart"); },
  6283. indentMore: function (cm) { return cm.indentSelection("add"); },
  6284. indentLess: function (cm) { return cm.indentSelection("subtract"); },
  6285. insertTab: function (cm) { return cm.replaceSelection("\t"); },
  6286. insertSoftTab: function (cm) {
  6287. var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize;
  6288. for (var i = 0; i < ranges.length; i++) {
  6289. var pos = ranges[i].from();
  6290. var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize);
  6291. spaces.push(spaceStr(tabSize - col % tabSize));
  6292. }
  6293. cm.replaceSelections(spaces);
  6294. },
  6295. defaultTab: function (cm) {
  6296. if (cm.somethingSelected()) { cm.indentSelection("add"); }
  6297. else { cm.execCommand("insertTab"); }
  6298. },
  6299. // Swap the two chars left and right of each selection's head.
  6300. // Move cursor behind the two swapped characters afterwards.
  6301. //
  6302. // Doesn't consider line feeds a character.
  6303. // Doesn't scan more than one line above to find a character.
  6304. // Doesn't do anything on an empty line.
  6305. // Doesn't do anything with non-empty selections.
  6306. transposeChars: function (cm) { return runInOp(cm, function () {
  6307. var ranges = cm.listSelections(), newSel = [];
  6308. for (var i = 0; i < ranges.length; i++) {
  6309. if (!ranges[i].empty()) { continue }
  6310. var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text;
  6311. if (line) {
  6312. if (cur.ch == line.length) { cur = new Pos(cur.line, cur.ch - 1); }
  6313. if (cur.ch > 0) {
  6314. cur = new Pos(cur.line, cur.ch + 1);
  6315. cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2),
  6316. Pos(cur.line, cur.ch - 2), cur, "+transpose");
  6317. } else if (cur.line > cm.doc.first) {
  6318. var prev = getLine(cm.doc, cur.line - 1).text;
  6319. if (prev) {
  6320. cur = new Pos(cur.line, 1);
  6321. cm.replaceRange(line.charAt(0) + cm.doc.lineSeparator() +
  6322. prev.charAt(prev.length - 1),
  6323. Pos(cur.line - 1, prev.length - 1), cur, "+transpose");
  6324. }
  6325. }
  6326. }
  6327. newSel.push(new Range(cur, cur));
  6328. }
  6329. cm.setSelections(newSel);
  6330. }); },
  6331. newlineAndIndent: function (cm) { return runInOp(cm, function () {
  6332. var sels = cm.listSelections();
  6333. for (var i = sels.length - 1; i >= 0; i--)
  6334. { cm.replaceRange(cm.doc.lineSeparator(), sels[i].anchor, sels[i].head, "+input"); }
  6335. sels = cm.listSelections();
  6336. for (var i$1 = 0; i$1 < sels.length; i$1++)
  6337. { cm.indentLine(sels[i$1].from().line, null, true); }
  6338. ensureCursorVisible(cm);
  6339. }); },
  6340. openLine: function (cm) { return cm.replaceSelection("\n", "start"); },
  6341. toggleOverwrite: function (cm) { return cm.toggleOverwrite(); }
  6342. };
  6343. function lineStart(cm, lineN) {
  6344. var line = getLine(cm.doc, lineN);
  6345. var visual = visualLine(line);
  6346. if (visual != line) { lineN = lineNo(visual); }
  6347. return endOfLine(true, cm, visual, lineN, 1)
  6348. }
  6349. function lineEnd(cm, lineN) {
  6350. var line = getLine(cm.doc, lineN);
  6351. var visual = visualLineEnd(line);
  6352. if (visual != line) { lineN = lineNo(visual); }
  6353. return endOfLine(true, cm, line, lineN, -1)
  6354. }
  6355. function lineStartSmart(cm, pos) {
  6356. var start = lineStart(cm, pos.line);
  6357. var line = getLine(cm.doc, start.line);
  6358. var order = getOrder(line, cm.doc.direction);
  6359. if (!order || order[0].level == 0) {
  6360. var firstNonWS = Math.max(0, line.text.search(/\S/));
  6361. var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch;
  6362. return Pos(start.line, inWS ? 0 : firstNonWS, start.sticky)
  6363. }
  6364. return start
  6365. }
  6366. // Run a handler that was bound to a key.
  6367. function doHandleBinding(cm, bound, dropShift) {
  6368. if (typeof bound == "string") {
  6369. bound = commands[bound];
  6370. if (!bound) { return false }
  6371. }
  6372. // Ensure previous input has been read, so that the handler sees a
  6373. // consistent view of the document
  6374. cm.display.input.ensurePolled();
  6375. var prevShift = cm.display.shift, done = false;
  6376. try {
  6377. if (cm.isReadOnly()) { cm.state.suppressEdits = true; }
  6378. if (dropShift) { cm.display.shift = false; }
  6379. done = bound(cm) != Pass;
  6380. } finally {
  6381. cm.display.shift = prevShift;
  6382. cm.state.suppressEdits = false;
  6383. }
  6384. return done
  6385. }
  6386. function lookupKeyForEditor(cm, name, handle) {
  6387. for (var i = 0; i < cm.state.keyMaps.length; i++) {
  6388. var result = lookupKey(name, cm.state.keyMaps[i], handle, cm);
  6389. if (result) { return result }
  6390. }
  6391. return (cm.options.extraKeys && lookupKey(name, cm.options.extraKeys, handle, cm))
  6392. || lookupKey(name, cm.options.keyMap, handle, cm)
  6393. }
  6394. // Note that, despite the name, this function is also used to check
  6395. // for bound mouse clicks.
  6396. var stopSeq = new Delayed;
  6397. function dispatchKey(cm, name, e, handle) {
  6398. var seq = cm.state.keySeq;
  6399. if (seq) {
  6400. if (isModifierKey(name)) { return "handled" }
  6401. if (/\'$/.test(name))
  6402. { cm.state.keySeq = null; }
  6403. else
  6404. { stopSeq.set(50, function () {
  6405. if (cm.state.keySeq == seq) {
  6406. cm.state.keySeq = null;
  6407. cm.display.input.reset();
  6408. }
  6409. }); }
  6410. if (dispatchKeyInner(cm, seq + " " + name, e, handle)) { return true }
  6411. }
  6412. return dispatchKeyInner(cm, name, e, handle)
  6413. }
  6414. function dispatchKeyInner(cm, name, e, handle) {
  6415. var result = lookupKeyForEditor(cm, name, handle);
  6416. if (result == "multi")
  6417. { cm.state.keySeq = name; }
  6418. if (result == "handled")
  6419. { signalLater(cm, "keyHandled", cm, name, e); }
  6420. if (result == "handled" || result == "multi") {
  6421. e_preventDefault(e);
  6422. restartBlink(cm);
  6423. }
  6424. return !!result
  6425. }
  6426. // Handle a key from the keydown event.
  6427. function handleKeyBinding(cm, e) {
  6428. var name = keyName(e, true);
  6429. if (!name) { return false }
  6430. if (e.shiftKey && !cm.state.keySeq) {
  6431. // First try to resolve full name (including 'Shift-'). Failing
  6432. // that, see if there is a cursor-motion command (starting with
  6433. // 'go') bound to the keyname without 'Shift-'.
  6434. return dispatchKey(cm, "Shift-" + name, e, function (b) { return doHandleBinding(cm, b, true); })
  6435. || dispatchKey(cm, name, e, function (b) {
  6436. if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion)
  6437. { return doHandleBinding(cm, b) }
  6438. })
  6439. } else {
  6440. return dispatchKey(cm, name, e, function (b) { return doHandleBinding(cm, b); })
  6441. }
  6442. }
  6443. // Handle a key from the keypress event
  6444. function handleCharBinding(cm, e, ch) {
  6445. return dispatchKey(cm, "'" + ch + "'", e, function (b) { return doHandleBinding(cm, b, true); })
  6446. }
  6447. var lastStoppedKey = null;
  6448. function onKeyDown(e) {
  6449. var cm = this;
  6450. cm.curOp.focus = activeElt();
  6451. if (signalDOMEvent(cm, e)) { return }
  6452. // IE does strange things with escape.
  6453. if (ie && ie_version < 11 && e.keyCode == 27) { e.returnValue = false; }
  6454. var code = e.keyCode;
  6455. cm.display.shift = code == 16 || e.shiftKey;
  6456. var handled = handleKeyBinding(cm, e);
  6457. if (presto) {
  6458. lastStoppedKey = handled ? code : null;
  6459. // Opera has no cut event... we try to at least catch the key combo
  6460. if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey))
  6461. { cm.replaceSelection("", null, "cut"); }
  6462. }
  6463. // Turn mouse into crosshair when Alt is held on Mac.
  6464. if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className))
  6465. { showCrossHair(cm); }
  6466. }
  6467. function showCrossHair(cm) {
  6468. var lineDiv = cm.display.lineDiv;
  6469. addClass(lineDiv, "CodeMirror-crosshair");
  6470. function up(e) {
  6471. if (e.keyCode == 18 || !e.altKey) {
  6472. rmClass(lineDiv, "CodeMirror-crosshair");
  6473. off(document, "keyup", up);
  6474. off(document, "mouseover", up);
  6475. }
  6476. }
  6477. on(document, "keyup", up);
  6478. on(document, "mouseover", up);
  6479. }
  6480. function onKeyUp(e) {
  6481. if (e.keyCode == 16) { this.doc.sel.shift = false; }
  6482. signalDOMEvent(this, e);
  6483. }
  6484. function onKeyPress(e) {
  6485. var cm = this;
  6486. if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) { return }
  6487. var keyCode = e.keyCode, charCode = e.charCode;
  6488. if (presto && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return}
  6489. if ((presto && (!e.which || e.which < 10)) && handleKeyBinding(cm, e)) { return }
  6490. var ch = String.fromCharCode(charCode == null ? keyCode : charCode);
  6491. // Some browsers fire keypress events for backspace
  6492. if (ch == "\x08") { return }
  6493. if (handleCharBinding(cm, e, ch)) { return }
  6494. cm.display.input.onKeyPress(e);
  6495. }
  6496. var DOUBLECLICK_DELAY = 400;
  6497. var PastClick = function(time, pos, button) {
  6498. this.time = time;
  6499. this.pos = pos;
  6500. this.button = button;
  6501. };
  6502. PastClick.prototype.compare = function (time, pos, button) {
  6503. return this.time + DOUBLECLICK_DELAY > time &&
  6504. cmp(pos, this.pos) == 0 && button == this.button
  6505. };
  6506. var lastClick;
  6507. var lastDoubleClick;
  6508. function clickRepeat(pos, button) {
  6509. var now = +new Date;
  6510. if (lastDoubleClick && lastDoubleClick.compare(now, pos, button)) {
  6511. lastClick = lastDoubleClick = null;
  6512. return "triple"
  6513. } else if (lastClick && lastClick.compare(now, pos, button)) {
  6514. lastDoubleClick = new PastClick(now, pos, button);
  6515. lastClick = null;
  6516. return "double"
  6517. } else {
  6518. lastClick = new PastClick(now, pos, button);
  6519. lastDoubleClick = null;
  6520. return "single"
  6521. }
  6522. }
  6523. // A mouse down can be a single click, double click, triple click,
  6524. // start of selection drag, start of text drag, new cursor
  6525. // (ctrl-click), rectangle drag (alt-drag), or xwin
  6526. // middle-click-paste. Or it might be a click on something we should
  6527. // not interfere with, such as a scrollbar or widget.
  6528. function onMouseDown(e) {
  6529. var cm = this, display = cm.display;
  6530. if (signalDOMEvent(cm, e) || display.activeTouch && display.input.supportsTouch()) { return }
  6531. display.input.ensurePolled();
  6532. display.shift = e.shiftKey;
  6533. if (eventInWidget(display, e)) {
  6534. if (!webkit) {
  6535. // Briefly turn off draggability, to allow widgets to do
  6536. // normal dragging things.
  6537. display.scroller.draggable = false;
  6538. setTimeout(function () { return display.scroller.draggable = true; }, 100);
  6539. }
  6540. return
  6541. }
  6542. if (clickInGutter(cm, e)) { return }
  6543. var pos = posFromMouse(cm, e), button = e_button(e), repeat = pos ? clickRepeat(pos, button) : "single";
  6544. window.focus();
  6545. // #3261: make sure, that we're not starting a second selection
  6546. if (button == 1 && cm.state.selectingText)
  6547. { cm.state.selectingText(e); }
  6548. if (pos && handleMappedButton(cm, button, pos, repeat, e)) { return }
  6549. if (button == 1) {
  6550. if (pos) { leftButtonDown(cm, pos, repeat, e); }
  6551. else if (e_target(e) == display.scroller) { e_preventDefault(e); }
  6552. } else if (button == 2) {
  6553. if (pos) { extendSelection(cm.doc, pos); }
  6554. setTimeout(function () { return display.input.focus(); }, 20);
  6555. } else if (button == 3) {
  6556. if (captureRightClick) { onContextMenu(cm, e); }
  6557. else { delayBlurEvent(cm); }
  6558. }
  6559. }
  6560. function handleMappedButton(cm, button, pos, repeat, event) {
  6561. var name = "Click";
  6562. if (repeat == "double") { name = "Double" + name; }
  6563. else if (repeat == "triple") { name = "Triple" + name; }
  6564. name = (button == 1 ? "Left" : button == 2 ? "Middle" : "Right") + name;
  6565. return dispatchKey(cm, addModifierNames(name, event), event, function (bound) {
  6566. if (typeof bound == "string") { bound = commands[bound]; }
  6567. if (!bound) { return false }
  6568. var done = false;
  6569. try {
  6570. if (cm.isReadOnly()) { cm.state.suppressEdits = true; }
  6571. done = bound(cm, pos) != Pass;
  6572. } finally {
  6573. cm.state.suppressEdits = false;
  6574. }
  6575. return done
  6576. })
  6577. }
  6578. function configureMouse(cm, repeat, event) {
  6579. var option = cm.getOption("configureMouse");
  6580. var value = option ? option(cm, repeat, event) : {};
  6581. if (value.unit == null) {
  6582. var rect = chromeOS ? event.shiftKey && event.metaKey : event.altKey;
  6583. value.unit = rect ? "rectangle" : repeat == "single" ? "char" : repeat == "double" ? "word" : "line";
  6584. }
  6585. if (value.extend == null || cm.doc.extend) { value.extend = cm.doc.extend || event.shiftKey; }
  6586. if (value.addNew == null) { value.addNew = mac ? event.metaKey : event.ctrlKey; }
  6587. if (value.moveOnDrag == null) { value.moveOnDrag = !(mac ? event.altKey : event.ctrlKey); }
  6588. return value
  6589. }
  6590. function leftButtonDown(cm, pos, repeat, event) {
  6591. if (ie) { setTimeout(bind(ensureFocus, cm), 0); }
  6592. else { cm.curOp.focus = activeElt(); }
  6593. var behavior = configureMouse(cm, repeat, event);
  6594. var sel = cm.doc.sel, contained;
  6595. if (cm.options.dragDrop && dragAndDrop && !cm.isReadOnly() &&
  6596. repeat == "single" && (contained = sel.contains(pos)) > -1 &&
  6597. (cmp((contained = sel.ranges[contained]).from(), pos) < 0 || pos.xRel > 0) &&
  6598. (cmp(contained.to(), pos) > 0 || pos.xRel < 0))
  6599. { leftButtonStartDrag(cm, event, pos, behavior); }
  6600. else
  6601. { leftButtonSelect(cm, event, pos, behavior); }
  6602. }
  6603. // Start a text drag. When it ends, see if any dragging actually
  6604. // happen, and treat as a click if it didn't.
  6605. function leftButtonStartDrag(cm, event, pos, behavior) {
  6606. var display = cm.display, moved = false;
  6607. var dragEnd = operation(cm, function (e) {
  6608. if (webkit) { display.scroller.draggable = false; }
  6609. cm.state.draggingText = false;
  6610. off(document, "mouseup", dragEnd);
  6611. off(document, "mousemove", mouseMove);
  6612. off(display.scroller, "dragstart", dragStart);
  6613. off(display.scroller, "drop", dragEnd);
  6614. if (!moved) {
  6615. e_preventDefault(e);
  6616. if (!behavior.addNew)
  6617. { extendSelection(cm.doc, pos, null, null, behavior.extend); }
  6618. // Work around unexplainable focus problem in IE9 (#2127) and Chrome (#3081)
  6619. if (webkit || ie && ie_version == 9)
  6620. { setTimeout(function () {document.body.focus(); display.input.focus();}, 20); }
  6621. else
  6622. { display.input.focus(); }
  6623. }
  6624. });
  6625. var mouseMove = function(e2) {
  6626. moved = moved || Math.abs(event.clientX - e2.clientX) + Math.abs(event.clientY - e2.clientY) >= 10;
  6627. };
  6628. var dragStart = function () { return moved = true; };
  6629. // Let the drag handler handle this.
  6630. if (webkit) { display.scroller.draggable = true; }
  6631. cm.state.draggingText = dragEnd;
  6632. dragEnd.copy = !behavior.moveOnDrag;
  6633. // IE's approach to draggable
  6634. if (display.scroller.dragDrop) { display.scroller.dragDrop(); }
  6635. on(document, "mouseup", dragEnd);
  6636. on(document, "mousemove", mouseMove);
  6637. on(display.scroller, "dragstart", dragStart);
  6638. on(display.scroller, "drop", dragEnd);
  6639. delayBlurEvent(cm);
  6640. setTimeout(function () { return display.input.focus(); }, 20);
  6641. }
  6642. function rangeForUnit(cm, pos, unit) {
  6643. if (unit == "char") { return new Range(pos, pos) }
  6644. if (unit == "word") { return cm.findWordAt(pos) }
  6645. if (unit == "line") { return new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))) }
  6646. var result = unit(cm, pos);
  6647. return new Range(result.from, result.to)
  6648. }
  6649. // Normal selection, as opposed to text dragging.
  6650. function leftButtonSelect(cm, event, start, behavior) {
  6651. var display = cm.display, doc = cm.doc;
  6652. e_preventDefault(event);
  6653. var ourRange, ourIndex, startSel = doc.sel, ranges = startSel.ranges;
  6654. if (behavior.addNew && !behavior.extend) {
  6655. ourIndex = doc.sel.contains(start);
  6656. if (ourIndex > -1)
  6657. { ourRange = ranges[ourIndex]; }
  6658. else
  6659. { ourRange = new Range(start, start); }
  6660. } else {
  6661. ourRange = doc.sel.primary();
  6662. ourIndex = doc.sel.primIndex;
  6663. }
  6664. if (behavior.unit == "rectangle") {
  6665. if (!behavior.addNew) { ourRange = new Range(start, start); }
  6666. start = posFromMouse(cm, event, true, true);
  6667. ourIndex = -1;
  6668. } else {
  6669. var range$$1 = rangeForUnit(cm, start, behavior.unit);
  6670. if (behavior.extend)
  6671. { ourRange = extendRange(ourRange, range$$1.anchor, range$$1.head, behavior.extend); }
  6672. else
  6673. { ourRange = range$$1; }
  6674. }
  6675. if (!behavior.addNew) {
  6676. ourIndex = 0;
  6677. setSelection(doc, new Selection([ourRange], 0), sel_mouse);
  6678. startSel = doc.sel;
  6679. } else if (ourIndex == -1) {
  6680. ourIndex = ranges.length;
  6681. setSelection(doc, normalizeSelection(ranges.concat([ourRange]), ourIndex),
  6682. {scroll: false, origin: "*mouse"});
  6683. } else if (ranges.length > 1 && ranges[ourIndex].empty() && behavior.unit == "char" && !behavior.extend) {
  6684. setSelection(doc, normalizeSelection(ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0),
  6685. {scroll: false, origin: "*mouse"});
  6686. startSel = doc.sel;
  6687. } else {
  6688. replaceOneSelection(doc, ourIndex, ourRange, sel_mouse);
  6689. }
  6690. var lastPos = start;
  6691. function extendTo(pos) {
  6692. if (cmp(lastPos, pos) == 0) { return }
  6693. lastPos = pos;
  6694. if (behavior.unit == "rectangle") {
  6695. var ranges = [], tabSize = cm.options.tabSize;
  6696. var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize);
  6697. var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize);
  6698. var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol);
  6699. for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line));
  6700. line <= end; line++) {
  6701. var text = getLine(doc, line).text, leftPos = findColumn(text, left, tabSize);
  6702. if (left == right)
  6703. { ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos))); }
  6704. else if (text.length > leftPos)
  6705. { ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize)))); }
  6706. }
  6707. if (!ranges.length) { ranges.push(new Range(start, start)); }
  6708. setSelection(doc, normalizeSelection(startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex),
  6709. {origin: "*mouse", scroll: false});
  6710. cm.scrollIntoView(pos);
  6711. } else {
  6712. var oldRange = ourRange;
  6713. var range$$1 = rangeForUnit(cm, pos, behavior.unit);
  6714. var anchor = oldRange.anchor, head;
  6715. if (cmp(range$$1.anchor, anchor) > 0) {
  6716. head = range$$1.head;
  6717. anchor = minPos(oldRange.from(), range$$1.anchor);
  6718. } else {
  6719. head = range$$1.anchor;
  6720. anchor = maxPos(oldRange.to(), range$$1.head);
  6721. }
  6722. var ranges$1 = startSel.ranges.slice(0);
  6723. ranges$1[ourIndex] = bidiSimplify(cm, new Range(clipPos(doc, anchor), head));
  6724. setSelection(doc, normalizeSelection(ranges$1, ourIndex), sel_mouse);
  6725. }
  6726. }
  6727. var editorSize = display.wrapper.getBoundingClientRect();
  6728. // Used to ensure timeout re-tries don't fire when another extend
  6729. // happened in the meantime (clearTimeout isn't reliable -- at
  6730. // least on Chrome, the timeouts still happen even when cleared,
  6731. // if the clear happens after their scheduled firing time).
  6732. var counter = 0;
  6733. function extend(e) {
  6734. var curCount = ++counter;
  6735. var cur = posFromMouse(cm, e, true, behavior.unit == "rectangle");
  6736. if (!cur) { return }
  6737. if (cmp(cur, lastPos) != 0) {
  6738. cm.curOp.focus = activeElt();
  6739. extendTo(cur);
  6740. var visible = visibleLines(display, doc);
  6741. if (cur.line >= visible.to || cur.line < visible.from)
  6742. { setTimeout(operation(cm, function () {if (counter == curCount) { extend(e); }}), 150); }
  6743. } else {
  6744. var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0;
  6745. if (outside) { setTimeout(operation(cm, function () {
  6746. if (counter != curCount) { return }
  6747. display.scroller.scrollTop += outside;
  6748. extend(e);
  6749. }), 50); }
  6750. }
  6751. }
  6752. function done(e) {
  6753. cm.state.selectingText = false;
  6754. counter = Infinity;
  6755. e_preventDefault(e);
  6756. display.input.focus();
  6757. off(document, "mousemove", move);
  6758. off(document, "mouseup", up);
  6759. doc.history.lastSelOrigin = null;
  6760. }
  6761. var move = operation(cm, function (e) {
  6762. if (!e_button(e)) { done(e); }
  6763. else { extend(e); }
  6764. });
  6765. var up = operation(cm, done);
  6766. cm.state.selectingText = up;
  6767. on(document, "mousemove", move);
  6768. on(document, "mouseup", up);
  6769. }
  6770. // Used when mouse-selecting to adjust the anchor to the proper side
  6771. // of a bidi jump depending on the visual position of the head.
  6772. function bidiSimplify(cm, range$$1) {
  6773. var anchor = range$$1.anchor;
  6774. var head = range$$1.head;
  6775. var anchorLine = getLine(cm.doc, anchor.line);
  6776. if (cmp(anchor, head) == 0 && anchor.sticky == head.sticky) { return range$$1 }
  6777. var order = getOrder(anchorLine);
  6778. if (!order) { return range$$1 }
  6779. var index = getBidiPartAt(order, anchor.ch, anchor.sticky), part = order[index];
  6780. if (part.from != anchor.ch && part.to != anchor.ch) { return range$$1 }
  6781. var boundary = index + ((part.from == anchor.ch) == (part.level != 1) ? 0 : 1);
  6782. if (boundary == 0 || boundary == order.length) { return range$$1 }
  6783. // Compute the relative visual position of the head compared to the
  6784. // anchor (<0 is to the left, >0 to the right)
  6785. var leftSide;
  6786. if (head.line != anchor.line) {
  6787. leftSide = (head.line - anchor.line) * (cm.doc.direction == "ltr" ? 1 : -1) > 0;
  6788. } else {
  6789. var headIndex = getBidiPartAt(order, head.ch, head.sticky);
  6790. var dir = headIndex - index || (head.ch - anchor.ch) * (part.level == 1 ? -1 : 1);
  6791. if (headIndex == boundary - 1 || headIndex == boundary)
  6792. { leftSide = dir < 0; }
  6793. else
  6794. { leftSide = dir > 0; }
  6795. }
  6796. var usePart = order[boundary + (leftSide ? -1 : 0)];
  6797. var from = leftSide == (usePart.level == 1);
  6798. var ch = from ? usePart.from : usePart.to, sticky = from ? "after" : "before";
  6799. return anchor.ch == ch && anchor.sticky == sticky ? range$$1 : new Range(new Pos(anchor.line, ch, sticky), head)
  6800. }
  6801. // Determines whether an event happened in the gutter, and fires the
  6802. // handlers for the corresponding event.
  6803. function gutterEvent(cm, e, type, prevent) {
  6804. var mX, mY;
  6805. if (e.touches) {
  6806. mX = e.touches[0].clientX;
  6807. mY = e.touches[0].clientY;
  6808. } else {
  6809. try { mX = e.clientX; mY = e.clientY; }
  6810. catch(e) { return false }
  6811. }
  6812. if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) { return false }
  6813. if (prevent) { e_preventDefault(e); }
  6814. var display = cm.display;
  6815. var lineBox = display.lineDiv.getBoundingClientRect();
  6816. if (mY > lineBox.bottom || !hasHandler(cm, type)) { return e_defaultPrevented(e) }
  6817. mY -= lineBox.top - display.viewOffset;
  6818. for (var i = 0; i < cm.options.gutters.length; ++i) {
  6819. var g = display.gutters.childNodes[i];
  6820. if (g && g.getBoundingClientRect().right >= mX) {
  6821. var line = lineAtHeight(cm.doc, mY);
  6822. var gutter = cm.options.gutters[i];
  6823. signal(cm, type, cm, line, gutter, e);
  6824. return e_defaultPrevented(e)
  6825. }
  6826. }
  6827. }
  6828. function clickInGutter(cm, e) {
  6829. return gutterEvent(cm, e, "gutterClick", true)
  6830. }
  6831. // CONTEXT MENU HANDLING
  6832. // To make the context menu work, we need to briefly unhide the
  6833. // textarea (making it as unobtrusive as possible) to let the
  6834. // right-click take effect on it.
  6835. function onContextMenu(cm, e) {
  6836. if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) { return }
  6837. if (signalDOMEvent(cm, e, "contextmenu")) { return }
  6838. cm.display.input.onContextMenu(e);
  6839. }
  6840. function contextMenuInGutter(cm, e) {
  6841. if (!hasHandler(cm, "gutterContextMenu")) { return false }
  6842. return gutterEvent(cm, e, "gutterContextMenu", false)
  6843. }
  6844. function themeChanged(cm) {
  6845. cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") +
  6846. cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-");
  6847. clearCaches(cm);
  6848. }
  6849. var Init = {toString: function(){return "CodeMirror.Init"}};
  6850. var defaults = {};
  6851. var optionHandlers = {};
  6852. function defineOptions(CodeMirror) {
  6853. var optionHandlers = CodeMirror.optionHandlers;
  6854. function option(name, deflt, handle, notOnInit) {
  6855. CodeMirror.defaults[name] = deflt;
  6856. if (handle) { optionHandlers[name] =
  6857. notOnInit ? function (cm, val, old) {if (old != Init) { handle(cm, val, old); }} : handle; }
  6858. }
  6859. CodeMirror.defineOption = option;
  6860. // Passed to option handlers when there is no old value.
  6861. CodeMirror.Init = Init;
  6862. // These two are, on init, called from the constructor because they
  6863. // have to be initialized before the editor can start at all.
  6864. option("value", "", function (cm, val) { return cm.setValue(val); }, true);
  6865. option("mode", null, function (cm, val) {
  6866. cm.doc.modeOption = val;
  6867. loadMode(cm);
  6868. }, true);
  6869. option("indentUnit", 2, loadMode, true);
  6870. option("indentWithTabs", false);
  6871. option("smartIndent", true);
  6872. option("tabSize", 4, function (cm) {
  6873. resetModeState(cm);
  6874. clearCaches(cm);
  6875. regChange(cm);
  6876. }, true);
  6877. option("lineSeparator", null, function (cm, val) {
  6878. cm.doc.lineSep = val;
  6879. if (!val) { return }
  6880. var newBreaks = [], lineNo = cm.doc.first;
  6881. cm.doc.iter(function (line) {
  6882. for (var pos = 0;;) {
  6883. var found = line.text.indexOf(val, pos);
  6884. if (found == -1) { break }
  6885. pos = found + val.length;
  6886. newBreaks.push(Pos(lineNo, found));
  6887. }
  6888. lineNo++;
  6889. });
  6890. for (var i = newBreaks.length - 1; i >= 0; i--)
  6891. { replaceRange(cm.doc, val, newBreaks[i], Pos(newBreaks[i].line, newBreaks[i].ch + val.length)); }
  6892. });
  6893. option("specialChars", /[\u0000-\u001f\u007f-\u009f\u00ad\u061c\u200b-\u200f\u2028\u2029\ufeff]/g, function (cm, val, old) {
  6894. cm.state.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g");
  6895. if (old != Init) { cm.refresh(); }
  6896. });
  6897. option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function (cm) { return cm.refresh(); }, true);
  6898. option("electricChars", true);
  6899. option("inputStyle", mobile ? "contenteditable" : "textarea", function () {
  6900. throw new Error("inputStyle can not (yet) be changed in a running editor") // FIXME
  6901. }, true);
  6902. option("spellcheck", false, function (cm, val) { return cm.getInputField().spellcheck = val; }, true);
  6903. option("rtlMoveVisually", !windows);
  6904. option("wholeLineUpdateBefore", true);
  6905. option("theme", "default", function (cm) {
  6906. themeChanged(cm);
  6907. guttersChanged(cm);
  6908. }, true);
  6909. option("keyMap", "default", function (cm, val, old) {
  6910. var next = getKeyMap(val);
  6911. var prev = old != Init && getKeyMap(old);
  6912. if (prev && prev.detach) { prev.detach(cm, next); }
  6913. if (next.attach) { next.attach(cm, prev || null); }
  6914. });
  6915. option("extraKeys", null);
  6916. option("configureMouse", null);
  6917. option("lineWrapping", false, wrappingChanged, true);
  6918. option("gutters", [], function (cm) {
  6919. setGuttersForLineNumbers(cm.options);
  6920. guttersChanged(cm);
  6921. }, true);
  6922. option("fixedGutter", true, function (cm, val) {
  6923. cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0";
  6924. cm.refresh();
  6925. }, true);
  6926. option("coverGutterNextToScrollbar", false, function (cm) { return updateScrollbars(cm); }, true);
  6927. option("scrollbarStyle", "native", function (cm) {
  6928. initScrollbars(cm);
  6929. updateScrollbars(cm);
  6930. cm.display.scrollbars.setScrollTop(cm.doc.scrollTop);
  6931. cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft);
  6932. }, true);
  6933. option("lineNumbers", false, function (cm) {
  6934. setGuttersForLineNumbers(cm.options);
  6935. guttersChanged(cm);
  6936. }, true);
  6937. option("firstLineNumber", 1, guttersChanged, true);
  6938. option("lineNumberFormatter", function (integer) { return integer; }, guttersChanged, true);
  6939. option("showCursorWhenSelecting", false, updateSelection, true);
  6940. option("resetSelectionOnContextMenu", true);
  6941. option("lineWiseCopyCut", true);
  6942. option("pasteLinesPerSelection", true);
  6943. option("readOnly", false, function (cm, val) {
  6944. if (val == "nocursor") {
  6945. onBlur(cm);
  6946. cm.display.input.blur();
  6947. }
  6948. cm.display.input.readOnlyChanged(val);
  6949. });
  6950. option("disableInput", false, function (cm, val) {if (!val) { cm.display.input.reset(); }}, true);
  6951. option("dragDrop", true, dragDropChanged);
  6952. option("allowDropFileTypes", null);
  6953. option("cursorBlinkRate", 530);
  6954. option("cursorScrollMargin", 0);
  6955. option("cursorHeight", 1, updateSelection, true);
  6956. option("singleCursorHeightPerLine", true, updateSelection, true);
  6957. option("workTime", 100);
  6958. option("workDelay", 100);
  6959. option("flattenSpans", true, resetModeState, true);
  6960. option("addModeClass", false, resetModeState, true);
  6961. option("pollInterval", 100);
  6962. option("undoDepth", 200, function (cm, val) { return cm.doc.history.undoDepth = val; });
  6963. option("historyEventDelay", 1250);
  6964. option("viewportMargin", 10, function (cm) { return cm.refresh(); }, true);
  6965. option("maxHighlightLength", 10000, resetModeState, true);
  6966. option("moveInputWithCursor", true, function (cm, val) {
  6967. if (!val) { cm.display.input.resetPosition(); }
  6968. });
  6969. option("tabindex", null, function (cm, val) { return cm.display.input.getField().tabIndex = val || ""; });
  6970. option("autofocus", null);
  6971. option("direction", "ltr", function (cm, val) { return cm.doc.setDirection(val); }, true);
  6972. }
  6973. function guttersChanged(cm) {
  6974. updateGutters(cm);
  6975. regChange(cm);
  6976. alignHorizontally(cm);
  6977. }
  6978. function dragDropChanged(cm, value, old) {
  6979. var wasOn = old && old != Init;
  6980. if (!value != !wasOn) {
  6981. var funcs = cm.display.dragFunctions;
  6982. var toggle = value ? on : off;
  6983. toggle(cm.display.scroller, "dragstart", funcs.start);
  6984. toggle(cm.display.scroller, "dragenter", funcs.enter);
  6985. toggle(cm.display.scroller, "dragover", funcs.over);
  6986. toggle(cm.display.scroller, "dragleave", funcs.leave);
  6987. toggle(cm.display.scroller, "drop", funcs.drop);
  6988. }
  6989. }
  6990. function wrappingChanged(cm) {
  6991. if (cm.options.lineWrapping) {
  6992. addClass(cm.display.wrapper, "CodeMirror-wrap");
  6993. cm.display.sizer.style.minWidth = "";
  6994. cm.display.sizerWidth = null;
  6995. } else {
  6996. rmClass(cm.display.wrapper, "CodeMirror-wrap");
  6997. findMaxLine(cm);
  6998. }
  6999. estimateLineHeights(cm);
  7000. regChange(cm);
  7001. clearCaches(cm);
  7002. setTimeout(function () { return updateScrollbars(cm); }, 100);
  7003. }
  7004. // A CodeMirror instance represents an editor. This is the object
  7005. // that user code is usually dealing with.
  7006. function CodeMirror$1(place, options) {
  7007. var this$1 = this;
  7008. if (!(this instanceof CodeMirror$1)) { return new CodeMirror$1(place, options) }
  7009. this.options = options = options ? copyObj(options) : {};
  7010. // Determine effective options based on given values and defaults.
  7011. copyObj(defaults, options, false);
  7012. setGuttersForLineNumbers(options);
  7013. var doc = options.value;
  7014. if (typeof doc == "string") { doc = new Doc(doc, options.mode, null, options.lineSeparator, options.direction); }
  7015. this.doc = doc;
  7016. var input = new CodeMirror$1.inputStyles[options.inputStyle](this);
  7017. var display = this.display = new Display(place, doc, input);
  7018. display.wrapper.CodeMirror = this;
  7019. updateGutters(this);
  7020. themeChanged(this);
  7021. if (options.lineWrapping)
  7022. { this.display.wrapper.className += " CodeMirror-wrap"; }
  7023. initScrollbars(this);
  7024. this.state = {
  7025. keyMaps: [], // stores maps added by addKeyMap
  7026. overlays: [], // highlighting overlays, as added by addOverlay
  7027. modeGen: 0, // bumped when mode/overlay changes, used to invalidate highlighting info
  7028. overwrite: false,
  7029. delayingBlurEvent: false,
  7030. focused: false,
  7031. suppressEdits: false, // used to disable editing during key handlers when in readOnly mode
  7032. pasteIncoming: false, cutIncoming: false, // help recognize paste/cut edits in input.poll
  7033. selectingText: false,
  7034. draggingText: false,
  7035. highlight: new Delayed(), // stores highlight worker timeout
  7036. keySeq: null, // Unfinished key sequence
  7037. specialChars: null
  7038. };
  7039. if (options.autofocus && !mobile) { display.input.focus(); }
  7040. // Override magic textarea content restore that IE sometimes does
  7041. // on our hidden textarea on reload
  7042. if (ie && ie_version < 11) { setTimeout(function () { return this$1.display.input.reset(true); }, 20); }
  7043. registerEventHandlers(this);
  7044. ensureGlobalHandlers();
  7045. startOperation(this);
  7046. this.curOp.forceUpdate = true;
  7047. attachDoc(this, doc);
  7048. if ((options.autofocus && !mobile) || this.hasFocus())
  7049. { setTimeout(bind(onFocus, this), 20); }
  7050. else
  7051. { onBlur(this); }
  7052. for (var opt in optionHandlers) { if (optionHandlers.hasOwnProperty(opt))
  7053. { optionHandlers[opt](this$1, options[opt], Init); } }
  7054. maybeUpdateLineNumberWidth(this);
  7055. if (options.finishInit) { options.finishInit(this); }
  7056. for (var i = 0; i < initHooks.length; ++i) { initHooks[i](this$1); }
  7057. endOperation(this);
  7058. // Suppress optimizelegibility in Webkit, since it breaks text
  7059. // measuring on line wrapping boundaries.
  7060. if (webkit && options.lineWrapping &&
  7061. getComputedStyle(display.lineDiv).textRendering == "optimizelegibility")
  7062. { display.lineDiv.style.textRendering = "auto"; }
  7063. }
  7064. // The default configuration options.
  7065. CodeMirror$1.defaults = defaults;
  7066. // Functions to run when options are changed.
  7067. CodeMirror$1.optionHandlers = optionHandlers;
  7068. // Attach the necessary event handlers when initializing the editor
  7069. function registerEventHandlers(cm) {
  7070. var d = cm.display;
  7071. on(d.scroller, "mousedown", operation(cm, onMouseDown));
  7072. // Older IE's will not fire a second mousedown for a double click
  7073. if (ie && ie_version < 11)
  7074. { on(d.scroller, "dblclick", operation(cm, function (e) {
  7075. if (signalDOMEvent(cm, e)) { return }
  7076. var pos = posFromMouse(cm, e);
  7077. if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) { return }
  7078. e_preventDefault(e);
  7079. var word = cm.findWordAt(pos);
  7080. extendSelection(cm.doc, word.anchor, word.head);
  7081. })); }
  7082. else
  7083. { on(d.scroller, "dblclick", function (e) { return signalDOMEvent(cm, e) || e_preventDefault(e); }); }
  7084. // Some browsers fire contextmenu *after* opening the menu, at
  7085. // which point we can't mess with it anymore. Context menu is
  7086. // handled in onMouseDown for these browsers.
  7087. if (!captureRightClick) { on(d.scroller, "contextmenu", function (e) { return onContextMenu(cm, e); }); }
  7088. // Used to suppress mouse event handling when a touch happens
  7089. var touchFinished, prevTouch = {end: 0};
  7090. function finishTouch() {
  7091. if (d.activeTouch) {
  7092. touchFinished = setTimeout(function () { return d.activeTouch = null; }, 1000);
  7093. prevTouch = d.activeTouch;
  7094. prevTouch.end = +new Date;
  7095. }
  7096. }
  7097. function isMouseLikeTouchEvent(e) {
  7098. if (e.touches.length != 1) { return false }
  7099. var touch = e.touches[0];
  7100. return touch.radiusX <= 1 && touch.radiusY <= 1
  7101. }
  7102. function farAway(touch, other) {
  7103. if (other.left == null) { return true }
  7104. var dx = other.left - touch.left, dy = other.top - touch.top;
  7105. return dx * dx + dy * dy > 20 * 20
  7106. }
  7107. on(d.scroller, "touchstart", function (e) {
  7108. if (!signalDOMEvent(cm, e) && !isMouseLikeTouchEvent(e) && !clickInGutter(cm, e)) {
  7109. d.input.ensurePolled();
  7110. clearTimeout(touchFinished);
  7111. var now = +new Date;
  7112. d.activeTouch = {start: now, moved: false,
  7113. prev: now - prevTouch.end <= 300 ? prevTouch : null};
  7114. if (e.touches.length == 1) {
  7115. d.activeTouch.left = e.touches[0].pageX;
  7116. d.activeTouch.top = e.touches[0].pageY;
  7117. }
  7118. }
  7119. });
  7120. on(d.scroller, "touchmove", function () {
  7121. if (d.activeTouch) { d.activeTouch.moved = true; }
  7122. });
  7123. on(d.scroller, "touchend", function (e) {
  7124. var touch = d.activeTouch;
  7125. if (touch && !eventInWidget(d, e) && touch.left != null &&
  7126. !touch.moved && new Date - touch.start < 300) {
  7127. var pos = cm.coordsChar(d.activeTouch, "page"), range;
  7128. if (!touch.prev || farAway(touch, touch.prev)) // Single tap
  7129. { range = new Range(pos, pos); }
  7130. else if (!touch.prev.prev || farAway(touch, touch.prev.prev)) // Double tap
  7131. { range = cm.findWordAt(pos); }
  7132. else // Triple tap
  7133. { range = new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))); }
  7134. cm.setSelection(range.anchor, range.head);
  7135. cm.focus();
  7136. e_preventDefault(e);
  7137. }
  7138. finishTouch();
  7139. });
  7140. on(d.scroller, "touchcancel", finishTouch);
  7141. // Sync scrolling between fake scrollbars and real scrollable
  7142. // area, ensure viewport is updated when scrolling.
  7143. on(d.scroller, "scroll", function () {
  7144. if (d.scroller.clientHeight) {
  7145. updateScrollTop(cm, d.scroller.scrollTop);
  7146. setScrollLeft(cm, d.scroller.scrollLeft, true);
  7147. signal(cm, "scroll", cm);
  7148. }
  7149. });
  7150. // Listen to wheel events in order to try and update the viewport on time.
  7151. on(d.scroller, "mousewheel", function (e) { return onScrollWheel(cm, e); });
  7152. on(d.scroller, "DOMMouseScroll", function (e) { return onScrollWheel(cm, e); });
  7153. // Prevent wrapper from ever scrolling
  7154. on(d.wrapper, "scroll", function () { return d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; });
  7155. d.dragFunctions = {
  7156. enter: function (e) {if (!signalDOMEvent(cm, e)) { e_stop(e); }},
  7157. over: function (e) {if (!signalDOMEvent(cm, e)) { onDragOver(cm, e); e_stop(e); }},
  7158. start: function (e) { return onDragStart(cm, e); },
  7159. drop: operation(cm, onDrop),
  7160. leave: function (e) {if (!signalDOMEvent(cm, e)) { clearDragCursor(cm); }}
  7161. };
  7162. var inp = d.input.getField();
  7163. on(inp, "keyup", function (e) { return onKeyUp.call(cm, e); });
  7164. on(inp, "keydown", operation(cm, onKeyDown));
  7165. on(inp, "keypress", operation(cm, onKeyPress));
  7166. on(inp, "focus", function (e) { return onFocus(cm, e); });
  7167. on(inp, "blur", function (e) { return onBlur(cm, e); });
  7168. }
  7169. var initHooks = [];
  7170. CodeMirror$1.defineInitHook = function (f) { return initHooks.push(f); };
  7171. // Indent the given line. The how parameter can be "smart",
  7172. // "add"/null, "subtract", or "prev". When aggressive is false
  7173. // (typically set to true for forced single-line indents), empty
  7174. // lines are not indented, and places where the mode returns Pass
  7175. // are left alone.
  7176. function indentLine(cm, n, how, aggressive) {
  7177. var doc = cm.doc, state;
  7178. if (how == null) { how = "add"; }
  7179. if (how == "smart") {
  7180. // Fall back to "prev" when the mode doesn't have an indentation
  7181. // method.
  7182. if (!doc.mode.indent) { how = "prev"; }
  7183. else { state = getContextBefore(cm, n).state; }
  7184. }
  7185. var tabSize = cm.options.tabSize;
  7186. var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize);
  7187. if (line.stateAfter) { line.stateAfter = null; }
  7188. var curSpaceString = line.text.match(/^\s*/)[0], indentation;
  7189. if (!aggressive && !/\S/.test(line.text)) {
  7190. indentation = 0;
  7191. how = "not";
  7192. } else if (how == "smart") {
  7193. indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text);
  7194. if (indentation == Pass || indentation > 150) {
  7195. if (!aggressive) { return }
  7196. how = "prev";
  7197. }
  7198. }
  7199. if (how == "prev") {
  7200. if (n > doc.first) { indentation = countColumn(getLine(doc, n-1).text, null, tabSize); }
  7201. else { indentation = 0; }
  7202. } else if (how == "add") {
  7203. indentation = curSpace + cm.options.indentUnit;
  7204. } else if (how == "subtract") {
  7205. indentation = curSpace - cm.options.indentUnit;
  7206. } else if (typeof how == "number") {
  7207. indentation = curSpace + how;
  7208. }
  7209. indentation = Math.max(0, indentation);
  7210. var indentString = "", pos = 0;
  7211. if (cm.options.indentWithTabs)
  7212. { for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";} }
  7213. if (pos < indentation) { indentString += spaceStr(indentation - pos); }
  7214. if (indentString != curSpaceString) {
  7215. replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input");
  7216. line.stateAfter = null;
  7217. return true
  7218. } else {
  7219. // Ensure that, if the cursor was in the whitespace at the start
  7220. // of the line, it is moved to the end of that space.
  7221. for (var i$1 = 0; i$1 < doc.sel.ranges.length; i$1++) {
  7222. var range = doc.sel.ranges[i$1];
  7223. if (range.head.line == n && range.head.ch < curSpaceString.length) {
  7224. var pos$1 = Pos(n, curSpaceString.length);
  7225. replaceOneSelection(doc, i$1, new Range(pos$1, pos$1));
  7226. break
  7227. }
  7228. }
  7229. }
  7230. }
  7231. // This will be set to a {lineWise: bool, text: [string]} object, so
  7232. // that, when pasting, we know what kind of selections the copied
  7233. // text was made out of.
  7234. var lastCopied = null;
  7235. function setLastCopied(newLastCopied) {
  7236. lastCopied = newLastCopied;
  7237. }
  7238. function applyTextInput(cm, inserted, deleted, sel, origin) {
  7239. var doc = cm.doc;
  7240. cm.display.shift = false;
  7241. if (!sel) { sel = doc.sel; }
  7242. var paste = cm.state.pasteIncoming || origin == "paste";
  7243. var textLines = splitLinesAuto(inserted), multiPaste = null;
  7244. // When pasting N lines into N selections, insert one line per selection
  7245. if (paste && sel.ranges.length > 1) {
  7246. if (lastCopied && lastCopied.text.join("\n") == inserted) {
  7247. if (sel.ranges.length % lastCopied.text.length == 0) {
  7248. multiPaste = [];
  7249. for (var i = 0; i < lastCopied.text.length; i++)
  7250. { multiPaste.push(doc.splitLines(lastCopied.text[i])); }
  7251. }
  7252. } else if (textLines.length == sel.ranges.length && cm.options.pasteLinesPerSelection) {
  7253. multiPaste = map(textLines, function (l) { return [l]; });
  7254. }
  7255. }
  7256. var updateInput;
  7257. // Normal behavior is to insert the new text into every selection
  7258. for (var i$1 = sel.ranges.length - 1; i$1 >= 0; i$1--) {
  7259. var range$$1 = sel.ranges[i$1];
  7260. var from = range$$1.from(), to = range$$1.to();
  7261. if (range$$1.empty()) {
  7262. if (deleted && deleted > 0) // Handle deletion
  7263. { from = Pos(from.line, from.ch - deleted); }
  7264. else if (cm.state.overwrite && !paste) // Handle overwrite
  7265. { to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length)); }
  7266. else if (lastCopied && lastCopied.lineWise && lastCopied.text.join("\n") == inserted)
  7267. { from = to = Pos(from.line, 0); }
  7268. }
  7269. updateInput = cm.curOp.updateInput;
  7270. var changeEvent = {from: from, to: to, text: multiPaste ? multiPaste[i$1 % multiPaste.length] : textLines,
  7271. origin: origin || (paste ? "paste" : cm.state.cutIncoming ? "cut" : "+input")};
  7272. makeChange(cm.doc, changeEvent);
  7273. signalLater(cm, "inputRead", cm, changeEvent);
  7274. }
  7275. if (inserted && !paste)
  7276. { triggerElectric(cm, inserted); }
  7277. ensureCursorVisible(cm);
  7278. cm.curOp.updateInput = updateInput;
  7279. cm.curOp.typing = true;
  7280. cm.state.pasteIncoming = cm.state.cutIncoming = false;
  7281. }
  7282. function handlePaste(e, cm) {
  7283. var pasted = e.clipboardData && e.clipboardData.getData("Text");
  7284. if (pasted) {
  7285. e.preventDefault();
  7286. if (!cm.isReadOnly() && !cm.options.disableInput)
  7287. { runInOp(cm, function () { return applyTextInput(cm, pasted, 0, null, "paste"); }); }
  7288. return true
  7289. }
  7290. }
  7291. function triggerElectric(cm, inserted) {
  7292. // When an 'electric' character is inserted, immediately trigger a reindent
  7293. if (!cm.options.electricChars || !cm.options.smartIndent) { return }
  7294. var sel = cm.doc.sel;
  7295. for (var i = sel.ranges.length - 1; i >= 0; i--) {
  7296. var range$$1 = sel.ranges[i];
  7297. if (range$$1.head.ch > 100 || (i && sel.ranges[i - 1].head.line == range$$1.head.line)) { continue }
  7298. var mode = cm.getModeAt(range$$1.head);
  7299. var indented = false;
  7300. if (mode.electricChars) {
  7301. for (var j = 0; j < mode.electricChars.length; j++)
  7302. { if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) {
  7303. indented = indentLine(cm, range$$1.head.line, "smart");
  7304. break
  7305. } }
  7306. } else if (mode.electricInput) {
  7307. if (mode.electricInput.test(getLine(cm.doc, range$$1.head.line).text.slice(0, range$$1.head.ch)))
  7308. { indented = indentLine(cm, range$$1.head.line, "smart"); }
  7309. }
  7310. if (indented) { signalLater(cm, "electricInput", cm, range$$1.head.line); }
  7311. }
  7312. }
  7313. function copyableRanges(cm) {
  7314. var text = [], ranges = [];
  7315. for (var i = 0; i < cm.doc.sel.ranges.length; i++) {
  7316. var line = cm.doc.sel.ranges[i].head.line;
  7317. var lineRange = {anchor: Pos(line, 0), head: Pos(line + 1, 0)};
  7318. ranges.push(lineRange);
  7319. text.push(cm.getRange(lineRange.anchor, lineRange.head));
  7320. }
  7321. return {text: text, ranges: ranges}
  7322. }
  7323. function disableBrowserMagic(field, spellcheck) {
  7324. field.setAttribute("autocorrect", "off");
  7325. field.setAttribute("autocapitalize", "off");
  7326. field.setAttribute("spellcheck", !!spellcheck);
  7327. }
  7328. function hiddenTextarea() {
  7329. var te = elt("textarea", null, null, "position: absolute; bottom: -1em; padding: 0; width: 1px; height: 1em; outline: none");
  7330. var div = elt("div", [te], null, "overflow: hidden; position: relative; width: 3px; height: 0px;");
  7331. // The textarea is kept positioned near the cursor to prevent the
  7332. // fact that it'll be scrolled into view on input from scrolling
  7333. // our fake cursor out of view. On webkit, when wrap=off, paste is
  7334. // very slow. So make the area wide instead.
  7335. if (webkit) { te.style.width = "1000px"; }
  7336. else { te.setAttribute("wrap", "off"); }
  7337. // If border: 0; -- iOS fails to open keyboard (issue #1287)
  7338. if (ios) { te.style.border = "1px solid black"; }
  7339. disableBrowserMagic(te);
  7340. return div
  7341. }
  7342. // The publicly visible API. Note that methodOp(f) means
  7343. // 'wrap f in an operation, performed on its `this` parameter'.
  7344. // This is not the complete set of editor methods. Most of the
  7345. // methods defined on the Doc type are also injected into
  7346. // CodeMirror.prototype, for backwards compatibility and
  7347. // convenience.
  7348. var addEditorMethods = function(CodeMirror) {
  7349. var optionHandlers = CodeMirror.optionHandlers;
  7350. var helpers = CodeMirror.helpers = {};
  7351. CodeMirror.prototype = {
  7352. constructor: CodeMirror,
  7353. focus: function(){window.focus(); this.display.input.focus();},
  7354. setOption: function(option, value) {
  7355. var options = this.options, old = options[option];
  7356. if (options[option] == value && option != "mode") { return }
  7357. options[option] = value;
  7358. if (optionHandlers.hasOwnProperty(option))
  7359. { operation(this, optionHandlers[option])(this, value, old); }
  7360. signal(this, "optionChange", this, option);
  7361. },
  7362. getOption: function(option) {return this.options[option]},
  7363. getDoc: function() {return this.doc},
  7364. addKeyMap: function(map$$1, bottom) {
  7365. this.state.keyMaps[bottom ? "push" : "unshift"](getKeyMap(map$$1));
  7366. },
  7367. removeKeyMap: function(map$$1) {
  7368. var maps = this.state.keyMaps;
  7369. for (var i = 0; i < maps.length; ++i)
  7370. { if (maps[i] == map$$1 || maps[i].name == map$$1) {
  7371. maps.splice(i, 1);
  7372. return true
  7373. } }
  7374. },
  7375. addOverlay: methodOp(function(spec, options) {
  7376. var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec);
  7377. if (mode.startState) { throw new Error("Overlays may not be stateful.") }
  7378. insertSorted(this.state.overlays,
  7379. {mode: mode, modeSpec: spec, opaque: options && options.opaque,
  7380. priority: (options && options.priority) || 0},
  7381. function (overlay) { return overlay.priority; });
  7382. this.state.modeGen++;
  7383. regChange(this);
  7384. }),
  7385. removeOverlay: methodOp(function(spec) {
  7386. var this$1 = this;
  7387. var overlays = this.state.overlays;
  7388. for (var i = 0; i < overlays.length; ++i) {
  7389. var cur = overlays[i].modeSpec;
  7390. if (cur == spec || typeof spec == "string" && cur.name == spec) {
  7391. overlays.splice(i, 1);
  7392. this$1.state.modeGen++;
  7393. regChange(this$1);
  7394. return
  7395. }
  7396. }
  7397. }),
  7398. indentLine: methodOp(function(n, dir, aggressive) {
  7399. if (typeof dir != "string" && typeof dir != "number") {
  7400. if (dir == null) { dir = this.options.smartIndent ? "smart" : "prev"; }
  7401. else { dir = dir ? "add" : "subtract"; }
  7402. }
  7403. if (isLine(this.doc, n)) { indentLine(this, n, dir, aggressive); }
  7404. }),
  7405. indentSelection: methodOp(function(how) {
  7406. var this$1 = this;
  7407. var ranges = this.doc.sel.ranges, end = -1;
  7408. for (var i = 0; i < ranges.length; i++) {
  7409. var range$$1 = ranges[i];
  7410. if (!range$$1.empty()) {
  7411. var from = range$$1.from(), to = range$$1.to();
  7412. var start = Math.max(end, from.line);
  7413. end = Math.min(this$1.lastLine(), to.line - (to.ch ? 0 : 1)) + 1;
  7414. for (var j = start; j < end; ++j)
  7415. { indentLine(this$1, j, how); }
  7416. var newRanges = this$1.doc.sel.ranges;
  7417. if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i].from().ch > 0)
  7418. { replaceOneSelection(this$1.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll); }
  7419. } else if (range$$1.head.line > end) {
  7420. indentLine(this$1, range$$1.head.line, how, true);
  7421. end = range$$1.head.line;
  7422. if (i == this$1.doc.sel.primIndex) { ensureCursorVisible(this$1); }
  7423. }
  7424. }
  7425. }),
  7426. // Fetch the parser token for a given character. Useful for hacks
  7427. // that want to inspect the mode state (say, for completion).
  7428. getTokenAt: function(pos, precise) {
  7429. return takeToken(this, pos, precise)
  7430. },
  7431. getLineTokens: function(line, precise) {
  7432. return takeToken(this, Pos(line), precise, true)
  7433. },
  7434. getTokenTypeAt: function(pos) {
  7435. pos = clipPos(this.doc, pos);
  7436. var styles = getLineStyles(this, getLine(this.doc, pos.line));
  7437. var before = 0, after = (styles.length - 1) / 2, ch = pos.ch;
  7438. var type;
  7439. if (ch == 0) { type = styles[2]; }
  7440. else { for (;;) {
  7441. var mid = (before + after) >> 1;
  7442. if ((mid ? styles[mid * 2 - 1] : 0) >= ch) { after = mid; }
  7443. else if (styles[mid * 2 + 1] < ch) { before = mid + 1; }
  7444. else { type = styles[mid * 2 + 2]; break }
  7445. } }
  7446. var cut = type ? type.indexOf("overlay ") : -1;
  7447. return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1)
  7448. },
  7449. getModeAt: function(pos) {
  7450. var mode = this.doc.mode;
  7451. if (!mode.innerMode) { return mode }
  7452. return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode
  7453. },
  7454. getHelper: function(pos, type) {
  7455. return this.getHelpers(pos, type)[0]
  7456. },
  7457. getHelpers: function(pos, type) {
  7458. var this$1 = this;
  7459. var found = [];
  7460. if (!helpers.hasOwnProperty(type)) { return found }
  7461. var help = helpers[type], mode = this.getModeAt(pos);
  7462. if (typeof mode[type] == "string") {
  7463. if (help[mode[type]]) { found.push(help[mode[type]]); }
  7464. } else if (mode[type]) {
  7465. for (var i = 0; i < mode[type].length; i++) {
  7466. var val = help[mode[type][i]];
  7467. if (val) { found.push(val); }
  7468. }
  7469. } else if (mode.helperType && help[mode.helperType]) {
  7470. found.push(help[mode.helperType]);
  7471. } else if (help[mode.name]) {
  7472. found.push(help[mode.name]);
  7473. }
  7474. for (var i$1 = 0; i$1 < help._global.length; i$1++) {
  7475. var cur = help._global[i$1];
  7476. if (cur.pred(mode, this$1) && indexOf(found, cur.val) == -1)
  7477. { found.push(cur.val); }
  7478. }
  7479. return found
  7480. },
  7481. getStateAfter: function(line, precise) {
  7482. var doc = this.doc;
  7483. line = clipLine(doc, line == null ? doc.first + doc.size - 1: line);
  7484. return getContextBefore(this, line + 1, precise).state
  7485. },
  7486. cursorCoords: function(start, mode) {
  7487. var pos, range$$1 = this.doc.sel.primary();
  7488. if (start == null) { pos = range$$1.head; }
  7489. else if (typeof start == "object") { pos = clipPos(this.doc, start); }
  7490. else { pos = start ? range$$1.from() : range$$1.to(); }
  7491. return cursorCoords(this, pos, mode || "page")
  7492. },
  7493. charCoords: function(pos, mode) {
  7494. return charCoords(this, clipPos(this.doc, pos), mode || "page")
  7495. },
  7496. coordsChar: function(coords, mode) {
  7497. coords = fromCoordSystem(this, coords, mode || "page");
  7498. return coordsChar(this, coords.left, coords.top)
  7499. },
  7500. lineAtHeight: function(height, mode) {
  7501. height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top;
  7502. return lineAtHeight(this.doc, height + this.display.viewOffset)
  7503. },
  7504. heightAtLine: function(line, mode, includeWidgets) {
  7505. var end = false, lineObj;
  7506. if (typeof line == "number") {
  7507. var last = this.doc.first + this.doc.size - 1;
  7508. if (line < this.doc.first) { line = this.doc.first; }
  7509. else if (line > last) { line = last; end = true; }
  7510. lineObj = getLine(this.doc, line);
  7511. } else {
  7512. lineObj = line;
  7513. }
  7514. return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || "page", includeWidgets || end).top +
  7515. (end ? this.doc.height - heightAtLine(lineObj) : 0)
  7516. },
  7517. defaultTextHeight: function() { return textHeight(this.display) },
  7518. defaultCharWidth: function() { return charWidth(this.display) },
  7519. getViewport: function() { return {from: this.display.viewFrom, to: this.display.viewTo}},
  7520. addWidget: function(pos, node, scroll, vert, horiz) {
  7521. var display = this.display;
  7522. pos = cursorCoords(this, clipPos(this.doc, pos));
  7523. var top = pos.bottom, left = pos.left;
  7524. node.style.position = "absolute";
  7525. node.setAttribute("cm-ignore-events", "true");
  7526. this.display.input.setUneditable(node);
  7527. display.sizer.appendChild(node);
  7528. if (vert == "over") {
  7529. top = pos.top;
  7530. } else if (vert == "above" || vert == "near") {
  7531. var vspace = Math.max(display.wrapper.clientHeight, this.doc.height),
  7532. hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth);
  7533. // Default to positioning above (if specified and possible); otherwise default to positioning below
  7534. if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight)
  7535. { top = pos.top - node.offsetHeight; }
  7536. else if (pos.bottom + node.offsetHeight <= vspace)
  7537. { top = pos.bottom; }
  7538. if (left + node.offsetWidth > hspace)
  7539. { left = hspace - node.offsetWidth; }
  7540. }
  7541. node.style.top = top + "px";
  7542. node.style.left = node.style.right = "";
  7543. if (horiz == "right") {
  7544. left = display.sizer.clientWidth - node.offsetWidth;
  7545. node.style.right = "0px";
  7546. } else {
  7547. if (horiz == "left") { left = 0; }
  7548. else if (horiz == "middle") { left = (display.sizer.clientWidth - node.offsetWidth) / 2; }
  7549. node.style.left = left + "px";
  7550. }
  7551. if (scroll)
  7552. { scrollIntoView(this, {left: left, top: top, right: left + node.offsetWidth, bottom: top + node.offsetHeight}); }
  7553. },
  7554. triggerOnKeyDown: methodOp(onKeyDown),
  7555. triggerOnKeyPress: methodOp(onKeyPress),
  7556. triggerOnKeyUp: onKeyUp,
  7557. triggerOnMouseDown: methodOp(onMouseDown),
  7558. execCommand: function(cmd) {
  7559. if (commands.hasOwnProperty(cmd))
  7560. { return commands[cmd].call(null, this) }
  7561. },
  7562. triggerElectric: methodOp(function(text) { triggerElectric(this, text); }),
  7563. findPosH: function(from, amount, unit, visually) {
  7564. var this$1 = this;
  7565. var dir = 1;
  7566. if (amount < 0) { dir = -1; amount = -amount; }
  7567. var cur = clipPos(this.doc, from);
  7568. for (var i = 0; i < amount; ++i) {
  7569. cur = findPosH(this$1.doc, cur, dir, unit, visually);
  7570. if (cur.hitSide) { break }
  7571. }
  7572. return cur
  7573. },
  7574. moveH: methodOp(function(dir, unit) {
  7575. var this$1 = this;
  7576. this.extendSelectionsBy(function (range$$1) {
  7577. if (this$1.display.shift || this$1.doc.extend || range$$1.empty())
  7578. { return findPosH(this$1.doc, range$$1.head, dir, unit, this$1.options.rtlMoveVisually) }
  7579. else
  7580. { return dir < 0 ? range$$1.from() : range$$1.to() }
  7581. }, sel_move);
  7582. }),
  7583. deleteH: methodOp(function(dir, unit) {
  7584. var sel = this.doc.sel, doc = this.doc;
  7585. if (sel.somethingSelected())
  7586. { doc.replaceSelection("", null, "+delete"); }
  7587. else
  7588. { deleteNearSelection(this, function (range$$1) {
  7589. var other = findPosH(doc, range$$1.head, dir, unit, false);
  7590. return dir < 0 ? {from: other, to: range$$1.head} : {from: range$$1.head, to: other}
  7591. }); }
  7592. }),
  7593. findPosV: function(from, amount, unit, goalColumn) {
  7594. var this$1 = this;
  7595. var dir = 1, x = goalColumn;
  7596. if (amount < 0) { dir = -1; amount = -amount; }
  7597. var cur = clipPos(this.doc, from);
  7598. for (var i = 0; i < amount; ++i) {
  7599. var coords = cursorCoords(this$1, cur, "div");
  7600. if (x == null) { x = coords.left; }
  7601. else { coords.left = x; }
  7602. cur = findPosV(this$1, coords, dir, unit);
  7603. if (cur.hitSide) { break }
  7604. }
  7605. return cur
  7606. },
  7607. moveV: methodOp(function(dir, unit) {
  7608. var this$1 = this;
  7609. var doc = this.doc, goals = [];
  7610. var collapse = !this.display.shift && !doc.extend && doc.sel.somethingSelected();
  7611. doc.extendSelectionsBy(function (range$$1) {
  7612. if (collapse)
  7613. { return dir < 0 ? range$$1.from() : range$$1.to() }
  7614. var headPos = cursorCoords(this$1, range$$1.head, "div");
  7615. if (range$$1.goalColumn != null) { headPos.left = range$$1.goalColumn; }
  7616. goals.push(headPos.left);
  7617. var pos = findPosV(this$1, headPos, dir, unit);
  7618. if (unit == "page" && range$$1 == doc.sel.primary())
  7619. { addToScrollTop(this$1, charCoords(this$1, pos, "div").top - headPos.top); }
  7620. return pos
  7621. }, sel_move);
  7622. if (goals.length) { for (var i = 0; i < doc.sel.ranges.length; i++)
  7623. { doc.sel.ranges[i].goalColumn = goals[i]; } }
  7624. }),
  7625. // Find the word at the given position (as returned by coordsChar).
  7626. findWordAt: function(pos) {
  7627. var doc = this.doc, line = getLine(doc, pos.line).text;
  7628. var start = pos.ch, end = pos.ch;
  7629. if (line) {
  7630. var helper = this.getHelper(pos, "wordChars");
  7631. if ((pos.sticky == "before" || end == line.length) && start) { --start; } else { ++end; }
  7632. var startChar = line.charAt(start);
  7633. var check = isWordChar(startChar, helper)
  7634. ? function (ch) { return isWordChar(ch, helper); }
  7635. : /\s/.test(startChar) ? function (ch) { return /\s/.test(ch); }
  7636. : function (ch) { return (!/\s/.test(ch) && !isWordChar(ch)); };
  7637. while (start > 0 && check(line.charAt(start - 1))) { --start; }
  7638. while (end < line.length && check(line.charAt(end))) { ++end; }
  7639. }
  7640. return new Range(Pos(pos.line, start), Pos(pos.line, end))
  7641. },
  7642. toggleOverwrite: function(value) {
  7643. if (value != null && value == this.state.overwrite) { return }
  7644. if (this.state.overwrite = !this.state.overwrite)
  7645. { addClass(this.display.cursorDiv, "CodeMirror-overwrite"); }
  7646. else
  7647. { rmClass(this.display.cursorDiv, "CodeMirror-overwrite"); }
  7648. signal(this, "overwriteToggle", this, this.state.overwrite);
  7649. },
  7650. hasFocus: function() { return this.display.input.getField() == activeElt() },
  7651. isReadOnly: function() { return !!(this.options.readOnly || this.doc.cantEdit) },
  7652. scrollTo: methodOp(function (x, y) { scrollToCoords(this, x, y); }),
  7653. getScrollInfo: function() {
  7654. var scroller = this.display.scroller;
  7655. return {left: scroller.scrollLeft, top: scroller.scrollTop,
  7656. height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight,
  7657. width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth,
  7658. clientHeight: displayHeight(this), clientWidth: displayWidth(this)}
  7659. },
  7660. scrollIntoView: methodOp(function(range$$1, margin) {
  7661. if (range$$1 == null) {
  7662. range$$1 = {from: this.doc.sel.primary().head, to: null};
  7663. if (margin == null) { margin = this.options.cursorScrollMargin; }
  7664. } else if (typeof range$$1 == "number") {
  7665. range$$1 = {from: Pos(range$$1, 0), to: null};
  7666. } else if (range$$1.from == null) {
  7667. range$$1 = {from: range$$1, to: null};
  7668. }
  7669. if (!range$$1.to) { range$$1.to = range$$1.from; }
  7670. range$$1.margin = margin || 0;
  7671. if (range$$1.from.line != null) {
  7672. scrollToRange(this, range$$1);
  7673. } else {
  7674. scrollToCoordsRange(this, range$$1.from, range$$1.to, range$$1.margin);
  7675. }
  7676. }),
  7677. setSize: methodOp(function(width, height) {
  7678. var this$1 = this;
  7679. var interpret = function (val) { return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val; };
  7680. if (width != null) { this.display.wrapper.style.width = interpret(width); }
  7681. if (height != null) { this.display.wrapper.style.height = interpret(height); }
  7682. if (this.options.lineWrapping) { clearLineMeasurementCache(this); }
  7683. var lineNo$$1 = this.display.viewFrom;
  7684. this.doc.iter(lineNo$$1, this.display.viewTo, function (line) {
  7685. if (line.widgets) { for (var i = 0; i < line.widgets.length; i++)
  7686. { if (line.widgets[i].noHScroll) { regLineChange(this$1, lineNo$$1, "widget"); break } } }
  7687. ++lineNo$$1;
  7688. });
  7689. this.curOp.forceUpdate = true;
  7690. signal(this, "refresh", this);
  7691. }),
  7692. operation: function(f){return runInOp(this, f)},
  7693. startOperation: function(){return startOperation(this)},
  7694. endOperation: function(){return endOperation(this)},
  7695. refresh: methodOp(function() {
  7696. var oldHeight = this.display.cachedTextHeight;
  7697. regChange(this);
  7698. this.curOp.forceUpdate = true;
  7699. clearCaches(this);
  7700. scrollToCoords(this, this.doc.scrollLeft, this.doc.scrollTop);
  7701. updateGutterSpace(this);
  7702. if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5)
  7703. { estimateLineHeights(this); }
  7704. signal(this, "refresh", this);
  7705. }),
  7706. swapDoc: methodOp(function(doc) {
  7707. var old = this.doc;
  7708. old.cm = null;
  7709. attachDoc(this, doc);
  7710. clearCaches(this);
  7711. this.display.input.reset();
  7712. scrollToCoords(this, doc.scrollLeft, doc.scrollTop);
  7713. this.curOp.forceScroll = true;
  7714. signalLater(this, "swapDoc", this, old);
  7715. return old
  7716. }),
  7717. getInputField: function(){return this.display.input.getField()},
  7718. getWrapperElement: function(){return this.display.wrapper},
  7719. getScrollerElement: function(){return this.display.scroller},
  7720. getGutterElement: function(){return this.display.gutters}
  7721. };
  7722. eventMixin(CodeMirror);
  7723. CodeMirror.registerHelper = function(type, name, value) {
  7724. if (!helpers.hasOwnProperty(type)) { helpers[type] = CodeMirror[type] = {_global: []}; }
  7725. helpers[type][name] = value;
  7726. };
  7727. CodeMirror.registerGlobalHelper = function(type, name, predicate, value) {
  7728. CodeMirror.registerHelper(type, name, value);
  7729. helpers[type]._global.push({pred: predicate, val: value});
  7730. };
  7731. };
  7732. // Used for horizontal relative motion. Dir is -1 or 1 (left or
  7733. // right), unit can be "char", "column" (like char, but doesn't
  7734. // cross line boundaries), "word" (across next word), or "group" (to
  7735. // the start of next group of word or non-word-non-whitespace
  7736. // chars). The visually param controls whether, in right-to-left
  7737. // text, direction 1 means to move towards the next index in the
  7738. // string, or towards the character to the right of the current
  7739. // position. The resulting position will have a hitSide=true
  7740. // property if it reached the end of the document.
  7741. function findPosH(doc, pos, dir, unit, visually) {
  7742. var oldPos = pos;
  7743. var origDir = dir;
  7744. var lineObj = getLine(doc, pos.line);
  7745. function findNextLine() {
  7746. var l = pos.line + dir;
  7747. if (l < doc.first || l >= doc.first + doc.size) { return false }
  7748. pos = new Pos(l, pos.ch, pos.sticky);
  7749. return lineObj = getLine(doc, l)
  7750. }
  7751. function moveOnce(boundToLine) {
  7752. var next;
  7753. if (visually) {
  7754. next = moveVisually(doc.cm, lineObj, pos, dir);
  7755. } else {
  7756. next = moveLogically(lineObj, pos, dir);
  7757. }
  7758. if (next == null) {
  7759. if (!boundToLine && findNextLine())
  7760. { pos = endOfLine(visually, doc.cm, lineObj, pos.line, dir); }
  7761. else
  7762. { return false }
  7763. } else {
  7764. pos = next;
  7765. }
  7766. return true
  7767. }
  7768. if (unit == "char") {
  7769. moveOnce();
  7770. } else if (unit == "column") {
  7771. moveOnce(true);
  7772. } else if (unit == "word" || unit == "group") {
  7773. var sawType = null, group = unit == "group";
  7774. var helper = doc.cm && doc.cm.getHelper(pos, "wordChars");
  7775. for (var first = true;; first = false) {
  7776. if (dir < 0 && !moveOnce(!first)) { break }
  7777. var cur = lineObj.text.charAt(pos.ch) || "\n";
  7778. var type = isWordChar(cur, helper) ? "w"
  7779. : group && cur == "\n" ? "n"
  7780. : !group || /\s/.test(cur) ? null
  7781. : "p";
  7782. if (group && !first && !type) { type = "s"; }
  7783. if (sawType && sawType != type) {
  7784. if (dir < 0) {dir = 1; moveOnce(); pos.sticky = "after";}
  7785. break
  7786. }
  7787. if (type) { sawType = type; }
  7788. if (dir > 0 && !moveOnce(!first)) { break }
  7789. }
  7790. }
  7791. var result = skipAtomic(doc, pos, oldPos, origDir, true);
  7792. if (equalCursorPos(oldPos, result)) { result.hitSide = true; }
  7793. return result
  7794. }
  7795. // For relative vertical movement. Dir may be -1 or 1. Unit can be
  7796. // "page" or "line". The resulting position will have a hitSide=true
  7797. // property if it reached the end of the document.
  7798. function findPosV(cm, pos, dir, unit) {
  7799. var doc = cm.doc, x = pos.left, y;
  7800. if (unit == "page") {
  7801. var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight);
  7802. var moveAmount = Math.max(pageSize - .5 * textHeight(cm.display), 3);
  7803. y = (dir > 0 ? pos.bottom : pos.top) + dir * moveAmount;
  7804. } else if (unit == "line") {
  7805. y = dir > 0 ? pos.bottom + 3 : pos.top - 3;
  7806. }
  7807. var target;
  7808. for (;;) {
  7809. target = coordsChar(cm, x, y);
  7810. if (!target.outside) { break }
  7811. if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break }
  7812. y += dir * 5;
  7813. }
  7814. return target
  7815. }
  7816. // CONTENTEDITABLE INPUT STYLE
  7817. var ContentEditableInput = function(cm) {
  7818. this.cm = cm;
  7819. this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null;
  7820. this.polling = new Delayed();
  7821. this.composing = null;
  7822. this.gracePeriod = false;
  7823. this.readDOMTimeout = null;
  7824. };
  7825. ContentEditableInput.prototype.init = function (display) {
  7826. var this$1 = this;
  7827. var input = this, cm = input.cm;
  7828. var div = input.div = display.lineDiv;
  7829. disableBrowserMagic(div, cm.options.spellcheck);
  7830. on(div, "paste", function (e) {
  7831. if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { return }
  7832. // IE doesn't fire input events, so we schedule a read for the pasted content in this way
  7833. if (ie_version <= 11) { setTimeout(operation(cm, function () { return this$1.updateFromDOM(); }), 20); }
  7834. });
  7835. on(div, "compositionstart", function (e) {
  7836. this$1.composing = {data: e.data, done: false};
  7837. });
  7838. on(div, "compositionupdate", function (e) {
  7839. if (!this$1.composing) { this$1.composing = {data: e.data, done: false}; }
  7840. });
  7841. on(div, "compositionend", function (e) {
  7842. if (this$1.composing) {
  7843. if (e.data != this$1.composing.data) { this$1.readFromDOMSoon(); }
  7844. this$1.composing.done = true;
  7845. }
  7846. });
  7847. on(div, "touchstart", function () { return input.forceCompositionEnd(); });
  7848. on(div, "input", function () {
  7849. if (!this$1.composing) { this$1.readFromDOMSoon(); }
  7850. });
  7851. function onCopyCut(e) {
  7852. if (signalDOMEvent(cm, e)) { return }
  7853. if (cm.somethingSelected()) {
  7854. setLastCopied({lineWise: false, text: cm.getSelections()});
  7855. if (e.type == "cut") { cm.replaceSelection("", null, "cut"); }
  7856. } else if (!cm.options.lineWiseCopyCut) {
  7857. return
  7858. } else {
  7859. var ranges = copyableRanges(cm);
  7860. setLastCopied({lineWise: true, text: ranges.text});
  7861. if (e.type == "cut") {
  7862. cm.operation(function () {
  7863. cm.setSelections(ranges.ranges, 0, sel_dontScroll);
  7864. cm.replaceSelection("", null, "cut");
  7865. });
  7866. }
  7867. }
  7868. if (e.clipboardData) {
  7869. e.clipboardData.clearData();
  7870. var content = lastCopied.text.join("\n");
  7871. // iOS exposes the clipboard API, but seems to discard content inserted into it
  7872. e.clipboardData.setData("Text", content);
  7873. if (e.clipboardData.getData("Text") == content) {
  7874. e.preventDefault();
  7875. return
  7876. }
  7877. }
  7878. // Old-fashioned briefly-focus-a-textarea hack
  7879. var kludge = hiddenTextarea(), te = kludge.firstChild;
  7880. cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild);
  7881. te.value = lastCopied.text.join("\n");
  7882. var hadFocus = document.activeElement;
  7883. selectInput(te);
  7884. setTimeout(function () {
  7885. cm.display.lineSpace.removeChild(kludge);
  7886. hadFocus.focus();
  7887. if (hadFocus == div) { input.showPrimarySelection(); }
  7888. }, 50);
  7889. }
  7890. on(div, "copy", onCopyCut);
  7891. on(div, "cut", onCopyCut);
  7892. };
  7893. ContentEditableInput.prototype.prepareSelection = function () {
  7894. var result = prepareSelection(this.cm, false);
  7895. result.focus = this.cm.state.focused;
  7896. return result
  7897. };
  7898. ContentEditableInput.prototype.showSelection = function (info, takeFocus) {
  7899. if (!info || !this.cm.display.view.length) { return }
  7900. if (info.focus || takeFocus) { this.showPrimarySelection(); }
  7901. this.showMultipleSelections(info);
  7902. };
  7903. ContentEditableInput.prototype.showPrimarySelection = function () {
  7904. var sel = window.getSelection(), cm = this.cm, prim = cm.doc.sel.primary();
  7905. var from = prim.from(), to = prim.to();
  7906. if (cm.display.viewTo == cm.display.viewFrom || from.line >= cm.display.viewTo || to.line < cm.display.viewFrom) {
  7907. sel.removeAllRanges();
  7908. return
  7909. }
  7910. var curAnchor = domToPos(cm, sel.anchorNode, sel.anchorOffset);
  7911. var curFocus = domToPos(cm, sel.focusNode, sel.focusOffset);
  7912. if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad &&
  7913. cmp(minPos(curAnchor, curFocus), from) == 0 &&
  7914. cmp(maxPos(curAnchor, curFocus), to) == 0)
  7915. { return }
  7916. var view = cm.display.view;
  7917. var start = (from.line >= cm.display.viewFrom && posToDOM(cm, from)) ||
  7918. {node: view[0].measure.map[2], offset: 0};
  7919. var end = to.line < cm.display.viewTo && posToDOM(cm, to);
  7920. if (!end) {
  7921. var measure = view[view.length - 1].measure;
  7922. var map$$1 = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map;
  7923. end = {node: map$$1[map$$1.length - 1], offset: map$$1[map$$1.length - 2] - map$$1[map$$1.length - 3]};
  7924. }
  7925. if (!start || !end) {
  7926. sel.removeAllRanges();
  7927. return
  7928. }
  7929. var old = sel.rangeCount && sel.getRangeAt(0), rng;
  7930. try { rng = range(start.node, start.offset, end.offset, end.node); }
  7931. catch(e) {} // Our model of the DOM might be outdated, in which case the range we try to set can be impossible
  7932. if (rng) {
  7933. if (!gecko && cm.state.focused) {
  7934. sel.collapse(start.node, start.offset);
  7935. if (!rng.collapsed) {
  7936. sel.removeAllRanges();
  7937. sel.addRange(rng);
  7938. }
  7939. } else {
  7940. sel.removeAllRanges();
  7941. sel.addRange(rng);
  7942. }
  7943. if (old && sel.anchorNode == null) { sel.addRange(old); }
  7944. else if (gecko) { this.startGracePeriod(); }
  7945. }
  7946. this.rememberSelection();
  7947. };
  7948. ContentEditableInput.prototype.startGracePeriod = function () {
  7949. var this$1 = this;
  7950. clearTimeout(this.gracePeriod);
  7951. this.gracePeriod = setTimeout(function () {
  7952. this$1.gracePeriod = false;
  7953. if (this$1.selectionChanged())
  7954. { this$1.cm.operation(function () { return this$1.cm.curOp.selectionChanged = true; }); }
  7955. }, 20);
  7956. };
  7957. ContentEditableInput.prototype.showMultipleSelections = function (info) {
  7958. removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors);
  7959. removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection);
  7960. };
  7961. ContentEditableInput.prototype.rememberSelection = function () {
  7962. var sel = window.getSelection();
  7963. this.lastAnchorNode = sel.anchorNode; this.lastAnchorOffset = sel.anchorOffset;
  7964. this.lastFocusNode = sel.focusNode; this.lastFocusOffset = sel.focusOffset;
  7965. };
  7966. ContentEditableInput.prototype.selectionInEditor = function () {
  7967. var sel = window.getSelection();
  7968. if (!sel.rangeCount) { return false }
  7969. var node = sel.getRangeAt(0).commonAncestorContainer;
  7970. return contains(this.div, node)
  7971. };
  7972. ContentEditableInput.prototype.focus = function () {
  7973. if (this.cm.options.readOnly != "nocursor") {
  7974. if (!this.selectionInEditor())
  7975. { this.showSelection(this.prepareSelection(), true); }
  7976. this.div.focus();
  7977. }
  7978. };
  7979. ContentEditableInput.prototype.blur = function () { this.div.blur(); };
  7980. ContentEditableInput.prototype.getField = function () { return this.div };
  7981. ContentEditableInput.prototype.supportsTouch = function () { return true };
  7982. ContentEditableInput.prototype.receivedFocus = function () {
  7983. var input = this;
  7984. if (this.selectionInEditor())
  7985. { this.pollSelection(); }
  7986. else
  7987. { runInOp(this.cm, function () { return input.cm.curOp.selectionChanged = true; }); }
  7988. function poll() {
  7989. if (input.cm.state.focused) {
  7990. input.pollSelection();
  7991. input.polling.set(input.cm.options.pollInterval, poll);
  7992. }
  7993. }
  7994. this.polling.set(this.cm.options.pollInterval, poll);
  7995. };
  7996. ContentEditableInput.prototype.selectionChanged = function () {
  7997. var sel = window.getSelection();
  7998. return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset ||
  7999. sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset
  8000. };
  8001. ContentEditableInput.prototype.pollSelection = function () {
  8002. if (this.readDOMTimeout != null || this.gracePeriod || !this.selectionChanged()) { return }
  8003. var sel = window.getSelection(), cm = this.cm;
  8004. // On Android Chrome (version 56, at least), backspacing into an
  8005. // uneditable block element will put the cursor in that element,
  8006. // and then, because it's not editable, hide the virtual keyboard.
  8007. // Because Android doesn't allow us to actually detect backspace
  8008. // presses in a sane way, this code checks for when that happens
  8009. // and simulates a backspace press in this case.
  8010. if (android && chrome && this.cm.options.gutters.length && isInGutter(sel.anchorNode)) {
  8011. this.cm.triggerOnKeyDown({type: "keydown", keyCode: 8, preventDefault: Math.abs});
  8012. this.blur();
  8013. this.focus();
  8014. return
  8015. }
  8016. if (this.composing) { return }
  8017. this.rememberSelection();
  8018. var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset);
  8019. var head = domToPos(cm, sel.focusNode, sel.focusOffset);
  8020. if (anchor && head) { runInOp(cm, function () {
  8021. setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll);
  8022. if (anchor.bad || head.bad) { cm.curOp.selectionChanged = true; }
  8023. }); }
  8024. };
  8025. ContentEditableInput.prototype.pollContent = function () {
  8026. if (this.readDOMTimeout != null) {
  8027. clearTimeout(this.readDOMTimeout);
  8028. this.readDOMTimeout = null;
  8029. }
  8030. var cm = this.cm, display = cm.display, sel = cm.doc.sel.primary();
  8031. var from = sel.from(), to = sel.to();
  8032. if (from.ch == 0 && from.line > cm.firstLine())
  8033. { from = Pos(from.line - 1, getLine(cm.doc, from.line - 1).length); }
  8034. if (to.ch == getLine(cm.doc, to.line).text.length && to.line < cm.lastLine())
  8035. { to = Pos(to.line + 1, 0); }
  8036. if (from.line < display.viewFrom || to.line > display.viewTo - 1) { return false }
  8037. var fromIndex, fromLine, fromNode;
  8038. if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) {
  8039. fromLine = lineNo(display.view[0].line);
  8040. fromNode = display.view[0].node;
  8041. } else {
  8042. fromLine = lineNo(display.view[fromIndex].line);
  8043. fromNode = display.view[fromIndex - 1].node.nextSibling;
  8044. }
  8045. var toIndex = findViewIndex(cm, to.line);
  8046. var toLine, toNode;
  8047. if (toIndex == display.view.length - 1) {
  8048. toLine = display.viewTo - 1;
  8049. toNode = display.lineDiv.lastChild;
  8050. } else {
  8051. toLine = lineNo(display.view[toIndex + 1].line) - 1;
  8052. toNode = display.view[toIndex + 1].node.previousSibling;
  8053. }
  8054. if (!fromNode) { return false }
  8055. var newText = cm.doc.splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine));
  8056. var oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length));
  8057. while (newText.length > 1 && oldText.length > 1) {
  8058. if (lst(newText) == lst(oldText)) { newText.pop(); oldText.pop(); toLine--; }
  8059. else if (newText[0] == oldText[0]) { newText.shift(); oldText.shift(); fromLine++; }
  8060. else { break }
  8061. }
  8062. var cutFront = 0, cutEnd = 0;
  8063. var newTop = newText[0], oldTop = oldText[0], maxCutFront = Math.min(newTop.length, oldTop.length);
  8064. while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront))
  8065. { ++cutFront; }
  8066. var newBot = lst(newText), oldBot = lst(oldText);
  8067. var maxCutEnd = Math.min(newBot.length - (newText.length == 1 ? cutFront : 0),
  8068. oldBot.length - (oldText.length == 1 ? cutFront : 0));
  8069. while (cutEnd < maxCutEnd &&
  8070. newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1))
  8071. { ++cutEnd; }
  8072. // Try to move start of change to start of selection if ambiguous
  8073. if (newText.length == 1 && oldText.length == 1 && fromLine == from.line) {
  8074. while (cutFront && cutFront > from.ch &&
  8075. newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) {
  8076. cutFront--;
  8077. cutEnd++;
  8078. }
  8079. }
  8080. newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd).replace(/^\u200b+/, "");
  8081. newText[0] = newText[0].slice(cutFront).replace(/\u200b+$/, "");
  8082. var chFrom = Pos(fromLine, cutFront);
  8083. var chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0);
  8084. if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) {
  8085. replaceRange(cm.doc, newText, chFrom, chTo, "+input");
  8086. return true
  8087. }
  8088. };
  8089. ContentEditableInput.prototype.ensurePolled = function () {
  8090. this.forceCompositionEnd();
  8091. };
  8092. ContentEditableInput.prototype.reset = function () {
  8093. this.forceCompositionEnd();
  8094. };
  8095. ContentEditableInput.prototype.forceCompositionEnd = function () {
  8096. if (!this.composing) { return }
  8097. clearTimeout(this.readDOMTimeout);
  8098. this.composing = null;
  8099. this.updateFromDOM();
  8100. this.div.blur();
  8101. this.div.focus();
  8102. };
  8103. ContentEditableInput.prototype.readFromDOMSoon = function () {
  8104. var this$1 = this;
  8105. if (this.readDOMTimeout != null) { return }
  8106. this.readDOMTimeout = setTimeout(function () {
  8107. this$1.readDOMTimeout = null;
  8108. if (this$1.composing) {
  8109. if (this$1.composing.done) { this$1.composing = null; }
  8110. else { return }
  8111. }
  8112. this$1.updateFromDOM();
  8113. }, 80);
  8114. };
  8115. ContentEditableInput.prototype.updateFromDOM = function () {
  8116. var this$1 = this;
  8117. if (this.cm.isReadOnly() || !this.pollContent())
  8118. { runInOp(this.cm, function () { return regChange(this$1.cm); }); }
  8119. };
  8120. ContentEditableInput.prototype.setUneditable = function (node) {
  8121. node.contentEditable = "false";
  8122. };
  8123. ContentEditableInput.prototype.onKeyPress = function (e) {
  8124. if (e.charCode == 0) { return }
  8125. e.preventDefault();
  8126. if (!this.cm.isReadOnly())
  8127. { operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0); }
  8128. };
  8129. ContentEditableInput.prototype.readOnlyChanged = function (val) {
  8130. this.div.contentEditable = String(val != "nocursor");
  8131. };
  8132. ContentEditableInput.prototype.onContextMenu = function () {};
  8133. ContentEditableInput.prototype.resetPosition = function () {};
  8134. ContentEditableInput.prototype.needsContentAttribute = true;
  8135. function posToDOM(cm, pos) {
  8136. var view = findViewForLine(cm, pos.line);
  8137. if (!view || view.hidden) { return null }
  8138. var line = getLine(cm.doc, pos.line);
  8139. var info = mapFromLineView(view, line, pos.line);
  8140. var order = getOrder(line, cm.doc.direction), side = "left";
  8141. if (order) {
  8142. var partPos = getBidiPartAt(order, pos.ch);
  8143. side = partPos % 2 ? "right" : "left";
  8144. }
  8145. var result = nodeAndOffsetInLineMap(info.map, pos.ch, side);
  8146. result.offset = result.collapse == "right" ? result.end : result.start;
  8147. return result
  8148. }
  8149. function isInGutter(node) {
  8150. for (var scan = node; scan; scan = scan.parentNode)
  8151. { if (/CodeMirror-gutter-wrapper/.test(scan.className)) { return true } }
  8152. return false
  8153. }
  8154. function badPos(pos, bad) { if (bad) { pos.bad = true; } return pos }
  8155. function domTextBetween(cm, from, to, fromLine, toLine) {
  8156. var text = "", closing = false, lineSep = cm.doc.lineSeparator();
  8157. function recognizeMarker(id) { return function (marker) { return marker.id == id; } }
  8158. function close() {
  8159. if (closing) {
  8160. text += lineSep;
  8161. closing = false;
  8162. }
  8163. }
  8164. function addText(str) {
  8165. if (str) {
  8166. close();
  8167. text += str;
  8168. }
  8169. }
  8170. function walk(node) {
  8171. if (node.nodeType == 1) {
  8172. var cmText = node.getAttribute("cm-text");
  8173. if (cmText != null) {
  8174. addText(cmText || node.textContent.replace(/\u200b/g, ""));
  8175. return
  8176. }
  8177. var markerID = node.getAttribute("cm-marker"), range$$1;
  8178. if (markerID) {
  8179. var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID));
  8180. if (found.length && (range$$1 = found[0].find(0)))
  8181. { addText(getBetween(cm.doc, range$$1.from, range$$1.to).join(lineSep)); }
  8182. return
  8183. }
  8184. if (node.getAttribute("contenteditable") == "false") { return }
  8185. var isBlock = /^(pre|div|p)$/i.test(node.nodeName);
  8186. if (isBlock) { close(); }
  8187. for (var i = 0; i < node.childNodes.length; i++)
  8188. { walk(node.childNodes[i]); }
  8189. if (isBlock) { closing = true; }
  8190. } else if (node.nodeType == 3) {
  8191. addText(node.nodeValue);
  8192. }
  8193. }
  8194. for (;;) {
  8195. walk(from);
  8196. if (from == to) { break }
  8197. from = from.nextSibling;
  8198. }
  8199. return text
  8200. }
  8201. function domToPos(cm, node, offset) {
  8202. var lineNode;
  8203. if (node == cm.display.lineDiv) {
  8204. lineNode = cm.display.lineDiv.childNodes[offset];
  8205. if (!lineNode) { return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true) }
  8206. node = null; offset = 0;
  8207. } else {
  8208. for (lineNode = node;; lineNode = lineNode.parentNode) {
  8209. if (!lineNode || lineNode == cm.display.lineDiv) { return null }
  8210. if (lineNode.parentNode && lineNode.parentNode == cm.display.lineDiv) { break }
  8211. }
  8212. }
  8213. for (var i = 0; i < cm.display.view.length; i++) {
  8214. var lineView = cm.display.view[i];
  8215. if (lineView.node == lineNode)
  8216. { return locateNodeInLineView(lineView, node, offset) }
  8217. }
  8218. }
  8219. function locateNodeInLineView(lineView, node, offset) {
  8220. var wrapper = lineView.text.firstChild, bad = false;
  8221. if (!node || !contains(wrapper, node)) { return badPos(Pos(lineNo(lineView.line), 0), true) }
  8222. if (node == wrapper) {
  8223. bad = true;
  8224. node = wrapper.childNodes[offset];
  8225. offset = 0;
  8226. if (!node) {
  8227. var line = lineView.rest ? lst(lineView.rest) : lineView.line;
  8228. return badPos(Pos(lineNo(line), line.text.length), bad)
  8229. }
  8230. }
  8231. var textNode = node.nodeType == 3 ? node : null, topNode = node;
  8232. if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) {
  8233. textNode = node.firstChild;
  8234. if (offset) { offset = textNode.nodeValue.length; }
  8235. }
  8236. while (topNode.parentNode != wrapper) { topNode = topNode.parentNode; }
  8237. var measure = lineView.measure, maps = measure.maps;
  8238. function find(textNode, topNode, offset) {
  8239. for (var i = -1; i < (maps ? maps.length : 0); i++) {
  8240. var map$$1 = i < 0 ? measure.map : maps[i];
  8241. for (var j = 0; j < map$$1.length; j += 3) {
  8242. var curNode = map$$1[j + 2];
  8243. if (curNode == textNode || curNode == topNode) {
  8244. var line = lineNo(i < 0 ? lineView.line : lineView.rest[i]);
  8245. var ch = map$$1[j] + offset;
  8246. if (offset < 0 || curNode != textNode) { ch = map$$1[j + (offset ? 1 : 0)]; }
  8247. return Pos(line, ch)
  8248. }
  8249. }
  8250. }
  8251. }
  8252. var found = find(textNode, topNode, offset);
  8253. if (found) { return badPos(found, bad) }
  8254. // FIXME this is all really shaky. might handle the few cases it needs to handle, but likely to cause problems
  8255. for (var after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) {
  8256. found = find(after, after.firstChild, 0);
  8257. if (found)
  8258. { return badPos(Pos(found.line, found.ch - dist), bad) }
  8259. else
  8260. { dist += after.textContent.length; }
  8261. }
  8262. for (var before = topNode.previousSibling, dist$1 = offset; before; before = before.previousSibling) {
  8263. found = find(before, before.firstChild, -1);
  8264. if (found)
  8265. { return badPos(Pos(found.line, found.ch + dist$1), bad) }
  8266. else
  8267. { dist$1 += before.textContent.length; }
  8268. }
  8269. }
  8270. // TEXTAREA INPUT STYLE
  8271. var TextareaInput = function(cm) {
  8272. this.cm = cm;
  8273. // See input.poll and input.reset
  8274. this.prevInput = "";
  8275. // Flag that indicates whether we expect input to appear real soon
  8276. // now (after some event like 'keypress' or 'input') and are
  8277. // polling intensively.
  8278. this.pollingFast = false;
  8279. // Self-resetting timeout for the poller
  8280. this.polling = new Delayed();
  8281. // Used to work around IE issue with selection being forgotten when focus moves away from textarea
  8282. this.hasSelection = false;
  8283. this.composing = null;
  8284. };
  8285. TextareaInput.prototype.init = function (display) {
  8286. var this$1 = this;
  8287. var input = this, cm = this.cm;
  8288. // Wraps and hides input textarea
  8289. var div = this.wrapper = hiddenTextarea();
  8290. // The semihidden textarea that is focused when the editor is
  8291. // focused, and receives input.
  8292. var te = this.textarea = div.firstChild;
  8293. display.wrapper.insertBefore(div, display.wrapper.firstChild);
  8294. // Needed to hide big blue blinking cursor on Mobile Safari (doesn't seem to work in iOS 8 anymore)
  8295. if (ios) { te.style.width = "0px"; }
  8296. on(te, "input", function () {
  8297. if (ie && ie_version >= 9 && this$1.hasSelection) { this$1.hasSelection = null; }
  8298. input.poll();
  8299. });
  8300. on(te, "paste", function (e) {
  8301. if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { return }
  8302. cm.state.pasteIncoming = true;
  8303. input.fastPoll();
  8304. });
  8305. function prepareCopyCut(e) {
  8306. if (signalDOMEvent(cm, e)) { return }
  8307. if (cm.somethingSelected()) {
  8308. setLastCopied({lineWise: false, text: cm.getSelections()});
  8309. } else if (!cm.options.lineWiseCopyCut) {
  8310. return
  8311. } else {
  8312. var ranges = copyableRanges(cm);
  8313. setLastCopied({lineWise: true, text: ranges.text});
  8314. if (e.type == "cut") {
  8315. cm.setSelections(ranges.ranges, null, sel_dontScroll);
  8316. } else {
  8317. input.prevInput = "";
  8318. te.value = ranges.text.join("\n");
  8319. selectInput(te);
  8320. }
  8321. }
  8322. if (e.type == "cut") { cm.state.cutIncoming = true; }
  8323. }
  8324. on(te, "cut", prepareCopyCut);
  8325. on(te, "copy", prepareCopyCut);
  8326. on(display.scroller, "paste", function (e) {
  8327. if (eventInWidget(display, e) || signalDOMEvent(cm, e)) { return }
  8328. cm.state.pasteIncoming = true;
  8329. input.focus();
  8330. });
  8331. // Prevent normal selection in the editor (we handle our own)
  8332. on(display.lineSpace, "selectstart", function (e) {
  8333. if (!eventInWidget(display, e)) { e_preventDefault(e); }
  8334. });
  8335. on(te, "compositionstart", function () {
  8336. var start = cm.getCursor("from");
  8337. if (input.composing) { input.composing.range.clear(); }
  8338. input.composing = {
  8339. start: start,
  8340. range: cm.markText(start, cm.getCursor("to"), {className: "CodeMirror-composing"})
  8341. };
  8342. });
  8343. on(te, "compositionend", function () {
  8344. if (input.composing) {
  8345. input.poll();
  8346. input.composing.range.clear();
  8347. input.composing = null;
  8348. }
  8349. });
  8350. };
  8351. TextareaInput.prototype.prepareSelection = function () {
  8352. // Redraw the selection and/or cursor
  8353. var cm = this.cm, display = cm.display, doc = cm.doc;
  8354. var result = prepareSelection(cm);
  8355. // Move the hidden textarea near the cursor to prevent scrolling artifacts
  8356. if (cm.options.moveInputWithCursor) {
  8357. var headPos = cursorCoords(cm, doc.sel.primary().head, "div");
  8358. var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect();
  8359. result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10,
  8360. headPos.top + lineOff.top - wrapOff.top));
  8361. result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10,
  8362. headPos.left + lineOff.left - wrapOff.left));
  8363. }
  8364. return result
  8365. };
  8366. TextareaInput.prototype.showSelection = function (drawn) {
  8367. var cm = this.cm, display = cm.display;
  8368. removeChildrenAndAdd(display.cursorDiv, drawn.cursors);
  8369. removeChildrenAndAdd(display.selectionDiv, drawn.selection);
  8370. if (drawn.teTop != null) {
  8371. this.wrapper.style.top = drawn.teTop + "px";
  8372. this.wrapper.style.left = drawn.teLeft + "px";
  8373. }
  8374. };
  8375. // Reset the input to correspond to the selection (or to be empty,
  8376. // when not typing and nothing is selected)
  8377. TextareaInput.prototype.reset = function (typing) {
  8378. if (this.contextMenuPending || this.composing) { return }
  8379. var cm = this.cm;
  8380. if (cm.somethingSelected()) {
  8381. this.prevInput = "";
  8382. var content = cm.getSelection();
  8383. this.textarea.value = content;
  8384. if (cm.state.focused) { selectInput(this.textarea); }
  8385. if (ie && ie_version >= 9) { this.hasSelection = content; }
  8386. } else if (!typing) {
  8387. this.prevInput = this.textarea.value = "";
  8388. if (ie && ie_version >= 9) { this.hasSelection = null; }
  8389. }
  8390. };
  8391. TextareaInput.prototype.getField = function () { return this.textarea };
  8392. TextareaInput.prototype.supportsTouch = function () { return false };
  8393. TextareaInput.prototype.focus = function () {
  8394. if (this.cm.options.readOnly != "nocursor" && (!mobile || activeElt() != this.textarea)) {
  8395. try { this.textarea.focus(); }
  8396. catch (e) {} // IE8 will throw if the textarea is display: none or not in DOM
  8397. }
  8398. };
  8399. TextareaInput.prototype.blur = function () { this.textarea.blur(); };
  8400. TextareaInput.prototype.resetPosition = function () {
  8401. this.wrapper.style.top = this.wrapper.style.left = 0;
  8402. };
  8403. TextareaInput.prototype.receivedFocus = function () { this.slowPoll(); };
  8404. // Poll for input changes, using the normal rate of polling. This
  8405. // runs as long as the editor is focused.
  8406. TextareaInput.prototype.slowPoll = function () {
  8407. var this$1 = this;
  8408. if (this.pollingFast) { return }
  8409. this.polling.set(this.cm.options.pollInterval, function () {
  8410. this$1.poll();
  8411. if (this$1.cm.state.focused) { this$1.slowPoll(); }
  8412. });
  8413. };
  8414. // When an event has just come in that is likely to add or change
  8415. // something in the input textarea, we poll faster, to ensure that
  8416. // the change appears on the screen quickly.
  8417. TextareaInput.prototype.fastPoll = function () {
  8418. var missed = false, input = this;
  8419. input.pollingFast = true;
  8420. function p() {
  8421. var changed = input.poll();
  8422. if (!changed && !missed) {missed = true; input.polling.set(60, p);}
  8423. else {input.pollingFast = false; input.slowPoll();}
  8424. }
  8425. input.polling.set(20, p);
  8426. };
  8427. // Read input from the textarea, and update the document to match.
  8428. // When something is selected, it is present in the textarea, and
  8429. // selected (unless it is huge, in which case a placeholder is
  8430. // used). When nothing is selected, the cursor sits after previously
  8431. // seen text (can be empty), which is stored in prevInput (we must
  8432. // not reset the textarea when typing, because that breaks IME).
  8433. TextareaInput.prototype.poll = function () {
  8434. var this$1 = this;
  8435. var cm = this.cm, input = this.textarea, prevInput = this.prevInput;
  8436. // Since this is called a *lot*, try to bail out as cheaply as
  8437. // possible when it is clear that nothing happened. hasSelection
  8438. // will be the case when there is a lot of text in the textarea,
  8439. // in which case reading its value would be expensive.
  8440. if (this.contextMenuPending || !cm.state.focused ||
  8441. (hasSelection(input) && !prevInput && !this.composing) ||
  8442. cm.isReadOnly() || cm.options.disableInput || cm.state.keySeq)
  8443. { return false }
  8444. var text = input.value;
  8445. // If nothing changed, bail.
  8446. if (text == prevInput && !cm.somethingSelected()) { return false }
  8447. // Work around nonsensical selection resetting in IE9/10, and
  8448. // inexplicable appearance of private area unicode characters on
  8449. // some key combos in Mac (#2689).
  8450. if (ie && ie_version >= 9 && this.hasSelection === text ||
  8451. mac && /[\uf700-\uf7ff]/.test(text)) {
  8452. cm.display.input.reset();
  8453. return false
  8454. }
  8455. if (cm.doc.sel == cm.display.selForContextMenu) {
  8456. var first = text.charCodeAt(0);
  8457. if (first == 0x200b && !prevInput) { prevInput = "\u200b"; }
  8458. if (first == 0x21da) { this.reset(); return this.cm.execCommand("undo") }
  8459. }
  8460. // Find the part of the input that is actually new
  8461. var same = 0, l = Math.min(prevInput.length, text.length);
  8462. while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) { ++same; }
  8463. runInOp(cm, function () {
  8464. applyTextInput(cm, text.slice(same), prevInput.length - same,
  8465. null, this$1.composing ? "*compose" : null);
  8466. // Don't leave long text in the textarea, since it makes further polling slow
  8467. if (text.length > 1000 || text.indexOf("\n") > -1) { input.value = this$1.prevInput = ""; }
  8468. else { this$1.prevInput = text; }
  8469. if (this$1.composing) {
  8470. this$1.composing.range.clear();
  8471. this$1.composing.range = cm.markText(this$1.composing.start, cm.getCursor("to"),
  8472. {className: "CodeMirror-composing"});
  8473. }
  8474. });
  8475. return true
  8476. };
  8477. TextareaInput.prototype.ensurePolled = function () {
  8478. if (this.pollingFast && this.poll()) { this.pollingFast = false; }
  8479. };
  8480. TextareaInput.prototype.onKeyPress = function () {
  8481. if (ie && ie_version >= 9) { this.hasSelection = null; }
  8482. this.fastPoll();
  8483. };
  8484. TextareaInput.prototype.onContextMenu = function (e) {
  8485. var input = this, cm = input.cm, display = cm.display, te = input.textarea;
  8486. var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop;
  8487. if (!pos || presto) { return } // Opera is difficult.
  8488. // Reset the current text selection only if the click is done outside of the selection
  8489. // and 'resetSelectionOnContextMenu' option is true.
  8490. var reset = cm.options.resetSelectionOnContextMenu;
  8491. if (reset && cm.doc.sel.contains(pos) == -1)
  8492. { operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll); }
  8493. var oldCSS = te.style.cssText, oldWrapperCSS = input.wrapper.style.cssText;
  8494. input.wrapper.style.cssText = "position: absolute";
  8495. var wrapperBox = input.wrapper.getBoundingClientRect();
  8496. 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);";
  8497. var oldScrollY;
  8498. if (webkit) { oldScrollY = window.scrollY; } // Work around Chrome issue (#2712)
  8499. display.input.focus();
  8500. if (webkit) { window.scrollTo(null, oldScrollY); }
  8501. display.input.reset();
  8502. // Adds "Select all" to context menu in FF
  8503. if (!cm.somethingSelected()) { te.value = input.prevInput = " "; }
  8504. input.contextMenuPending = true;
  8505. display.selForContextMenu = cm.doc.sel;
  8506. clearTimeout(display.detectingSelectAll);
  8507. // Select-all will be greyed out if there's nothing to select, so
  8508. // this adds a zero-width space so that we can later check whether
  8509. // it got selected.
  8510. function prepareSelectAllHack() {
  8511. if (te.selectionStart != null) {
  8512. var selected = cm.somethingSelected();
  8513. var extval = "\u200b" + (selected ? te.value : "");
  8514. te.value = "\u21da"; // Used to catch context-menu undo
  8515. te.value = extval;
  8516. input.prevInput = selected ? "" : "\u200b";
  8517. te.selectionStart = 1; te.selectionEnd = extval.length;
  8518. // Re-set this, in case some other handler touched the
  8519. // selection in the meantime.
  8520. display.selForContextMenu = cm.doc.sel;
  8521. }
  8522. }
  8523. function rehide() {
  8524. input.contextMenuPending = false;
  8525. input.wrapper.style.cssText = oldWrapperCSS;
  8526. te.style.cssText = oldCSS;
  8527. if (ie && ie_version < 9) { display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos); }
  8528. // Try to detect the user choosing select-all
  8529. if (te.selectionStart != null) {
  8530. if (!ie || (ie && ie_version < 9)) { prepareSelectAllHack(); }
  8531. var i = 0, poll = function () {
  8532. if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0 &&
  8533. te.selectionEnd > 0 && input.prevInput == "\u200b") {
  8534. operation(cm, selectAll)(cm);
  8535. } else if (i++ < 10) {
  8536. display.detectingSelectAll = setTimeout(poll, 500);
  8537. } else {
  8538. display.selForContextMenu = null;
  8539. display.input.reset();
  8540. }
  8541. };
  8542. display.detectingSelectAll = setTimeout(poll, 200);
  8543. }
  8544. }
  8545. if (ie && ie_version >= 9) { prepareSelectAllHack(); }
  8546. if (captureRightClick) {
  8547. e_stop(e);
  8548. var mouseup = function () {
  8549. off(window, "mouseup", mouseup);
  8550. setTimeout(rehide, 20);
  8551. };
  8552. on(window, "mouseup", mouseup);
  8553. } else {
  8554. setTimeout(rehide, 50);
  8555. }
  8556. };
  8557. TextareaInput.prototype.readOnlyChanged = function (val) {
  8558. if (!val) { this.reset(); }
  8559. this.textarea.disabled = val == "nocursor";
  8560. };
  8561. TextareaInput.prototype.setUneditable = function () {};
  8562. TextareaInput.prototype.needsContentAttribute = false;
  8563. function fromTextArea(textarea, options) {
  8564. options = options ? copyObj(options) : {};
  8565. options.value = textarea.value;
  8566. if (!options.tabindex && textarea.tabIndex)
  8567. { options.tabindex = textarea.tabIndex; }
  8568. if (!options.placeholder && textarea.placeholder)
  8569. { options.placeholder = textarea.placeholder; }
  8570. // Set autofocus to true if this textarea is focused, or if it has
  8571. // autofocus and no other element is focused.
  8572. if (options.autofocus == null) {
  8573. var hasFocus = activeElt();
  8574. options.autofocus = hasFocus == textarea ||
  8575. textarea.getAttribute("autofocus") != null && hasFocus == document.body;
  8576. }
  8577. function save() {textarea.value = cm.getValue();}
  8578. var realSubmit;
  8579. if (textarea.form) {
  8580. on(textarea.form, "submit", save);
  8581. // Deplorable hack to make the submit method do the right thing.
  8582. if (!options.leaveSubmitMethodAlone) {
  8583. var form = textarea.form;
  8584. realSubmit = form.submit;
  8585. try {
  8586. var wrappedSubmit = form.submit = function () {
  8587. save();
  8588. form.submit = realSubmit;
  8589. form.submit();
  8590. form.submit = wrappedSubmit;
  8591. };
  8592. } catch(e) {}
  8593. }
  8594. }
  8595. options.finishInit = function (cm) {
  8596. cm.save = save;
  8597. cm.getTextArea = function () { return textarea; };
  8598. cm.toTextArea = function () {
  8599. cm.toTextArea = isNaN; // Prevent this from being ran twice
  8600. save();
  8601. textarea.parentNode.removeChild(cm.getWrapperElement());
  8602. textarea.style.display = "";
  8603. if (textarea.form) {
  8604. off(textarea.form, "submit", save);
  8605. if (typeof textarea.form.submit == "function")
  8606. { textarea.form.submit = realSubmit; }
  8607. }
  8608. };
  8609. };
  8610. textarea.style.display = "none";
  8611. var cm = CodeMirror$1(function (node) { return textarea.parentNode.insertBefore(node, textarea.nextSibling); },
  8612. options);
  8613. return cm
  8614. }
  8615. function addLegacyProps(CodeMirror) {
  8616. CodeMirror.off = off;
  8617. CodeMirror.on = on;
  8618. CodeMirror.wheelEventPixels = wheelEventPixels;
  8619. CodeMirror.Doc = Doc;
  8620. CodeMirror.splitLines = splitLinesAuto;
  8621. CodeMirror.countColumn = countColumn;
  8622. CodeMirror.findColumn = findColumn;
  8623. CodeMirror.isWordChar = isWordCharBasic;
  8624. CodeMirror.Pass = Pass;
  8625. CodeMirror.signal = signal;
  8626. CodeMirror.Line = Line;
  8627. CodeMirror.changeEnd = changeEnd;
  8628. CodeMirror.scrollbarModel = scrollbarModel;
  8629. CodeMirror.Pos = Pos;
  8630. CodeMirror.cmpPos = cmp;
  8631. CodeMirror.modes = modes;
  8632. CodeMirror.mimeModes = mimeModes;
  8633. CodeMirror.resolveMode = resolveMode;
  8634. CodeMirror.getMode = getMode;
  8635. CodeMirror.modeExtensions = modeExtensions;
  8636. CodeMirror.extendMode = extendMode;
  8637. CodeMirror.copyState = copyState;
  8638. CodeMirror.startState = startState;
  8639. CodeMirror.innerMode = innerMode;
  8640. CodeMirror.commands = commands;
  8641. CodeMirror.keyMap = keyMap;
  8642. CodeMirror.keyName = keyName;
  8643. CodeMirror.isModifierKey = isModifierKey;
  8644. CodeMirror.lookupKey = lookupKey;
  8645. CodeMirror.normalizeKeyMap = normalizeKeyMap;
  8646. CodeMirror.StringStream = StringStream;
  8647. CodeMirror.SharedTextMarker = SharedTextMarker;
  8648. CodeMirror.TextMarker = TextMarker;
  8649. CodeMirror.LineWidget = LineWidget;
  8650. CodeMirror.e_preventDefault = e_preventDefault;
  8651. CodeMirror.e_stopPropagation = e_stopPropagation;
  8652. CodeMirror.e_stop = e_stop;
  8653. CodeMirror.addClass = addClass;
  8654. CodeMirror.contains = contains;
  8655. CodeMirror.rmClass = rmClass;
  8656. CodeMirror.keyNames = keyNames;
  8657. }
  8658. // EDITOR CONSTRUCTOR
  8659. defineOptions(CodeMirror$1);
  8660. addEditorMethods(CodeMirror$1);
  8661. // Set up methods on CodeMirror's prototype to redirect to the editor's document.
  8662. var dontDelegate = "iter insert remove copy getEditor constructor".split(" ");
  8663. for (var prop in Doc.prototype) { if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0)
  8664. { CodeMirror$1.prototype[prop] = (function(method) {
  8665. return function() {return method.apply(this.doc, arguments)}
  8666. })(Doc.prototype[prop]); } }
  8667. eventMixin(Doc);
  8668. // INPUT HANDLING
  8669. CodeMirror$1.inputStyles = {"textarea": TextareaInput, "contenteditable": ContentEditableInput};
  8670. // MODE DEFINITION AND QUERYING
  8671. // Extra arguments are stored as the mode's dependencies, which is
  8672. // used by (legacy) mechanisms like loadmode.js to automatically
  8673. // load a mode. (Preferred mechanism is the require/define calls.)
  8674. CodeMirror$1.defineMode = function(name/*, mode, …*/) {
  8675. if (!CodeMirror$1.defaults.mode && name != "null") { CodeMirror$1.defaults.mode = name; }
  8676. defineMode.apply(this, arguments);
  8677. };
  8678. CodeMirror$1.defineMIME = defineMIME;
  8679. // Minimal default mode.
  8680. CodeMirror$1.defineMode("null", function () { return ({token: function (stream) { return stream.skipToEnd(); }}); });
  8681. CodeMirror$1.defineMIME("text/plain", "null");
  8682. // EXTENSIONS
  8683. CodeMirror$1.defineExtension = function (name, func) {
  8684. CodeMirror$1.prototype[name] = func;
  8685. };
  8686. CodeMirror$1.defineDocExtension = function (name, func) {
  8687. Doc.prototype[name] = func;
  8688. };
  8689. CodeMirror$1.fromTextArea = fromTextArea;
  8690. addLegacyProps(CodeMirror$1);
  8691. CodeMirror$1.version = "5.35.0";
  8692. return CodeMirror$1;
  8693. })));