Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

2 lat temu
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849
  1. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  2. // Distributed under an MIT license: https://codemirror.net/LICENSE
  3. // This is CodeMirror (https://codemirror.net), a code editor
  4. // implemented in JavaScript on top of the browser's DOM.
  5. //
  6. // You can find some technical background for some of the code below
  7. // at http://marijnhaverbeke.nl/blog/#cm-internals .
  8. (function (global, factory) {
  9. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  10. typeof define === 'function' && define.amd ? define(factory) :
  11. (global = global || self, 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 = safari && (/Mobile\/\w+/.test(userAgent) || navigator.maxTouchPoints > 2);
  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() {
  157. this.id = null;
  158. this.f = null;
  159. this.time = 0;
  160. this.handler = bind(this.onTimeout, this);
  161. };
  162. Delayed.prototype.onTimeout = function (self) {
  163. self.id = 0;
  164. if (self.time <= +new Date) {
  165. self.f();
  166. } else {
  167. setTimeout(self.handler, self.time - +new Date);
  168. }
  169. };
  170. Delayed.prototype.set = function (ms, f) {
  171. this.f = f;
  172. var time = +new Date + ms;
  173. if (!this.id || time < this.time) {
  174. clearTimeout(this.id);
  175. this.id = setTimeout(this.handler, ms);
  176. this.time = time;
  177. }
  178. };
  179. function indexOf(array, elt) {
  180. for (var i = 0; i < array.length; ++i)
  181. { if (array[i] == elt) { return i } }
  182. return -1
  183. }
  184. // Number of pixels added to scroller and sizer to hide scrollbar
  185. var scrollerGap = 50;
  186. // Returned or thrown by various protocols to signal 'I'm not
  187. // handling this'.
  188. var Pass = {toString: function(){return "CodeMirror.Pass"}};
  189. // Reused option objects for setSelection & friends
  190. var sel_dontScroll = {scroll: false}, sel_mouse = {origin: "*mouse"}, sel_move = {origin: "+move"};
  191. // The inverse of countColumn -- find the offset that corresponds to
  192. // a particular column.
  193. function findColumn(string, goal, tabSize) {
  194. for (var pos = 0, col = 0;;) {
  195. var nextTab = string.indexOf("\t", pos);
  196. if (nextTab == -1) { nextTab = string.length; }
  197. var skipped = nextTab - pos;
  198. if (nextTab == string.length || col + skipped >= goal)
  199. { return pos + Math.min(skipped, goal - col) }
  200. col += nextTab - pos;
  201. col += tabSize - (col % tabSize);
  202. pos = nextTab + 1;
  203. if (col >= goal) { return pos }
  204. }
  205. }
  206. var spaceStrs = [""];
  207. function spaceStr(n) {
  208. while (spaceStrs.length <= n)
  209. { spaceStrs.push(lst(spaceStrs) + " "); }
  210. return spaceStrs[n]
  211. }
  212. function lst(arr) { return arr[arr.length-1] }
  213. function map(array, f) {
  214. var out = [];
  215. for (var i = 0; i < array.length; i++) { out[i] = f(array[i], i); }
  216. return out
  217. }
  218. function insertSorted(array, value, score) {
  219. var pos = 0, priority = score(value);
  220. while (pos < array.length && score(array[pos]) <= priority) { pos++; }
  221. array.splice(pos, 0, value);
  222. }
  223. function nothing() {}
  224. function createObj(base, props) {
  225. var inst;
  226. if (Object.create) {
  227. inst = Object.create(base);
  228. } else {
  229. nothing.prototype = base;
  230. inst = new nothing();
  231. }
  232. if (props) { copyObj(props, inst); }
  233. return inst
  234. }
  235. var nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;
  236. function isWordCharBasic(ch) {
  237. return /\w/.test(ch) || ch > "\x80" &&
  238. (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch))
  239. }
  240. function isWordChar(ch, helper) {
  241. if (!helper) { return isWordCharBasic(ch) }
  242. if (helper.source.indexOf("\\w") > -1 && isWordCharBasic(ch)) { return true }
  243. return helper.test(ch)
  244. }
  245. function isEmpty(obj) {
  246. for (var n in obj) { if (obj.hasOwnProperty(n) && obj[n]) { return false } }
  247. return true
  248. }
  249. // Extending unicode characters. A series of a non-extending char +
  250. // any number of extending chars is treated as a single unit as far
  251. // as editing and measuring is concerned. This is not fully correct,
  252. // since some scripts/fonts/browsers also treat other configurations
  253. // of code points as a group.
  254. 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]/;
  255. function isExtendingChar(ch) { return ch.charCodeAt(0) >= 768 && extendingChars.test(ch) }
  256. // Returns a number from the range [`0`; `str.length`] unless `pos` is outside that range.
  257. function skipExtendingChars(str, pos, dir) {
  258. while ((dir < 0 ? pos > 0 : pos < str.length) && isExtendingChar(str.charAt(pos))) { pos += dir; }
  259. return pos
  260. }
  261. // Returns the value from the range [`from`; `to`] that satisfies
  262. // `pred` and is closest to `from`. Assumes that at least `to`
  263. // satisfies `pred`. Supports `from` being greater than `to`.
  264. function findFirst(pred, from, to) {
  265. // At any point we are certain `to` satisfies `pred`, don't know
  266. // whether `from` does.
  267. var dir = from > to ? -1 : 1;
  268. for (;;) {
  269. if (from == to) { return from }
  270. var midF = (from + to) / 2, mid = dir < 0 ? Math.ceil(midF) : Math.floor(midF);
  271. if (mid == from) { return pred(mid) ? from : to }
  272. if (pred(mid)) { to = mid; }
  273. else { from = mid + dir; }
  274. }
  275. }
  276. // BIDI HELPERS
  277. function iterateBidiSections(order, from, to, f) {
  278. if (!order) { return f(from, to, "ltr", 0) }
  279. var found = false;
  280. for (var i = 0; i < order.length; ++i) {
  281. var part = order[i];
  282. if (part.from < to && part.to > from || from == to && part.to == from) {
  283. f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr", i);
  284. found = true;
  285. }
  286. }
  287. if (!found) { f(from, to, "ltr"); }
  288. }
  289. var bidiOther = null;
  290. function getBidiPartAt(order, ch, sticky) {
  291. var found;
  292. bidiOther = null;
  293. for (var i = 0; i < order.length; ++i) {
  294. var cur = order[i];
  295. if (cur.from < ch && cur.to > ch) { return i }
  296. if (cur.to == ch) {
  297. if (cur.from != cur.to && sticky == "before") { found = i; }
  298. else { bidiOther = i; }
  299. }
  300. if (cur.from == ch) {
  301. if (cur.from != cur.to && sticky != "before") { found = i; }
  302. else { bidiOther = i; }
  303. }
  304. }
  305. return found != null ? found : bidiOther
  306. }
  307. // Bidirectional ordering algorithm
  308. // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm
  309. // that this (partially) implements.
  310. // One-char codes used for character types:
  311. // L (L): Left-to-Right
  312. // R (R): Right-to-Left
  313. // r (AL): Right-to-Left Arabic
  314. // 1 (EN): European Number
  315. // + (ES): European Number Separator
  316. // % (ET): European Number Terminator
  317. // n (AN): Arabic Number
  318. // , (CS): Common Number Separator
  319. // m (NSM): Non-Spacing Mark
  320. // b (BN): Boundary Neutral
  321. // s (B): Paragraph Separator
  322. // t (S): Segment Separator
  323. // w (WS): Whitespace
  324. // N (ON): Other Neutrals
  325. // Returns null if characters are ordered as they appear
  326. // (left-to-right), or an array of sections ({from, to, level}
  327. // objects) in the order in which they occur visually.
  328. var bidiOrdering = (function() {
  329. // Character types for codepoints 0 to 0xff
  330. var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN";
  331. // Character types for codepoints 0x600 to 0x6f9
  332. var arabicTypes = "nnnnnnNNr%%r,rNNmmmmmmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmmmnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmnNmmmmmmrrmmNmmmmrr1111111111";
  333. function charType(code) {
  334. if (code <= 0xf7) { return lowTypes.charAt(code) }
  335. else if (0x590 <= code && code <= 0x5f4) { return "R" }
  336. else if (0x600 <= code && code <= 0x6f9) { return arabicTypes.charAt(code - 0x600) }
  337. else if (0x6ee <= code && code <= 0x8ac) { return "r" }
  338. else if (0x2000 <= code && code <= 0x200b) { return "w" }
  339. else if (code == 0x200c) { return "b" }
  340. else { return "L" }
  341. }
  342. var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/;
  343. var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/;
  344. function BidiSpan(level, from, to) {
  345. this.level = level;
  346. this.from = from; this.to = to;
  347. }
  348. return function(str, direction) {
  349. var outerType = direction == "ltr" ? "L" : "R";
  350. if (str.length == 0 || direction == "ltr" && !bidiRE.test(str)) { return false }
  351. var len = str.length, types = [];
  352. for (var i = 0; i < len; ++i)
  353. { types.push(charType(str.charCodeAt(i))); }
  354. // W1. Examine each non-spacing mark (NSM) in the level run, and
  355. // change the type of the NSM to the type of the previous
  356. // character. If the NSM is at the start of the level run, it will
  357. // get the type of sor.
  358. for (var i$1 = 0, prev = outerType; i$1 < len; ++i$1) {
  359. var type = types[i$1];
  360. if (type == "m") { types[i$1] = prev; }
  361. else { prev = type; }
  362. }
  363. // W2. Search backwards from each instance of a European number
  364. // until the first strong type (R, L, AL, or sor) is found. If an
  365. // AL is found, change the type of the European number to Arabic
  366. // number.
  367. // W3. Change all ALs to R.
  368. for (var i$2 = 0, cur = outerType; i$2 < len; ++i$2) {
  369. var type$1 = types[i$2];
  370. if (type$1 == "1" && cur == "r") { types[i$2] = "n"; }
  371. else if (isStrong.test(type$1)) { cur = type$1; if (type$1 == "r") { types[i$2] = "R"; } }
  372. }
  373. // W4. A single European separator between two European numbers
  374. // changes to a European number. A single common separator between
  375. // two numbers of the same type changes to that type.
  376. for (var i$3 = 1, prev$1 = types[0]; i$3 < len - 1; ++i$3) {
  377. var type$2 = types[i$3];
  378. if (type$2 == "+" && prev$1 == "1" && types[i$3+1] == "1") { types[i$3] = "1"; }
  379. else if (type$2 == "," && prev$1 == types[i$3+1] &&
  380. (prev$1 == "1" || prev$1 == "n")) { types[i$3] = prev$1; }
  381. prev$1 = type$2;
  382. }
  383. // W5. A sequence of European terminators adjacent to European
  384. // numbers changes to all European numbers.
  385. // W6. Otherwise, separators and terminators change to Other
  386. // Neutral.
  387. for (var i$4 = 0; i$4 < len; ++i$4) {
  388. var type$3 = types[i$4];
  389. if (type$3 == ",") { types[i$4] = "N"; }
  390. else if (type$3 == "%") {
  391. var end = (void 0);
  392. for (end = i$4 + 1; end < len && types[end] == "%"; ++end) {}
  393. var replace = (i$4 && types[i$4-1] == "!") || (end < len && types[end] == "1") ? "1" : "N";
  394. for (var j = i$4; j < end; ++j) { types[j] = replace; }
  395. i$4 = end - 1;
  396. }
  397. }
  398. // W7. Search backwards from each instance of a European number
  399. // until the first strong type (R, L, or sor) is found. If an L is
  400. // found, then change the type of the European number to L.
  401. for (var i$5 = 0, cur$1 = outerType; i$5 < len; ++i$5) {
  402. var type$4 = types[i$5];
  403. if (cur$1 == "L" && type$4 == "1") { types[i$5] = "L"; }
  404. else if (isStrong.test(type$4)) { cur$1 = type$4; }
  405. }
  406. // N1. A sequence of neutrals takes the direction of the
  407. // surrounding strong text if the text on both sides has the same
  408. // direction. European and Arabic numbers act as if they were R in
  409. // terms of their influence on neutrals. Start-of-level-run (sor)
  410. // and end-of-level-run (eor) are used at level run boundaries.
  411. // N2. Any remaining neutrals take the embedding direction.
  412. for (var i$6 = 0; i$6 < len; ++i$6) {
  413. if (isNeutral.test(types[i$6])) {
  414. var end$1 = (void 0);
  415. for (end$1 = i$6 + 1; end$1 < len && isNeutral.test(types[end$1]); ++end$1) {}
  416. var before = (i$6 ? types[i$6-1] : outerType) == "L";
  417. var after = (end$1 < len ? types[end$1] : outerType) == "L";
  418. var replace$1 = before == after ? (before ? "L" : "R") : outerType;
  419. for (var j$1 = i$6; j$1 < end$1; ++j$1) { types[j$1] = replace$1; }
  420. i$6 = end$1 - 1;
  421. }
  422. }
  423. // Here we depart from the documented algorithm, in order to avoid
  424. // building up an actual levels array. Since there are only three
  425. // levels (0, 1, 2) in an implementation that doesn't take
  426. // explicit embedding into account, we can build up the order on
  427. // the fly, without following the level-based algorithm.
  428. var order = [], m;
  429. for (var i$7 = 0; i$7 < len;) {
  430. if (countsAsLeft.test(types[i$7])) {
  431. var start = i$7;
  432. for (++i$7; i$7 < len && countsAsLeft.test(types[i$7]); ++i$7) {}
  433. order.push(new BidiSpan(0, start, i$7));
  434. } else {
  435. var pos = i$7, at = order.length, isRTL = direction == "rtl" ? 1 : 0;
  436. for (++i$7; i$7 < len && types[i$7] != "L"; ++i$7) {}
  437. for (var j$2 = pos; j$2 < i$7;) {
  438. if (countsAsNum.test(types[j$2])) {
  439. if (pos < j$2) { order.splice(at, 0, new BidiSpan(1, pos, j$2)); at += isRTL; }
  440. var nstart = j$2;
  441. for (++j$2; j$2 < i$7 && countsAsNum.test(types[j$2]); ++j$2) {}
  442. order.splice(at, 0, new BidiSpan(2, nstart, j$2));
  443. at += isRTL;
  444. pos = j$2;
  445. } else { ++j$2; }
  446. }
  447. if (pos < i$7) { order.splice(at, 0, new BidiSpan(1, pos, i$7)); }
  448. }
  449. }
  450. if (direction == "ltr") {
  451. if (order[0].level == 1 && (m = str.match(/^\s+/))) {
  452. order[0].from = m[0].length;
  453. order.unshift(new BidiSpan(0, 0, m[0].length));
  454. }
  455. if (lst(order).level == 1 && (m = str.match(/\s+$/))) {
  456. lst(order).to -= m[0].length;
  457. order.push(new BidiSpan(0, len - m[0].length, len));
  458. }
  459. }
  460. return direction == "rtl" ? order.reverse() : order
  461. }
  462. })();
  463. // Get the bidi ordering for the given line (and cache it). Returns
  464. // false for lines that are fully left-to-right, and an array of
  465. // BidiSpan objects otherwise.
  466. function getOrder(line, direction) {
  467. var order = line.order;
  468. if (order == null) { order = line.order = bidiOrdering(line.text, direction); }
  469. return order
  470. }
  471. // EVENT HANDLING
  472. // Lightweight event framework. on/off also work on DOM nodes,
  473. // registering native DOM handlers.
  474. var noHandlers = [];
  475. var on = function(emitter, type, f) {
  476. if (emitter.addEventListener) {
  477. emitter.addEventListener(type, f, false);
  478. } else if (emitter.attachEvent) {
  479. emitter.attachEvent("on" + type, f);
  480. } else {
  481. var map = emitter._handlers || (emitter._handlers = {});
  482. map[type] = (map[type] || noHandlers).concat(f);
  483. }
  484. };
  485. function getHandlers(emitter, type) {
  486. return emitter._handlers && emitter._handlers[type] || noHandlers
  487. }
  488. function off(emitter, type, f) {
  489. if (emitter.removeEventListener) {
  490. emitter.removeEventListener(type, f, false);
  491. } else if (emitter.detachEvent) {
  492. emitter.detachEvent("on" + type, f);
  493. } else {
  494. var map = emitter._handlers, arr = map && map[type];
  495. if (arr) {
  496. var index = indexOf(arr, f);
  497. if (index > -1)
  498. { map[type] = arr.slice(0, index).concat(arr.slice(index + 1)); }
  499. }
  500. }
  501. }
  502. function signal(emitter, type /*, values...*/) {
  503. var handlers = getHandlers(emitter, type);
  504. if (!handlers.length) { return }
  505. var args = Array.prototype.slice.call(arguments, 2);
  506. for (var i = 0; i < handlers.length; ++i) { handlers[i].apply(null, args); }
  507. }
  508. // The DOM events that CodeMirror handles can be overridden by
  509. // registering a (non-DOM) handler on the editor for the event name,
  510. // and preventDefault-ing the event in that handler.
  511. function signalDOMEvent(cm, e, override) {
  512. if (typeof e == "string")
  513. { e = {type: e, preventDefault: function() { this.defaultPrevented = true; }}; }
  514. signal(cm, override || e.type, cm, e);
  515. return e_defaultPrevented(e) || e.codemirrorIgnore
  516. }
  517. function signalCursorActivity(cm) {
  518. var arr = cm._handlers && cm._handlers.cursorActivity;
  519. if (!arr) { return }
  520. var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = []);
  521. for (var i = 0; i < arr.length; ++i) { if (indexOf(set, arr[i]) == -1)
  522. { set.push(arr[i]); } }
  523. }
  524. function hasHandler(emitter, type) {
  525. return getHandlers(emitter, type).length > 0
  526. }
  527. // Add on and off methods to a constructor's prototype, to make
  528. // registering events on such objects more convenient.
  529. function eventMixin(ctor) {
  530. ctor.prototype.on = function(type, f) {on(this, type, f);};
  531. ctor.prototype.off = function(type, f) {off(this, type, f);};
  532. }
  533. // Due to the fact that we still support jurassic IE versions, some
  534. // compatibility wrappers are needed.
  535. function e_preventDefault(e) {
  536. if (e.preventDefault) { e.preventDefault(); }
  537. else { e.returnValue = false; }
  538. }
  539. function e_stopPropagation(e) {
  540. if (e.stopPropagation) { e.stopPropagation(); }
  541. else { e.cancelBubble = true; }
  542. }
  543. function e_defaultPrevented(e) {
  544. return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false
  545. }
  546. function e_stop(e) {e_preventDefault(e); e_stopPropagation(e);}
  547. function e_target(e) {return e.target || e.srcElement}
  548. function e_button(e) {
  549. var b = e.which;
  550. if (b == null) {
  551. if (e.button & 1) { b = 1; }
  552. else if (e.button & 2) { b = 3; }
  553. else if (e.button & 4) { b = 2; }
  554. }
  555. if (mac && e.ctrlKey && b == 1) { b = 3; }
  556. return b
  557. }
  558. // Detect drag-and-drop
  559. var dragAndDrop = function() {
  560. // There is *some* kind of drag-and-drop support in IE6-8, but I
  561. // couldn't get it to work yet.
  562. if (ie && ie_version < 9) { return false }
  563. var div = elt('div');
  564. return "draggable" in div || "dragDrop" in div
  565. }();
  566. var zwspSupported;
  567. function zeroWidthElement(measure) {
  568. if (zwspSupported == null) {
  569. var test = elt("span", "\u200b");
  570. removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")]));
  571. if (measure.firstChild.offsetHeight != 0)
  572. { zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8); }
  573. }
  574. var node = zwspSupported ? elt("span", "\u200b") :
  575. elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px");
  576. node.setAttribute("cm-text", "");
  577. return node
  578. }
  579. // Feature-detect IE's crummy client rect reporting for bidi text
  580. var badBidiRects;
  581. function hasBadBidiRects(measure) {
  582. if (badBidiRects != null) { return badBidiRects }
  583. var txt = removeChildrenAndAdd(measure, document.createTextNode("A\u062eA"));
  584. var r0 = range(txt, 0, 1).getBoundingClientRect();
  585. var r1 = range(txt, 1, 2).getBoundingClientRect();
  586. removeChildren(measure);
  587. if (!r0 || r0.left == r0.right) { return false } // Safari returns null in some cases (#2780)
  588. return badBidiRects = (r1.right - r0.right < 3)
  589. }
  590. // See if "".split is the broken IE version, if so, provide an
  591. // alternative way to split lines.
  592. var splitLinesAuto = "\n\nb".split(/\n/).length != 3 ? function (string) {
  593. var pos = 0, result = [], l = string.length;
  594. while (pos <= l) {
  595. var nl = string.indexOf("\n", pos);
  596. if (nl == -1) { nl = string.length; }
  597. var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl);
  598. var rt = line.indexOf("\r");
  599. if (rt != -1) {
  600. result.push(line.slice(0, rt));
  601. pos += rt + 1;
  602. } else {
  603. result.push(line);
  604. pos = nl + 1;
  605. }
  606. }
  607. return result
  608. } : function (string) { return string.split(/\r\n?|\n/); };
  609. var hasSelection = window.getSelection ? function (te) {
  610. try { return te.selectionStart != te.selectionEnd }
  611. catch(e) { return false }
  612. } : function (te) {
  613. var range;
  614. try {range = te.ownerDocument.selection.createRange();}
  615. catch(e) {}
  616. if (!range || range.parentElement() != te) { return false }
  617. return range.compareEndPoints("StartToEnd", range) != 0
  618. };
  619. var hasCopyEvent = (function () {
  620. var e = elt("div");
  621. if ("oncopy" in e) { return true }
  622. e.setAttribute("oncopy", "return;");
  623. return typeof e.oncopy == "function"
  624. })();
  625. var badZoomedRects = null;
  626. function hasBadZoomedRects(measure) {
  627. if (badZoomedRects != null) { return badZoomedRects }
  628. var node = removeChildrenAndAdd(measure, elt("span", "x"));
  629. var normal = node.getBoundingClientRect();
  630. var fromRange = range(node, 0, 1).getBoundingClientRect();
  631. return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1
  632. }
  633. // Known modes, by name and by MIME
  634. var modes = {}, mimeModes = {};
  635. // Extra arguments are stored as the mode's dependencies, which is
  636. // used by (legacy) mechanisms like loadmode.js to automatically
  637. // load a mode. (Preferred mechanism is the require/define calls.)
  638. function defineMode(name, mode) {
  639. if (arguments.length > 2)
  640. { mode.dependencies = Array.prototype.slice.call(arguments, 2); }
  641. modes[name] = mode;
  642. }
  643. function defineMIME(mime, spec) {
  644. mimeModes[mime] = spec;
  645. }
  646. // Given a MIME type, a {name, ...options} config object, or a name
  647. // string, return a mode config object.
  648. function resolveMode(spec) {
  649. if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) {
  650. spec = mimeModes[spec];
  651. } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) {
  652. var found = mimeModes[spec.name];
  653. if (typeof found == "string") { found = {name: found}; }
  654. spec = createObj(found, spec);
  655. spec.name = found.name;
  656. } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) {
  657. return resolveMode("application/xml")
  658. } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+json$/.test(spec)) {
  659. return resolveMode("application/json")
  660. }
  661. if (typeof spec == "string") { return {name: spec} }
  662. else { return spec || {name: "null"} }
  663. }
  664. // Given a mode spec (anything that resolveMode accepts), find and
  665. // initialize an actual mode object.
  666. function getMode(options, spec) {
  667. spec = resolveMode(spec);
  668. var mfactory = modes[spec.name];
  669. if (!mfactory) { return getMode(options, "text/plain") }
  670. var modeObj = mfactory(options, spec);
  671. if (modeExtensions.hasOwnProperty(spec.name)) {
  672. var exts = modeExtensions[spec.name];
  673. for (var prop in exts) {
  674. if (!exts.hasOwnProperty(prop)) { continue }
  675. if (modeObj.hasOwnProperty(prop)) { modeObj["_" + prop] = modeObj[prop]; }
  676. modeObj[prop] = exts[prop];
  677. }
  678. }
  679. modeObj.name = spec.name;
  680. if (spec.helperType) { modeObj.helperType = spec.helperType; }
  681. if (spec.modeProps) { for (var prop$1 in spec.modeProps)
  682. { modeObj[prop$1] = spec.modeProps[prop$1]; } }
  683. return modeObj
  684. }
  685. // This can be used to attach properties to mode objects from
  686. // outside the actual mode definition.
  687. var modeExtensions = {};
  688. function extendMode(mode, properties) {
  689. var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {});
  690. copyObj(properties, exts);
  691. }
  692. function copyState(mode, state) {
  693. if (state === true) { return state }
  694. if (mode.copyState) { return mode.copyState(state) }
  695. var nstate = {};
  696. for (var n in state) {
  697. var val = state[n];
  698. if (val instanceof Array) { val = val.concat([]); }
  699. nstate[n] = val;
  700. }
  701. return nstate
  702. }
  703. // Given a mode and a state (for that mode), find the inner mode and
  704. // state at the position that the state refers to.
  705. function innerMode(mode, state) {
  706. var info;
  707. while (mode.innerMode) {
  708. info = mode.innerMode(state);
  709. if (!info || info.mode == mode) { break }
  710. state = info.state;
  711. mode = info.mode;
  712. }
  713. return info || {mode: mode, state: state}
  714. }
  715. function startState(mode, a1, a2) {
  716. return mode.startState ? mode.startState(a1, a2) : true
  717. }
  718. // STRING STREAM
  719. // Fed to the mode parsers, provides helper functions to make
  720. // parsers more succinct.
  721. var StringStream = function(string, tabSize, lineOracle) {
  722. this.pos = this.start = 0;
  723. this.string = string;
  724. this.tabSize = tabSize || 8;
  725. this.lastColumnPos = this.lastColumnValue = 0;
  726. this.lineStart = 0;
  727. this.lineOracle = lineOracle;
  728. };
  729. StringStream.prototype.eol = function () {return this.pos >= this.string.length};
  730. StringStream.prototype.sol = function () {return this.pos == this.lineStart};
  731. StringStream.prototype.peek = function () {return this.string.charAt(this.pos) || undefined};
  732. StringStream.prototype.next = function () {
  733. if (this.pos < this.string.length)
  734. { return this.string.charAt(this.pos++) }
  735. };
  736. StringStream.prototype.eat = function (match) {
  737. var ch = this.string.charAt(this.pos);
  738. var ok;
  739. if (typeof match == "string") { ok = ch == match; }
  740. else { ok = ch && (match.test ? match.test(ch) : match(ch)); }
  741. if (ok) {++this.pos; return ch}
  742. };
  743. StringStream.prototype.eatWhile = function (match) {
  744. var start = this.pos;
  745. while (this.eat(match)){}
  746. return this.pos > start
  747. };
  748. StringStream.prototype.eatSpace = function () {
  749. var start = this.pos;
  750. while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) { ++this.pos; }
  751. return this.pos > start
  752. };
  753. StringStream.prototype.skipToEnd = function () {this.pos = this.string.length;};
  754. StringStream.prototype.skipTo = function (ch) {
  755. var found = this.string.indexOf(ch, this.pos);
  756. if (found > -1) {this.pos = found; return true}
  757. };
  758. StringStream.prototype.backUp = function (n) {this.pos -= n;};
  759. StringStream.prototype.column = function () {
  760. if (this.lastColumnPos < this.start) {
  761. this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue);
  762. this.lastColumnPos = this.start;
  763. }
  764. return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0)
  765. };
  766. StringStream.prototype.indentation = function () {
  767. return countColumn(this.string, null, this.tabSize) -
  768. (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0)
  769. };
  770. StringStream.prototype.match = function (pattern, consume, caseInsensitive) {
  771. if (typeof pattern == "string") {
  772. var cased = function (str) { return caseInsensitive ? str.toLowerCase() : str; };
  773. var substr = this.string.substr(this.pos, pattern.length);
  774. if (cased(substr) == cased(pattern)) {
  775. if (consume !== false) { this.pos += pattern.length; }
  776. return true
  777. }
  778. } else {
  779. var match = this.string.slice(this.pos).match(pattern);
  780. if (match && match.index > 0) { return null }
  781. if (match && consume !== false) { this.pos += match[0].length; }
  782. return match
  783. }
  784. };
  785. StringStream.prototype.current = function (){return this.string.slice(this.start, this.pos)};
  786. StringStream.prototype.hideFirstChars = function (n, inner) {
  787. this.lineStart += n;
  788. try { return inner() }
  789. finally { this.lineStart -= n; }
  790. };
  791. StringStream.prototype.lookAhead = function (n) {
  792. var oracle = this.lineOracle;
  793. return oracle && oracle.lookAhead(n)
  794. };
  795. StringStream.prototype.baseToken = function () {
  796. var oracle = this.lineOracle;
  797. return oracle && oracle.baseToken(this.pos)
  798. };
  799. // Find the line object corresponding to the given line number.
  800. function getLine(doc, n) {
  801. n -= doc.first;
  802. if (n < 0 || n >= doc.size) { throw new Error("There is no line " + (n + doc.first) + " in the document.") }
  803. var chunk = doc;
  804. while (!chunk.lines) {
  805. for (var i = 0;; ++i) {
  806. var child = chunk.children[i], sz = child.chunkSize();
  807. if (n < sz) { chunk = child; break }
  808. n -= sz;
  809. }
  810. }
  811. return chunk.lines[n]
  812. }
  813. // Get the part of a document between two positions, as an array of
  814. // strings.
  815. function getBetween(doc, start, end) {
  816. var out = [], n = start.line;
  817. doc.iter(start.line, end.line + 1, function (line) {
  818. var text = line.text;
  819. if (n == end.line) { text = text.slice(0, end.ch); }
  820. if (n == start.line) { text = text.slice(start.ch); }
  821. out.push(text);
  822. ++n;
  823. });
  824. return out
  825. }
  826. // Get the lines between from and to, as array of strings.
  827. function getLines(doc, from, to) {
  828. var out = [];
  829. doc.iter(from, to, function (line) { out.push(line.text); }); // iter aborts when callback returns truthy value
  830. return out
  831. }
  832. // Update the height of a line, propagating the height change
  833. // upwards to parent nodes.
  834. function updateLineHeight(line, height) {
  835. var diff = height - line.height;
  836. if (diff) { for (var n = line; n; n = n.parent) { n.height += diff; } }
  837. }
  838. // Given a line object, find its line number by walking up through
  839. // its parent links.
  840. function lineNo(line) {
  841. if (line.parent == null) { return null }
  842. var cur = line.parent, no = indexOf(cur.lines, line);
  843. for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) {
  844. for (var i = 0;; ++i) {
  845. if (chunk.children[i] == cur) { break }
  846. no += chunk.children[i].chunkSize();
  847. }
  848. }
  849. return no + cur.first
  850. }
  851. // Find the line at the given vertical position, using the height
  852. // information in the document tree.
  853. function lineAtHeight(chunk, h) {
  854. var n = chunk.first;
  855. outer: do {
  856. for (var i$1 = 0; i$1 < chunk.children.length; ++i$1) {
  857. var child = chunk.children[i$1], ch = child.height;
  858. if (h < ch) { chunk = child; continue outer }
  859. h -= ch;
  860. n += child.chunkSize();
  861. }
  862. return n
  863. } while (!chunk.lines)
  864. var i = 0;
  865. for (; i < chunk.lines.length; ++i) {
  866. var line = chunk.lines[i], lh = line.height;
  867. if (h < lh) { break }
  868. h -= lh;
  869. }
  870. return n + i
  871. }
  872. function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size}
  873. function lineNumberFor(options, i) {
  874. return String(options.lineNumberFormatter(i + options.firstLineNumber))
  875. }
  876. // A Pos instance represents a position within the text.
  877. function Pos(line, ch, sticky) {
  878. if ( sticky === void 0 ) sticky = null;
  879. if (!(this instanceof Pos)) { return new Pos(line, ch, sticky) }
  880. this.line = line;
  881. this.ch = ch;
  882. this.sticky = sticky;
  883. }
  884. // Compare two positions, return 0 if they are the same, a negative
  885. // number when a is less, and a positive number otherwise.
  886. function cmp(a, b) { return a.line - b.line || a.ch - b.ch }
  887. function equalCursorPos(a, b) { return a.sticky == b.sticky && cmp(a, b) == 0 }
  888. function copyPos(x) {return Pos(x.line, x.ch)}
  889. function maxPos(a, b) { return cmp(a, b) < 0 ? b : a }
  890. function minPos(a, b) { return cmp(a, b) < 0 ? a : b }
  891. // Most of the external API clips given positions to make sure they
  892. // actually exist within the document.
  893. function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1))}
  894. function clipPos(doc, pos) {
  895. if (pos.line < doc.first) { return Pos(doc.first, 0) }
  896. var last = doc.first + doc.size - 1;
  897. if (pos.line > last) { return Pos(last, getLine(doc, last).text.length) }
  898. return clipToLen(pos, getLine(doc, pos.line).text.length)
  899. }
  900. function clipToLen(pos, linelen) {
  901. var ch = pos.ch;
  902. if (ch == null || ch > linelen) { return Pos(pos.line, linelen) }
  903. else if (ch < 0) { return Pos(pos.line, 0) }
  904. else { return pos }
  905. }
  906. function clipPosArray(doc, array) {
  907. var out = [];
  908. for (var i = 0; i < array.length; i++) { out[i] = clipPos(doc, array[i]); }
  909. return out
  910. }
  911. var SavedContext = function(state, lookAhead) {
  912. this.state = state;
  913. this.lookAhead = lookAhead;
  914. };
  915. var Context = function(doc, state, line, lookAhead) {
  916. this.state = state;
  917. this.doc = doc;
  918. this.line = line;
  919. this.maxLookAhead = lookAhead || 0;
  920. this.baseTokens = null;
  921. this.baseTokenPos = 1;
  922. };
  923. Context.prototype.lookAhead = function (n) {
  924. var line = this.doc.getLine(this.line + n);
  925. if (line != null && n > this.maxLookAhead) { this.maxLookAhead = n; }
  926. return line
  927. };
  928. Context.prototype.baseToken = function (n) {
  929. if (!this.baseTokens) { return null }
  930. while (this.baseTokens[this.baseTokenPos] <= n)
  931. { this.baseTokenPos += 2; }
  932. var type = this.baseTokens[this.baseTokenPos + 1];
  933. return {type: type && type.replace(/( |^)overlay .*/, ""),
  934. size: this.baseTokens[this.baseTokenPos] - n}
  935. };
  936. Context.prototype.nextLine = function () {
  937. this.line++;
  938. if (this.maxLookAhead > 0) { this.maxLookAhead--; }
  939. };
  940. Context.fromSaved = function (doc, saved, line) {
  941. if (saved instanceof SavedContext)
  942. { return new Context(doc, copyState(doc.mode, saved.state), line, saved.lookAhead) }
  943. else
  944. { return new Context(doc, copyState(doc.mode, saved), line) }
  945. };
  946. Context.prototype.save = function (copy) {
  947. var state = copy !== false ? copyState(this.doc.mode, this.state) : this.state;
  948. return this.maxLookAhead > 0 ? new SavedContext(state, this.maxLookAhead) : state
  949. };
  950. // Compute a style array (an array starting with a mode generation
  951. // -- for invalidation -- followed by pairs of end positions and
  952. // style strings), which is used to highlight the tokens on the
  953. // line.
  954. function highlightLine(cm, line, context, forceToEnd) {
  955. // A styles array always starts with a number identifying the
  956. // mode/overlays that it is based on (for easy invalidation).
  957. var st = [cm.state.modeGen], lineClasses = {};
  958. // Compute the base array of styles
  959. runMode(cm, line.text, cm.doc.mode, context, function (end, style) { return st.push(end, style); },
  960. lineClasses, forceToEnd);
  961. var state = context.state;
  962. // Run overlays, adjust style array.
  963. var loop = function ( o ) {
  964. context.baseTokens = st;
  965. var overlay = cm.state.overlays[o], i = 1, at = 0;
  966. context.state = true;
  967. runMode(cm, line.text, overlay.mode, context, function (end, style) {
  968. var start = i;
  969. // Ensure there's a token end at the current position, and that i points at it
  970. while (at < end) {
  971. var i_end = st[i];
  972. if (i_end > end)
  973. { st.splice(i, 1, end, st[i+1], i_end); }
  974. i += 2;
  975. at = Math.min(end, i_end);
  976. }
  977. if (!style) { return }
  978. if (overlay.opaque) {
  979. st.splice(start, i - start, end, "overlay " + style);
  980. i = start + 2;
  981. } else {
  982. for (; start < i; start += 2) {
  983. var cur = st[start+1];
  984. st[start+1] = (cur ? cur + " " : "") + "overlay " + style;
  985. }
  986. }
  987. }, lineClasses);
  988. context.state = state;
  989. context.baseTokens = null;
  990. context.baseTokenPos = 1;
  991. };
  992. for (var o = 0; o < cm.state.overlays.length; ++o) loop( o );
  993. return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null}
  994. }
  995. function getLineStyles(cm, line, updateFrontier) {
  996. if (!line.styles || line.styles[0] != cm.state.modeGen) {
  997. var context = getContextBefore(cm, lineNo(line));
  998. var resetState = line.text.length > cm.options.maxHighlightLength && copyState(cm.doc.mode, context.state);
  999. var result = highlightLine(cm, line, context);
  1000. if (resetState) { context.state = resetState; }
  1001. line.stateAfter = context.save(!resetState);
  1002. line.styles = result.styles;
  1003. if (result.classes) { line.styleClasses = result.classes; }
  1004. else if (line.styleClasses) { line.styleClasses = null; }
  1005. if (updateFrontier === cm.doc.highlightFrontier)
  1006. { cm.doc.modeFrontier = Math.max(cm.doc.modeFrontier, ++cm.doc.highlightFrontier); }
  1007. }
  1008. return line.styles
  1009. }
  1010. function getContextBefore(cm, n, precise) {
  1011. var doc = cm.doc, display = cm.display;
  1012. if (!doc.mode.startState) { return new Context(doc, true, n) }
  1013. var start = findStartLine(cm, n, precise);
  1014. var saved = start > doc.first && getLine(doc, start - 1).stateAfter;
  1015. var context = saved ? Context.fromSaved(doc, saved, start) : new Context(doc, startState(doc.mode), start);
  1016. doc.iter(start, n, function (line) {
  1017. processLine(cm, line.text, context);
  1018. var pos = context.line;
  1019. line.stateAfter = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo ? context.save() : null;
  1020. context.nextLine();
  1021. });
  1022. if (precise) { doc.modeFrontier = context.line; }
  1023. return context
  1024. }
  1025. // Lightweight form of highlight -- proceed over this line and
  1026. // update state, but don't save a style array. Used for lines that
  1027. // aren't currently visible.
  1028. function processLine(cm, text, context, startAt) {
  1029. var mode = cm.doc.mode;
  1030. var stream = new StringStream(text, cm.options.tabSize, context);
  1031. stream.start = stream.pos = startAt || 0;
  1032. if (text == "") { callBlankLine(mode, context.state); }
  1033. while (!stream.eol()) {
  1034. readToken(mode, stream, context.state);
  1035. stream.start = stream.pos;
  1036. }
  1037. }
  1038. function callBlankLine(mode, state) {
  1039. if (mode.blankLine) { return mode.blankLine(state) }
  1040. if (!mode.innerMode) { return }
  1041. var inner = innerMode(mode, state);
  1042. if (inner.mode.blankLine) { return inner.mode.blankLine(inner.state) }
  1043. }
  1044. function readToken(mode, stream, state, inner) {
  1045. for (var i = 0; i < 10; i++) {
  1046. if (inner) { inner[0] = innerMode(mode, state).mode; }
  1047. var style = mode.token(stream, state);
  1048. if (stream.pos > stream.start) { return style }
  1049. }
  1050. throw new Error("Mode " + mode.name + " failed to advance stream.")
  1051. }
  1052. var Token = function(stream, type, state) {
  1053. this.start = stream.start; this.end = stream.pos;
  1054. this.string = stream.current();
  1055. this.type = type || null;
  1056. this.state = state;
  1057. };
  1058. // Utility for getTokenAt and getLineTokens
  1059. function takeToken(cm, pos, precise, asArray) {
  1060. var doc = cm.doc, mode = doc.mode, style;
  1061. pos = clipPos(doc, pos);
  1062. var line = getLine(doc, pos.line), context = getContextBefore(cm, pos.line, precise);
  1063. var stream = new StringStream(line.text, cm.options.tabSize, context), tokens;
  1064. if (asArray) { tokens = []; }
  1065. while ((asArray || stream.pos < pos.ch) && !stream.eol()) {
  1066. stream.start = stream.pos;
  1067. style = readToken(mode, stream, context.state);
  1068. if (asArray) { tokens.push(new Token(stream, style, copyState(doc.mode, context.state))); }
  1069. }
  1070. return asArray ? tokens : new Token(stream, style, context.state)
  1071. }
  1072. function extractLineClasses(type, output) {
  1073. if (type) { for (;;) {
  1074. var lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/);
  1075. if (!lineClass) { break }
  1076. type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length);
  1077. var prop = lineClass[1] ? "bgClass" : "textClass";
  1078. if (output[prop] == null)
  1079. { output[prop] = lineClass[2]; }
  1080. else if (!(new RegExp("(?:^|\\s)" + lineClass[2] + "(?:$|\\s)")).test(output[prop]))
  1081. { output[prop] += " " + lineClass[2]; }
  1082. } }
  1083. return type
  1084. }
  1085. // Run the given mode's parser over a line, calling f for each token.
  1086. function runMode(cm, text, mode, context, f, lineClasses, forceToEnd) {
  1087. var flattenSpans = mode.flattenSpans;
  1088. if (flattenSpans == null) { flattenSpans = cm.options.flattenSpans; }
  1089. var curStart = 0, curStyle = null;
  1090. var stream = new StringStream(text, cm.options.tabSize, context), style;
  1091. var inner = cm.options.addModeClass && [null];
  1092. if (text == "") { extractLineClasses(callBlankLine(mode, context.state), lineClasses); }
  1093. while (!stream.eol()) {
  1094. if (stream.pos > cm.options.maxHighlightLength) {
  1095. flattenSpans = false;
  1096. if (forceToEnd) { processLine(cm, text, context, stream.pos); }
  1097. stream.pos = text.length;
  1098. style = null;
  1099. } else {
  1100. style = extractLineClasses(readToken(mode, stream, context.state, inner), lineClasses);
  1101. }
  1102. if (inner) {
  1103. var mName = inner[0].name;
  1104. if (mName) { style = "m-" + (style ? mName + " " + style : mName); }
  1105. }
  1106. if (!flattenSpans || curStyle != style) {
  1107. while (curStart < stream.start) {
  1108. curStart = Math.min(stream.start, curStart + 5000);
  1109. f(curStart, curStyle);
  1110. }
  1111. curStyle = style;
  1112. }
  1113. stream.start = stream.pos;
  1114. }
  1115. while (curStart < stream.pos) {
  1116. // Webkit seems to refuse to render text nodes longer than 57444
  1117. // characters, and returns inaccurate measurements in nodes
  1118. // starting around 5000 chars.
  1119. var pos = Math.min(stream.pos, curStart + 5000);
  1120. f(pos, curStyle);
  1121. curStart = pos;
  1122. }
  1123. }
  1124. // Finds the line to start with when starting a parse. Tries to
  1125. // find a line with a stateAfter, so that it can start with a
  1126. // valid state. If that fails, it returns the line with the
  1127. // smallest indentation, which tends to need the least context to
  1128. // parse correctly.
  1129. function findStartLine(cm, n, precise) {
  1130. var minindent, minline, doc = cm.doc;
  1131. var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100);
  1132. for (var search = n; search > lim; --search) {
  1133. if (search <= doc.first) { return doc.first }
  1134. var line = getLine(doc, search - 1), after = line.stateAfter;
  1135. if (after && (!precise || search + (after instanceof SavedContext ? after.lookAhead : 0) <= doc.modeFrontier))
  1136. { return search }
  1137. var indented = countColumn(line.text, null, cm.options.tabSize);
  1138. if (minline == null || minindent > indented) {
  1139. minline = search - 1;
  1140. minindent = indented;
  1141. }
  1142. }
  1143. return minline
  1144. }
  1145. function retreatFrontier(doc, n) {
  1146. doc.modeFrontier = Math.min(doc.modeFrontier, n);
  1147. if (doc.highlightFrontier < n - 10) { return }
  1148. var start = doc.first;
  1149. for (var line = n - 1; line > start; line--) {
  1150. var saved = getLine(doc, line).stateAfter;
  1151. // change is on 3
  1152. // state on line 1 looked ahead 2 -- so saw 3
  1153. // test 1 + 2 < 3 should cover this
  1154. if (saved && (!(saved instanceof SavedContext) || line + saved.lookAhead < n)) {
  1155. start = line + 1;
  1156. break
  1157. }
  1158. }
  1159. doc.highlightFrontier = Math.min(doc.highlightFrontier, start);
  1160. }
  1161. // Optimize some code when these features are not used.
  1162. var sawReadOnlySpans = false, sawCollapsedSpans = false;
  1163. function seeReadOnlySpans() {
  1164. sawReadOnlySpans = true;
  1165. }
  1166. function seeCollapsedSpans() {
  1167. sawCollapsedSpans = true;
  1168. }
  1169. // TEXTMARKER SPANS
  1170. function MarkedSpan(marker, from, to) {
  1171. this.marker = marker;
  1172. this.from = from; this.to = to;
  1173. }
  1174. // Search an array of spans for a span matching the given marker.
  1175. function getMarkedSpanFor(spans, marker) {
  1176. if (spans) { for (var i = 0; i < spans.length; ++i) {
  1177. var span = spans[i];
  1178. if (span.marker == marker) { return span }
  1179. } }
  1180. }
  1181. // Remove a span from an array, returning undefined if no spans are
  1182. // left (we don't store arrays for lines without spans).
  1183. function removeMarkedSpan(spans, span) {
  1184. var r;
  1185. for (var i = 0; i < spans.length; ++i)
  1186. { if (spans[i] != span) { (r || (r = [])).push(spans[i]); } }
  1187. return r
  1188. }
  1189. // Add a span to a line.
  1190. function addMarkedSpan(line, span, op) {
  1191. var inThisOp = op && window.WeakSet && (op.markedSpans || (op.markedSpans = new WeakSet));
  1192. if (inThisOp && inThisOp.has(line.markedSpans)) {
  1193. line.markedSpans.push(span);
  1194. } else {
  1195. line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span];
  1196. if (inThisOp) { inThisOp.add(line.markedSpans); }
  1197. }
  1198. span.marker.attachLine(line);
  1199. }
  1200. // Used for the algorithm that adjusts markers for a change in the
  1201. // document. These functions cut an array of spans at a given
  1202. // character position, returning an array of remaining chunks (or
  1203. // undefined if nothing remains).
  1204. function markedSpansBefore(old, startCh, isInsert) {
  1205. var nw;
  1206. if (old) { for (var i = 0; i < old.length; ++i) {
  1207. var span = old[i], marker = span.marker;
  1208. var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh);
  1209. if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) {
  1210. var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh)
  1211. ;(nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to));
  1212. }
  1213. } }
  1214. return nw
  1215. }
  1216. function markedSpansAfter(old, endCh, isInsert) {
  1217. var nw;
  1218. if (old) { for (var i = 0; i < old.length; ++i) {
  1219. var span = old[i], marker = span.marker;
  1220. var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh);
  1221. if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) {
  1222. var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh)
  1223. ;(nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh,
  1224. span.to == null ? null : span.to - endCh));
  1225. }
  1226. } }
  1227. return nw
  1228. }
  1229. // Given a change object, compute the new set of marker spans that
  1230. // cover the line in which the change took place. Removes spans
  1231. // entirely within the change, reconnects spans belonging to the
  1232. // same marker that appear on both sides of the change, and cuts off
  1233. // spans partially within the change. Returns an array of span
  1234. // arrays with one element for each line in (after) the change.
  1235. function stretchSpansOverChange(doc, change) {
  1236. if (change.full) { return null }
  1237. var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans;
  1238. var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans;
  1239. if (!oldFirst && !oldLast) { return null }
  1240. var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0;
  1241. // Get the spans that 'stick out' on both sides
  1242. var first = markedSpansBefore(oldFirst, startCh, isInsert);
  1243. var last = markedSpansAfter(oldLast, endCh, isInsert);
  1244. // Next, merge those two ends
  1245. var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0);
  1246. if (first) {
  1247. // Fix up .to properties of first
  1248. for (var i = 0; i < first.length; ++i) {
  1249. var span = first[i];
  1250. if (span.to == null) {
  1251. var found = getMarkedSpanFor(last, span.marker);
  1252. if (!found) { span.to = startCh; }
  1253. else if (sameLine) { span.to = found.to == null ? null : found.to + offset; }
  1254. }
  1255. }
  1256. }
  1257. if (last) {
  1258. // Fix up .from in last (or move them into first in case of sameLine)
  1259. for (var i$1 = 0; i$1 < last.length; ++i$1) {
  1260. var span$1 = last[i$1];
  1261. if (span$1.to != null) { span$1.to += offset; }
  1262. if (span$1.from == null) {
  1263. var found$1 = getMarkedSpanFor(first, span$1.marker);
  1264. if (!found$1) {
  1265. span$1.from = offset;
  1266. if (sameLine) { (first || (first = [])).push(span$1); }
  1267. }
  1268. } else {
  1269. span$1.from += offset;
  1270. if (sameLine) { (first || (first = [])).push(span$1); }
  1271. }
  1272. }
  1273. }
  1274. // Make sure we didn't create any zero-length spans
  1275. if (first) { first = clearEmptySpans(first); }
  1276. if (last && last != first) { last = clearEmptySpans(last); }
  1277. var newMarkers = [first];
  1278. if (!sameLine) {
  1279. // Fill gap with whole-line-spans
  1280. var gap = change.text.length - 2, gapMarkers;
  1281. if (gap > 0 && first)
  1282. { for (var i$2 = 0; i$2 < first.length; ++i$2)
  1283. { if (first[i$2].to == null)
  1284. { (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i$2].marker, null, null)); } } }
  1285. for (var i$3 = 0; i$3 < gap; ++i$3)
  1286. { newMarkers.push(gapMarkers); }
  1287. newMarkers.push(last);
  1288. }
  1289. return newMarkers
  1290. }
  1291. // Remove spans that are empty and don't have a clearWhenEmpty
  1292. // option of false.
  1293. function clearEmptySpans(spans) {
  1294. for (var i = 0; i < spans.length; ++i) {
  1295. var span = spans[i];
  1296. if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false)
  1297. { spans.splice(i--, 1); }
  1298. }
  1299. if (!spans.length) { return null }
  1300. return spans
  1301. }
  1302. // Used to 'clip' out readOnly ranges when making a change.
  1303. function removeReadOnlyRanges(doc, from, to) {
  1304. var markers = null;
  1305. doc.iter(from.line, to.line + 1, function (line) {
  1306. if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) {
  1307. var mark = line.markedSpans[i].marker;
  1308. if (mark.readOnly && (!markers || indexOf(markers, mark) == -1))
  1309. { (markers || (markers = [])).push(mark); }
  1310. } }
  1311. });
  1312. if (!markers) { return null }
  1313. var parts = [{from: from, to: to}];
  1314. for (var i = 0; i < markers.length; ++i) {
  1315. var mk = markers[i], m = mk.find(0);
  1316. for (var j = 0; j < parts.length; ++j) {
  1317. var p = parts[j];
  1318. if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) { continue }
  1319. var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to);
  1320. if (dfrom < 0 || !mk.inclusiveLeft && !dfrom)
  1321. { newParts.push({from: p.from, to: m.from}); }
  1322. if (dto > 0 || !mk.inclusiveRight && !dto)
  1323. { newParts.push({from: m.to, to: p.to}); }
  1324. parts.splice.apply(parts, newParts);
  1325. j += newParts.length - 3;
  1326. }
  1327. }
  1328. return parts
  1329. }
  1330. // Connect or disconnect spans from a line.
  1331. function detachMarkedSpans(line) {
  1332. var spans = line.markedSpans;
  1333. if (!spans) { return }
  1334. for (var i = 0; i < spans.length; ++i)
  1335. { spans[i].marker.detachLine(line); }
  1336. line.markedSpans = null;
  1337. }
  1338. function attachMarkedSpans(line, spans) {
  1339. if (!spans) { return }
  1340. for (var i = 0; i < spans.length; ++i)
  1341. { spans[i].marker.attachLine(line); }
  1342. line.markedSpans = spans;
  1343. }
  1344. // Helpers used when computing which overlapping collapsed span
  1345. // counts as the larger one.
  1346. function extraLeft(marker) { return marker.inclusiveLeft ? -1 : 0 }
  1347. function extraRight(marker) { return marker.inclusiveRight ? 1 : 0 }
  1348. // Returns a number indicating which of two overlapping collapsed
  1349. // spans is larger (and thus includes the other). Falls back to
  1350. // comparing ids when the spans cover exactly the same range.
  1351. function compareCollapsedMarkers(a, b) {
  1352. var lenDiff = a.lines.length - b.lines.length;
  1353. if (lenDiff != 0) { return lenDiff }
  1354. var aPos = a.find(), bPos = b.find();
  1355. var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b);
  1356. if (fromCmp) { return -fromCmp }
  1357. var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b);
  1358. if (toCmp) { return toCmp }
  1359. return b.id - a.id
  1360. }
  1361. // Find out whether a line ends or starts in a collapsed span. If
  1362. // so, return the marker for that span.
  1363. function collapsedSpanAtSide(line, start) {
  1364. var sps = sawCollapsedSpans && line.markedSpans, found;
  1365. if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) {
  1366. sp = sps[i];
  1367. if (sp.marker.collapsed && (start ? sp.from : sp.to) == null &&
  1368. (!found || compareCollapsedMarkers(found, sp.marker) < 0))
  1369. { found = sp.marker; }
  1370. } }
  1371. return found
  1372. }
  1373. function collapsedSpanAtStart(line) { return collapsedSpanAtSide(line, true) }
  1374. function collapsedSpanAtEnd(line) { return collapsedSpanAtSide(line, false) }
  1375. function collapsedSpanAround(line, ch) {
  1376. var sps = sawCollapsedSpans && line.markedSpans, found;
  1377. if (sps) { for (var i = 0; i < sps.length; ++i) {
  1378. var sp = sps[i];
  1379. if (sp.marker.collapsed && (sp.from == null || sp.from < ch) && (sp.to == null || sp.to > ch) &&
  1380. (!found || compareCollapsedMarkers(found, sp.marker) < 0)) { found = sp.marker; }
  1381. } }
  1382. return found
  1383. }
  1384. // Test whether there exists a collapsed span that partially
  1385. // overlaps (covers the start or end, but not both) of a new span.
  1386. // Such overlap is not allowed.
  1387. function conflictingCollapsedRange(doc, lineNo, from, to, marker) {
  1388. var line = getLine(doc, lineNo);
  1389. var sps = sawCollapsedSpans && line.markedSpans;
  1390. if (sps) { for (var i = 0; i < sps.length; ++i) {
  1391. var sp = sps[i];
  1392. if (!sp.marker.collapsed) { continue }
  1393. var found = sp.marker.find(0);
  1394. var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker);
  1395. var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker);
  1396. if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) { continue }
  1397. if (fromCmp <= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.to, from) >= 0 : cmp(found.to, from) > 0) ||
  1398. fromCmp >= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.from, to) <= 0 : cmp(found.from, to) < 0))
  1399. { return true }
  1400. } }
  1401. }
  1402. // A visual line is a line as drawn on the screen. Folding, for
  1403. // example, can cause multiple logical lines to appear on the same
  1404. // visual line. This finds the start of the visual line that the
  1405. // given line is part of (usually that is the line itself).
  1406. function visualLine(line) {
  1407. var merged;
  1408. while (merged = collapsedSpanAtStart(line))
  1409. { line = merged.find(-1, true).line; }
  1410. return line
  1411. }
  1412. function visualLineEnd(line) {
  1413. var merged;
  1414. while (merged = collapsedSpanAtEnd(line))
  1415. { line = merged.find(1, true).line; }
  1416. return line
  1417. }
  1418. // Returns an array of logical lines that continue the visual line
  1419. // started by the argument, or undefined if there are no such lines.
  1420. function visualLineContinued(line) {
  1421. var merged, lines;
  1422. while (merged = collapsedSpanAtEnd(line)) {
  1423. line = merged.find(1, true).line
  1424. ;(lines || (lines = [])).push(line);
  1425. }
  1426. return lines
  1427. }
  1428. // Get the line number of the start of the visual line that the
  1429. // given line number is part of.
  1430. function visualLineNo(doc, lineN) {
  1431. var line = getLine(doc, lineN), vis = visualLine(line);
  1432. if (line == vis) { return lineN }
  1433. return lineNo(vis)
  1434. }
  1435. // Get the line number of the start of the next visual line after
  1436. // the given line.
  1437. function visualLineEndNo(doc, lineN) {
  1438. if (lineN > doc.lastLine()) { return lineN }
  1439. var line = getLine(doc, lineN), merged;
  1440. if (!lineIsHidden(doc, line)) { return lineN }
  1441. while (merged = collapsedSpanAtEnd(line))
  1442. { line = merged.find(1, true).line; }
  1443. return lineNo(line) + 1
  1444. }
  1445. // Compute whether a line is hidden. Lines count as hidden when they
  1446. // are part of a visual line that starts with another line, or when
  1447. // they are entirely covered by collapsed, non-widget span.
  1448. function lineIsHidden(doc, line) {
  1449. var sps = sawCollapsedSpans && line.markedSpans;
  1450. if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) {
  1451. sp = sps[i];
  1452. if (!sp.marker.collapsed) { continue }
  1453. if (sp.from == null) { return true }
  1454. if (sp.marker.widgetNode) { continue }
  1455. if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp))
  1456. { return true }
  1457. } }
  1458. }
  1459. function lineIsHiddenInner(doc, line, span) {
  1460. if (span.to == null) {
  1461. var end = span.marker.find(1, true);
  1462. return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker))
  1463. }
  1464. if (span.marker.inclusiveRight && span.to == line.text.length)
  1465. { return true }
  1466. for (var sp = (void 0), i = 0; i < line.markedSpans.length; ++i) {
  1467. sp = line.markedSpans[i];
  1468. if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to &&
  1469. (sp.to == null || sp.to != span.from) &&
  1470. (sp.marker.inclusiveLeft || span.marker.inclusiveRight) &&
  1471. lineIsHiddenInner(doc, line, sp)) { return true }
  1472. }
  1473. }
  1474. // Find the height above the given line.
  1475. function heightAtLine(lineObj) {
  1476. lineObj = visualLine(lineObj);
  1477. var h = 0, chunk = lineObj.parent;
  1478. for (var i = 0; i < chunk.lines.length; ++i) {
  1479. var line = chunk.lines[i];
  1480. if (line == lineObj) { break }
  1481. else { h += line.height; }
  1482. }
  1483. for (var p = chunk.parent; p; chunk = p, p = chunk.parent) {
  1484. for (var i$1 = 0; i$1 < p.children.length; ++i$1) {
  1485. var cur = p.children[i$1];
  1486. if (cur == chunk) { break }
  1487. else { h += cur.height; }
  1488. }
  1489. }
  1490. return h
  1491. }
  1492. // Compute the character length of a line, taking into account
  1493. // collapsed ranges (see markText) that might hide parts, and join
  1494. // other lines onto it.
  1495. function lineLength(line) {
  1496. if (line.height == 0) { return 0 }
  1497. var len = line.text.length, merged, cur = line;
  1498. while (merged = collapsedSpanAtStart(cur)) {
  1499. var found = merged.find(0, true);
  1500. cur = found.from.line;
  1501. len += found.from.ch - found.to.ch;
  1502. }
  1503. cur = line;
  1504. while (merged = collapsedSpanAtEnd(cur)) {
  1505. var found$1 = merged.find(0, true);
  1506. len -= cur.text.length - found$1.from.ch;
  1507. cur = found$1.to.line;
  1508. len += cur.text.length - found$1.to.ch;
  1509. }
  1510. return len
  1511. }
  1512. // Find the longest line in the document.
  1513. function findMaxLine(cm) {
  1514. var d = cm.display, doc = cm.doc;
  1515. d.maxLine = getLine(doc, doc.first);
  1516. d.maxLineLength = lineLength(d.maxLine);
  1517. d.maxLineChanged = true;
  1518. doc.iter(function (line) {
  1519. var len = lineLength(line);
  1520. if (len > d.maxLineLength) {
  1521. d.maxLineLength = len;
  1522. d.maxLine = line;
  1523. }
  1524. });
  1525. }
  1526. // LINE DATA STRUCTURE
  1527. // Line objects. These hold state related to a line, including
  1528. // highlighting info (the styles array).
  1529. var Line = function(text, markedSpans, estimateHeight) {
  1530. this.text = text;
  1531. attachMarkedSpans(this, markedSpans);
  1532. this.height = estimateHeight ? estimateHeight(this) : 1;
  1533. };
  1534. Line.prototype.lineNo = function () { return lineNo(this) };
  1535. eventMixin(Line);
  1536. // Change the content (text, markers) of a line. Automatically
  1537. // invalidates cached information and tries to re-estimate the
  1538. // line's height.
  1539. function updateLine(line, text, markedSpans, estimateHeight) {
  1540. line.text = text;
  1541. if (line.stateAfter) { line.stateAfter = null; }
  1542. if (line.styles) { line.styles = null; }
  1543. if (line.order != null) { line.order = null; }
  1544. detachMarkedSpans(line);
  1545. attachMarkedSpans(line, markedSpans);
  1546. var estHeight = estimateHeight ? estimateHeight(line) : 1;
  1547. if (estHeight != line.height) { updateLineHeight(line, estHeight); }
  1548. }
  1549. // Detach a line from the document tree and its markers.
  1550. function cleanUpLine(line) {
  1551. line.parent = null;
  1552. detachMarkedSpans(line);
  1553. }
  1554. // Convert a style as returned by a mode (either null, or a string
  1555. // containing one or more styles) to a CSS style. This is cached,
  1556. // and also looks for line-wide styles.
  1557. var styleToClassCache = {}, styleToClassCacheWithMode = {};
  1558. function interpretTokenStyle(style, options) {
  1559. if (!style || /^\s*$/.test(style)) { return null }
  1560. var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache;
  1561. return cache[style] ||
  1562. (cache[style] = style.replace(/\S+/g, "cm-$&"))
  1563. }
  1564. // Render the DOM representation of the text of a line. Also builds
  1565. // up a 'line map', which points at the DOM nodes that represent
  1566. // specific stretches of text, and is used by the measuring code.
  1567. // The returned object contains the DOM node, this map, and
  1568. // information about line-wide styles that were set by the mode.
  1569. function buildLineContent(cm, lineView) {
  1570. // The padding-right forces the element to have a 'border', which
  1571. // is needed on Webkit to be able to get line-level bounding
  1572. // rectangles for it (in measureChar).
  1573. var content = eltP("span", null, null, webkit ? "padding-right: .1px" : null);
  1574. var builder = {pre: eltP("pre", [content], "CodeMirror-line"), content: content,
  1575. col: 0, pos: 0, cm: cm,
  1576. trailingSpace: false,
  1577. splitSpaces: cm.getOption("lineWrapping")};
  1578. lineView.measure = {};
  1579. // Iterate over the logical lines that make up this visual line.
  1580. for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) {
  1581. var line = i ? lineView.rest[i - 1] : lineView.line, order = (void 0);
  1582. builder.pos = 0;
  1583. builder.addToken = buildToken;
  1584. // Optionally wire in some hacks into the token-rendering
  1585. // algorithm, to deal with browser quirks.
  1586. if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line, cm.doc.direction)))
  1587. { builder.addToken = buildTokenBadBidi(builder.addToken, order); }
  1588. builder.map = [];
  1589. var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line);
  1590. insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate));
  1591. if (line.styleClasses) {
  1592. if (line.styleClasses.bgClass)
  1593. { builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || ""); }
  1594. if (line.styleClasses.textClass)
  1595. { builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || ""); }
  1596. }
  1597. // Ensure at least a single node is present, for measuring.
  1598. if (builder.map.length == 0)
  1599. { builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure))); }
  1600. // Store the map and a cache object for the current logical line
  1601. if (i == 0) {
  1602. lineView.measure.map = builder.map;
  1603. lineView.measure.cache = {};
  1604. } else {
  1605. (lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map)
  1606. ;(lineView.measure.caches || (lineView.measure.caches = [])).push({});
  1607. }
  1608. }
  1609. // See issue #2901
  1610. if (webkit) {
  1611. var last = builder.content.lastChild;
  1612. if (/\bcm-tab\b/.test(last.className) || (last.querySelector && last.querySelector(".cm-tab")))
  1613. { builder.content.className = "cm-tab-wrap-hack"; }
  1614. }
  1615. signal(cm, "renderLine", cm, lineView.line, builder.pre);
  1616. if (builder.pre.className)
  1617. { builder.textClass = joinClasses(builder.pre.className, builder.textClass || ""); }
  1618. return builder
  1619. }
  1620. function defaultSpecialCharPlaceholder(ch) {
  1621. var token = elt("span", "\u2022", "cm-invalidchar");
  1622. token.title = "\\u" + ch.charCodeAt(0).toString(16);
  1623. token.setAttribute("aria-label", token.title);
  1624. return token
  1625. }
  1626. // Build up the DOM representation for a single token, and add it to
  1627. // the line map. Takes care to render special characters separately.
  1628. function buildToken(builder, text, style, startStyle, endStyle, css, attributes) {
  1629. if (!text) { return }
  1630. var displayText = builder.splitSpaces ? splitSpaces(text, builder.trailingSpace) : text;
  1631. var special = builder.cm.state.specialChars, mustWrap = false;
  1632. var content;
  1633. if (!special.test(text)) {
  1634. builder.col += text.length;
  1635. content = document.createTextNode(displayText);
  1636. builder.map.push(builder.pos, builder.pos + text.length, content);
  1637. if (ie && ie_version < 9) { mustWrap = true; }
  1638. builder.pos += text.length;
  1639. } else {
  1640. content = document.createDocumentFragment();
  1641. var pos = 0;
  1642. while (true) {
  1643. special.lastIndex = pos;
  1644. var m = special.exec(text);
  1645. var skipped = m ? m.index - pos : text.length - pos;
  1646. if (skipped) {
  1647. var txt = document.createTextNode(displayText.slice(pos, pos + skipped));
  1648. if (ie && ie_version < 9) { content.appendChild(elt("span", [txt])); }
  1649. else { content.appendChild(txt); }
  1650. builder.map.push(builder.pos, builder.pos + skipped, txt);
  1651. builder.col += skipped;
  1652. builder.pos += skipped;
  1653. }
  1654. if (!m) { break }
  1655. pos += skipped + 1;
  1656. var txt$1 = (void 0);
  1657. if (m[0] == "\t") {
  1658. var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize;
  1659. txt$1 = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab"));
  1660. txt$1.setAttribute("role", "presentation");
  1661. txt$1.setAttribute("cm-text", "\t");
  1662. builder.col += tabWidth;
  1663. } else if (m[0] == "\r" || m[0] == "\n") {
  1664. txt$1 = content.appendChild(elt("span", m[0] == "\r" ? "\u240d" : "\u2424", "cm-invalidchar"));
  1665. txt$1.setAttribute("cm-text", m[0]);
  1666. builder.col += 1;
  1667. } else {
  1668. txt$1 = builder.cm.options.specialCharPlaceholder(m[0]);
  1669. txt$1.setAttribute("cm-text", m[0]);
  1670. if (ie && ie_version < 9) { content.appendChild(elt("span", [txt$1])); }
  1671. else { content.appendChild(txt$1); }
  1672. builder.col += 1;
  1673. }
  1674. builder.map.push(builder.pos, builder.pos + 1, txt$1);
  1675. builder.pos++;
  1676. }
  1677. }
  1678. builder.trailingSpace = displayText.charCodeAt(text.length - 1) == 32;
  1679. if (style || startStyle || endStyle || mustWrap || css || attributes) {
  1680. var fullStyle = style || "";
  1681. if (startStyle) { fullStyle += startStyle; }
  1682. if (endStyle) { fullStyle += endStyle; }
  1683. var token = elt("span", [content], fullStyle, css);
  1684. if (attributes) {
  1685. for (var attr in attributes) { if (attributes.hasOwnProperty(attr) && attr != "style" && attr != "class")
  1686. { token.setAttribute(attr, attributes[attr]); } }
  1687. }
  1688. return builder.content.appendChild(token)
  1689. }
  1690. builder.content.appendChild(content);
  1691. }
  1692. // Change some spaces to NBSP to prevent the browser from collapsing
  1693. // trailing spaces at the end of a line when rendering text (issue #1362).
  1694. function splitSpaces(text, trailingBefore) {
  1695. if (text.length > 1 && !/ /.test(text)) { return text }
  1696. var spaceBefore = trailingBefore, result = "";
  1697. for (var i = 0; i < text.length; i++) {
  1698. var ch = text.charAt(i);
  1699. if (ch == " " && spaceBefore && (i == text.length - 1 || text.charCodeAt(i + 1) == 32))
  1700. { ch = "\u00a0"; }
  1701. result += ch;
  1702. spaceBefore = ch == " ";
  1703. }
  1704. return result
  1705. }
  1706. // Work around nonsense dimensions being reported for stretches of
  1707. // right-to-left text.
  1708. function buildTokenBadBidi(inner, order) {
  1709. return function (builder, text, style, startStyle, endStyle, css, attributes) {
  1710. style = style ? style + " cm-force-border" : "cm-force-border";
  1711. var start = builder.pos, end = start + text.length;
  1712. for (;;) {
  1713. // Find the part that overlaps with the start of this text
  1714. var part = (void 0);
  1715. for (var i = 0; i < order.length; i++) {
  1716. part = order[i];
  1717. if (part.to > start && part.from <= start) { break }
  1718. }
  1719. if (part.to >= end) { return inner(builder, text, style, startStyle, endStyle, css, attributes) }
  1720. inner(builder, text.slice(0, part.to - start), style, startStyle, null, css, attributes);
  1721. startStyle = null;
  1722. text = text.slice(part.to - start);
  1723. start = part.to;
  1724. }
  1725. }
  1726. }
  1727. function buildCollapsedSpan(builder, size, marker, ignoreWidget) {
  1728. var widget = !ignoreWidget && marker.widgetNode;
  1729. if (widget) { builder.map.push(builder.pos, builder.pos + size, widget); }
  1730. if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) {
  1731. if (!widget)
  1732. { widget = builder.content.appendChild(document.createElement("span")); }
  1733. widget.setAttribute("cm-marker", marker.id);
  1734. }
  1735. if (widget) {
  1736. builder.cm.display.input.setUneditable(widget);
  1737. builder.content.appendChild(widget);
  1738. }
  1739. builder.pos += size;
  1740. builder.trailingSpace = false;
  1741. }
  1742. // Outputs a number of spans to make up a line, taking highlighting
  1743. // and marked text into account.
  1744. function insertLineContent(line, builder, styles) {
  1745. var spans = line.markedSpans, allText = line.text, at = 0;
  1746. if (!spans) {
  1747. for (var i$1 = 1; i$1 < styles.length; i$1+=2)
  1748. { builder.addToken(builder, allText.slice(at, at = styles[i$1]), interpretTokenStyle(styles[i$1+1], builder.cm.options)); }
  1749. return
  1750. }
  1751. var len = allText.length, pos = 0, i = 1, text = "", style, css;
  1752. var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, collapsed, attributes;
  1753. for (;;) {
  1754. if (nextChange == pos) { // Update current marker set
  1755. spanStyle = spanEndStyle = spanStartStyle = css = "";
  1756. attributes = null;
  1757. collapsed = null; nextChange = Infinity;
  1758. var foundBookmarks = [], endStyles = (void 0);
  1759. for (var j = 0; j < spans.length; ++j) {
  1760. var sp = spans[j], m = sp.marker;
  1761. if (m.type == "bookmark" && sp.from == pos && m.widgetNode) {
  1762. foundBookmarks.push(m);
  1763. } else if (sp.from <= pos && (sp.to == null || sp.to > pos || m.collapsed && sp.to == pos && sp.from == pos)) {
  1764. if (sp.to != null && sp.to != pos && nextChange > sp.to) {
  1765. nextChange = sp.to;
  1766. spanEndStyle = "";
  1767. }
  1768. if (m.className) { spanStyle += " " + m.className; }
  1769. if (m.css) { css = (css ? css + ";" : "") + m.css; }
  1770. if (m.startStyle && sp.from == pos) { spanStartStyle += " " + m.startStyle; }
  1771. if (m.endStyle && sp.to == nextChange) { (endStyles || (endStyles = [])).push(m.endStyle, sp.to); }
  1772. // support for the old title property
  1773. // https://github.com/codemirror/CodeMirror/pull/5673
  1774. if (m.title) { (attributes || (attributes = {})).title = m.title; }
  1775. if (m.attributes) {
  1776. for (var attr in m.attributes)
  1777. { (attributes || (attributes = {}))[attr] = m.attributes[attr]; }
  1778. }
  1779. if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0))
  1780. { collapsed = sp; }
  1781. } else if (sp.from > pos && nextChange > sp.from) {
  1782. nextChange = sp.from;
  1783. }
  1784. }
  1785. if (endStyles) { for (var j$1 = 0; j$1 < endStyles.length; j$1 += 2)
  1786. { if (endStyles[j$1 + 1] == nextChange) { spanEndStyle += " " + endStyles[j$1]; } } }
  1787. if (!collapsed || collapsed.from == pos) { for (var j$2 = 0; j$2 < foundBookmarks.length; ++j$2)
  1788. { buildCollapsedSpan(builder, 0, foundBookmarks[j$2]); } }
  1789. if (collapsed && (collapsed.from || 0) == pos) {
  1790. buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos,
  1791. collapsed.marker, collapsed.from == null);
  1792. if (collapsed.to == null) { return }
  1793. if (collapsed.to == pos) { collapsed = false; }
  1794. }
  1795. }
  1796. if (pos >= len) { break }
  1797. var upto = Math.min(len, nextChange);
  1798. while (true) {
  1799. if (text) {
  1800. var end = pos + text.length;
  1801. if (!collapsed) {
  1802. var tokenText = end > upto ? text.slice(0, upto - pos) : text;
  1803. builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle,
  1804. spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", css, attributes);
  1805. }
  1806. if (end >= upto) {text = text.slice(upto - pos); pos = upto; break}
  1807. pos = end;
  1808. spanStartStyle = "";
  1809. }
  1810. text = allText.slice(at, at = styles[i++]);
  1811. style = interpretTokenStyle(styles[i++], builder.cm.options);
  1812. }
  1813. }
  1814. }
  1815. // These objects are used to represent the visible (currently drawn)
  1816. // part of the document. A LineView may correspond to multiple
  1817. // logical lines, if those are connected by collapsed ranges.
  1818. function LineView(doc, line, lineN) {
  1819. // The starting line
  1820. this.line = line;
  1821. // Continuing lines, if any
  1822. this.rest = visualLineContinued(line);
  1823. // Number of logical lines in this visual line
  1824. this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1;
  1825. this.node = this.text = null;
  1826. this.hidden = lineIsHidden(doc, line);
  1827. }
  1828. // Create a range of LineView objects for the given lines.
  1829. function buildViewArray(cm, from, to) {
  1830. var array = [], nextPos;
  1831. for (var pos = from; pos < to; pos = nextPos) {
  1832. var view = new LineView(cm.doc, getLine(cm.doc, pos), pos);
  1833. nextPos = pos + view.size;
  1834. array.push(view);
  1835. }
  1836. return array
  1837. }
  1838. var operationGroup = null;
  1839. function pushOperation(op) {
  1840. if (operationGroup) {
  1841. operationGroup.ops.push(op);
  1842. } else {
  1843. op.ownsGroup = operationGroup = {
  1844. ops: [op],
  1845. delayedCallbacks: []
  1846. };
  1847. }
  1848. }
  1849. function fireCallbacksForOps(group) {
  1850. // Calls delayed callbacks and cursorActivity handlers until no
  1851. // new ones appear
  1852. var callbacks = group.delayedCallbacks, i = 0;
  1853. do {
  1854. for (; i < callbacks.length; i++)
  1855. { callbacks[i].call(null); }
  1856. for (var j = 0; j < group.ops.length; j++) {
  1857. var op = group.ops[j];
  1858. if (op.cursorActivityHandlers)
  1859. { while (op.cursorActivityCalled < op.cursorActivityHandlers.length)
  1860. { op.cursorActivityHandlers[op.cursorActivityCalled++].call(null, op.cm); } }
  1861. }
  1862. } while (i < callbacks.length)
  1863. }
  1864. function finishOperation(op, endCb) {
  1865. var group = op.ownsGroup;
  1866. if (!group) { return }
  1867. try { fireCallbacksForOps(group); }
  1868. finally {
  1869. operationGroup = null;
  1870. endCb(group);
  1871. }
  1872. }
  1873. var orphanDelayedCallbacks = null;
  1874. // Often, we want to signal events at a point where we are in the
  1875. // middle of some work, but don't want the handler to start calling
  1876. // other methods on the editor, which might be in an inconsistent
  1877. // state or simply not expect any other events to happen.
  1878. // signalLater looks whether there are any handlers, and schedules
  1879. // them to be executed when the last operation ends, or, if no
  1880. // operation is active, when a timeout fires.
  1881. function signalLater(emitter, type /*, values...*/) {
  1882. var arr = getHandlers(emitter, type);
  1883. if (!arr.length) { return }
  1884. var args = Array.prototype.slice.call(arguments, 2), list;
  1885. if (operationGroup) {
  1886. list = operationGroup.delayedCallbacks;
  1887. } else if (orphanDelayedCallbacks) {
  1888. list = orphanDelayedCallbacks;
  1889. } else {
  1890. list = orphanDelayedCallbacks = [];
  1891. setTimeout(fireOrphanDelayed, 0);
  1892. }
  1893. var loop = function ( i ) {
  1894. list.push(function () { return arr[i].apply(null, args); });
  1895. };
  1896. for (var i = 0; i < arr.length; ++i)
  1897. loop( i );
  1898. }
  1899. function fireOrphanDelayed() {
  1900. var delayed = orphanDelayedCallbacks;
  1901. orphanDelayedCallbacks = null;
  1902. for (var i = 0; i < delayed.length; ++i) { delayed[i](); }
  1903. }
  1904. // When an aspect of a line changes, a string is added to
  1905. // lineView.changes. This updates the relevant part of the line's
  1906. // DOM structure.
  1907. function updateLineForChanges(cm, lineView, lineN, dims) {
  1908. for (var j = 0; j < lineView.changes.length; j++) {
  1909. var type = lineView.changes[j];
  1910. if (type == "text") { updateLineText(cm, lineView); }
  1911. else if (type == "gutter") { updateLineGutter(cm, lineView, lineN, dims); }
  1912. else if (type == "class") { updateLineClasses(cm, lineView); }
  1913. else if (type == "widget") { updateLineWidgets(cm, lineView, dims); }
  1914. }
  1915. lineView.changes = null;
  1916. }
  1917. // Lines with gutter elements, widgets or a background class need to
  1918. // be wrapped, and have the extra elements added to the wrapper div
  1919. function ensureLineWrapped(lineView) {
  1920. if (lineView.node == lineView.text) {
  1921. lineView.node = elt("div", null, null, "position: relative");
  1922. if (lineView.text.parentNode)
  1923. { lineView.text.parentNode.replaceChild(lineView.node, lineView.text); }
  1924. lineView.node.appendChild(lineView.text);
  1925. if (ie && ie_version < 8) { lineView.node.style.zIndex = 2; }
  1926. }
  1927. return lineView.node
  1928. }
  1929. function updateLineBackground(cm, lineView) {
  1930. var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass;
  1931. if (cls) { cls += " CodeMirror-linebackground"; }
  1932. if (lineView.background) {
  1933. if (cls) { lineView.background.className = cls; }
  1934. else { lineView.background.parentNode.removeChild(lineView.background); lineView.background = null; }
  1935. } else if (cls) {
  1936. var wrap = ensureLineWrapped(lineView);
  1937. lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild);
  1938. cm.display.input.setUneditable(lineView.background);
  1939. }
  1940. }
  1941. // Wrapper around buildLineContent which will reuse the structure
  1942. // in display.externalMeasured when possible.
  1943. function getLineContent(cm, lineView) {
  1944. var ext = cm.display.externalMeasured;
  1945. if (ext && ext.line == lineView.line) {
  1946. cm.display.externalMeasured = null;
  1947. lineView.measure = ext.measure;
  1948. return ext.built
  1949. }
  1950. return buildLineContent(cm, lineView)
  1951. }
  1952. // Redraw the line's text. Interacts with the background and text
  1953. // classes because the mode may output tokens that influence these
  1954. // classes.
  1955. function updateLineText(cm, lineView) {
  1956. var cls = lineView.text.className;
  1957. var built = getLineContent(cm, lineView);
  1958. if (lineView.text == lineView.node) { lineView.node = built.pre; }
  1959. lineView.text.parentNode.replaceChild(built.pre, lineView.text);
  1960. lineView.text = built.pre;
  1961. if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) {
  1962. lineView.bgClass = built.bgClass;
  1963. lineView.textClass = built.textClass;
  1964. updateLineClasses(cm, lineView);
  1965. } else if (cls) {
  1966. lineView.text.className = cls;
  1967. }
  1968. }
  1969. function updateLineClasses(cm, lineView) {
  1970. updateLineBackground(cm, lineView);
  1971. if (lineView.line.wrapClass)
  1972. { ensureLineWrapped(lineView).className = lineView.line.wrapClass; }
  1973. else if (lineView.node != lineView.text)
  1974. { lineView.node.className = ""; }
  1975. var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass;
  1976. lineView.text.className = textClass || "";
  1977. }
  1978. function updateLineGutter(cm, lineView, lineN, dims) {
  1979. if (lineView.gutter) {
  1980. lineView.node.removeChild(lineView.gutter);
  1981. lineView.gutter = null;
  1982. }
  1983. if (lineView.gutterBackground) {
  1984. lineView.node.removeChild(lineView.gutterBackground);
  1985. lineView.gutterBackground = null;
  1986. }
  1987. if (lineView.line.gutterClass) {
  1988. var wrap = ensureLineWrapped(lineView);
  1989. lineView.gutterBackground = elt("div", null, "CodeMirror-gutter-background " + lineView.line.gutterClass,
  1990. ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px; width: " + (dims.gutterTotalWidth) + "px"));
  1991. cm.display.input.setUneditable(lineView.gutterBackground);
  1992. wrap.insertBefore(lineView.gutterBackground, lineView.text);
  1993. }
  1994. var markers = lineView.line.gutterMarkers;
  1995. if (cm.options.lineNumbers || markers) {
  1996. var wrap$1 = ensureLineWrapped(lineView);
  1997. var gutterWrap = lineView.gutter = elt("div", null, "CodeMirror-gutter-wrapper", ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px"));
  1998. gutterWrap.setAttribute("aria-hidden", "true");
  1999. cm.display.input.setUneditable(gutterWrap);
  2000. wrap$1.insertBefore(gutterWrap, lineView.text);
  2001. if (lineView.line.gutterClass)
  2002. { gutterWrap.className += " " + lineView.line.gutterClass; }
  2003. if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"]))
  2004. { lineView.lineNumber = gutterWrap.appendChild(
  2005. elt("div", lineNumberFor(cm.options, lineN),
  2006. "CodeMirror-linenumber CodeMirror-gutter-elt",
  2007. ("left: " + (dims.gutterLeft["CodeMirror-linenumbers"]) + "px; width: " + (cm.display.lineNumInnerWidth) + "px"))); }
  2008. if (markers) { for (var k = 0; k < cm.display.gutterSpecs.length; ++k) {
  2009. var id = cm.display.gutterSpecs[k].className, found = markers.hasOwnProperty(id) && markers[id];
  2010. if (found)
  2011. { gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt",
  2012. ("left: " + (dims.gutterLeft[id]) + "px; width: " + (dims.gutterWidth[id]) + "px"))); }
  2013. } }
  2014. }
  2015. }
  2016. function updateLineWidgets(cm, lineView, dims) {
  2017. if (lineView.alignable) { lineView.alignable = null; }
  2018. var isWidget = classTest("CodeMirror-linewidget");
  2019. for (var node = lineView.node.firstChild, next = (void 0); node; node = next) {
  2020. next = node.nextSibling;
  2021. if (isWidget.test(node.className)) { lineView.node.removeChild(node); }
  2022. }
  2023. insertLineWidgets(cm, lineView, dims);
  2024. }
  2025. // Build a line's DOM representation from scratch
  2026. function buildLineElement(cm, lineView, lineN, dims) {
  2027. var built = getLineContent(cm, lineView);
  2028. lineView.text = lineView.node = built.pre;
  2029. if (built.bgClass) { lineView.bgClass = built.bgClass; }
  2030. if (built.textClass) { lineView.textClass = built.textClass; }
  2031. updateLineClasses(cm, lineView);
  2032. updateLineGutter(cm, lineView, lineN, dims);
  2033. insertLineWidgets(cm, lineView, dims);
  2034. return lineView.node
  2035. }
  2036. // A lineView may contain multiple logical lines (when merged by
  2037. // collapsed spans). The widgets for all of them need to be drawn.
  2038. function insertLineWidgets(cm, lineView, dims) {
  2039. insertLineWidgetsFor(cm, lineView.line, lineView, dims, true);
  2040. if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++)
  2041. { insertLineWidgetsFor(cm, lineView.rest[i], lineView, dims, false); } }
  2042. }
  2043. function insertLineWidgetsFor(cm, line, lineView, dims, allowAbove) {
  2044. if (!line.widgets) { return }
  2045. var wrap = ensureLineWrapped(lineView);
  2046. for (var i = 0, ws = line.widgets; i < ws.length; ++i) {
  2047. var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget" + (widget.className ? " " + widget.className : ""));
  2048. if (!widget.handleMouseEvents) { node.setAttribute("cm-ignore-events", "true"); }
  2049. positionLineWidget(widget, node, lineView, dims);
  2050. cm.display.input.setUneditable(node);
  2051. if (allowAbove && widget.above)
  2052. { wrap.insertBefore(node, lineView.gutter || lineView.text); }
  2053. else
  2054. { wrap.appendChild(node); }
  2055. signalLater(widget, "redraw");
  2056. }
  2057. }
  2058. function positionLineWidget(widget, node, lineView, dims) {
  2059. if (widget.noHScroll) {
  2060. (lineView.alignable || (lineView.alignable = [])).push(node);
  2061. var width = dims.wrapperWidth;
  2062. node.style.left = dims.fixedPos + "px";
  2063. if (!widget.coverGutter) {
  2064. width -= dims.gutterTotalWidth;
  2065. node.style.paddingLeft = dims.gutterTotalWidth + "px";
  2066. }
  2067. node.style.width = width + "px";
  2068. }
  2069. if (widget.coverGutter) {
  2070. node.style.zIndex = 5;
  2071. node.style.position = "relative";
  2072. if (!widget.noHScroll) { node.style.marginLeft = -dims.gutterTotalWidth + "px"; }
  2073. }
  2074. }
  2075. function widgetHeight(widget) {
  2076. if (widget.height != null) { return widget.height }
  2077. var cm = widget.doc.cm;
  2078. if (!cm) { return 0 }
  2079. if (!contains(document.body, widget.node)) {
  2080. var parentStyle = "position: relative;";
  2081. if (widget.coverGutter)
  2082. { parentStyle += "margin-left: -" + cm.display.gutters.offsetWidth + "px;"; }
  2083. if (widget.noHScroll)
  2084. { parentStyle += "width: " + cm.display.wrapper.clientWidth + "px;"; }
  2085. removeChildrenAndAdd(cm.display.measure, elt("div", [widget.node], null, parentStyle));
  2086. }
  2087. return widget.height = widget.node.parentNode.offsetHeight
  2088. }
  2089. // Return true when the given mouse event happened in a widget
  2090. function eventInWidget(display, e) {
  2091. for (var n = e_target(e); n != display.wrapper; n = n.parentNode) {
  2092. if (!n || (n.nodeType == 1 && n.getAttribute("cm-ignore-events") == "true") ||
  2093. (n.parentNode == display.sizer && n != display.mover))
  2094. { return true }
  2095. }
  2096. }
  2097. // POSITION MEASUREMENT
  2098. function paddingTop(display) {return display.lineSpace.offsetTop}
  2099. function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight}
  2100. function paddingH(display) {
  2101. if (display.cachedPaddingH) { return display.cachedPaddingH }
  2102. var e = removeChildrenAndAdd(display.measure, elt("pre", "x", "CodeMirror-line-like"));
  2103. var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle;
  2104. var data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)};
  2105. if (!isNaN(data.left) && !isNaN(data.right)) { display.cachedPaddingH = data; }
  2106. return data
  2107. }
  2108. function scrollGap(cm) { return scrollerGap - cm.display.nativeBarWidth }
  2109. function displayWidth(cm) {
  2110. return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth
  2111. }
  2112. function displayHeight(cm) {
  2113. return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight
  2114. }
  2115. // Ensure the lineView.wrapping.heights array is populated. This is
  2116. // an array of bottom offsets for the lines that make up a drawn
  2117. // line. When lineWrapping is on, there might be more than one
  2118. // height.
  2119. function ensureLineHeights(cm, lineView, rect) {
  2120. var wrapping = cm.options.lineWrapping;
  2121. var curWidth = wrapping && displayWidth(cm);
  2122. if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) {
  2123. var heights = lineView.measure.heights = [];
  2124. if (wrapping) {
  2125. lineView.measure.width = curWidth;
  2126. var rects = lineView.text.firstChild.getClientRects();
  2127. for (var i = 0; i < rects.length - 1; i++) {
  2128. var cur = rects[i], next = rects[i + 1];
  2129. if (Math.abs(cur.bottom - next.bottom) > 2)
  2130. { heights.push((cur.bottom + next.top) / 2 - rect.top); }
  2131. }
  2132. }
  2133. heights.push(rect.bottom - rect.top);
  2134. }
  2135. }
  2136. // Find a line map (mapping character offsets to text nodes) and a
  2137. // measurement cache for the given line number. (A line view might
  2138. // contain multiple lines when collapsed ranges are present.)
  2139. function mapFromLineView(lineView, line, lineN) {
  2140. if (lineView.line == line)
  2141. { return {map: lineView.measure.map, cache: lineView.measure.cache} }
  2142. if (lineView.rest) {
  2143. for (var i = 0; i < lineView.rest.length; i++)
  2144. { if (lineView.rest[i] == line)
  2145. { return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i]} } }
  2146. for (var i$1 = 0; i$1 < lineView.rest.length; i$1++)
  2147. { if (lineNo(lineView.rest[i$1]) > lineN)
  2148. { return {map: lineView.measure.maps[i$1], cache: lineView.measure.caches[i$1], before: true} } }
  2149. }
  2150. }
  2151. // Render a line into the hidden node display.externalMeasured. Used
  2152. // when measurement is needed for a line that's not in the viewport.
  2153. function updateExternalMeasurement(cm, line) {
  2154. line = visualLine(line);
  2155. var lineN = lineNo(line);
  2156. var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN);
  2157. view.lineN = lineN;
  2158. var built = view.built = buildLineContent(cm, view);
  2159. view.text = built.pre;
  2160. removeChildrenAndAdd(cm.display.lineMeasure, built.pre);
  2161. return view
  2162. }
  2163. // Get a {top, bottom, left, right} box (in line-local coordinates)
  2164. // for a given character.
  2165. function measureChar(cm, line, ch, bias) {
  2166. return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias)
  2167. }
  2168. // Find a line view that corresponds to the given line number.
  2169. function findViewForLine(cm, lineN) {
  2170. if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo)
  2171. { return cm.display.view[findViewIndex(cm, lineN)] }
  2172. var ext = cm.display.externalMeasured;
  2173. if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size)
  2174. { return ext }
  2175. }
  2176. // Measurement can be split in two steps, the set-up work that
  2177. // applies to the whole line, and the measurement of the actual
  2178. // character. Functions like coordsChar, that need to do a lot of
  2179. // measurements in a row, can thus ensure that the set-up work is
  2180. // only done once.
  2181. function prepareMeasureForLine(cm, line) {
  2182. var lineN = lineNo(line);
  2183. var view = findViewForLine(cm, lineN);
  2184. if (view && !view.text) {
  2185. view = null;
  2186. } else if (view && view.changes) {
  2187. updateLineForChanges(cm, view, lineN, getDimensions(cm));
  2188. cm.curOp.forceUpdate = true;
  2189. }
  2190. if (!view)
  2191. { view = updateExternalMeasurement(cm, line); }
  2192. var info = mapFromLineView(view, line, lineN);
  2193. return {
  2194. line: line, view: view, rect: null,
  2195. map: info.map, cache: info.cache, before: info.before,
  2196. hasHeights: false
  2197. }
  2198. }
  2199. // Given a prepared measurement object, measures the position of an
  2200. // actual character (or fetches it from the cache).
  2201. function measureCharPrepared(cm, prepared, ch, bias, varHeight) {
  2202. if (prepared.before) { ch = -1; }
  2203. var key = ch + (bias || ""), found;
  2204. if (prepared.cache.hasOwnProperty(key)) {
  2205. found = prepared.cache[key];
  2206. } else {
  2207. if (!prepared.rect)
  2208. { prepared.rect = prepared.view.text.getBoundingClientRect(); }
  2209. if (!prepared.hasHeights) {
  2210. ensureLineHeights(cm, prepared.view, prepared.rect);
  2211. prepared.hasHeights = true;
  2212. }
  2213. found = measureCharInner(cm, prepared, ch, bias);
  2214. if (!found.bogus) { prepared.cache[key] = found; }
  2215. }
  2216. return {left: found.left, right: found.right,
  2217. top: varHeight ? found.rtop : found.top,
  2218. bottom: varHeight ? found.rbottom : found.bottom}
  2219. }
  2220. var nullRect = {left: 0, right: 0, top: 0, bottom: 0};
  2221. function nodeAndOffsetInLineMap(map, ch, bias) {
  2222. var node, start, end, collapse, mStart, mEnd;
  2223. // First, search the line map for the text node corresponding to,
  2224. // or closest to, the target character.
  2225. for (var i = 0; i < map.length; i += 3) {
  2226. mStart = map[i];
  2227. mEnd = map[i + 1];
  2228. if (ch < mStart) {
  2229. start = 0; end = 1;
  2230. collapse = "left";
  2231. } else if (ch < mEnd) {
  2232. start = ch - mStart;
  2233. end = start + 1;
  2234. } else if (i == map.length - 3 || ch == mEnd && map[i + 3] > ch) {
  2235. end = mEnd - mStart;
  2236. start = end - 1;
  2237. if (ch >= mEnd) { collapse = "right"; }
  2238. }
  2239. if (start != null) {
  2240. node = map[i + 2];
  2241. if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right"))
  2242. { collapse = bias; }
  2243. if (bias == "left" && start == 0)
  2244. { while (i && map[i - 2] == map[i - 3] && map[i - 1].insertLeft) {
  2245. node = map[(i -= 3) + 2];
  2246. collapse = "left";
  2247. } }
  2248. if (bias == "right" && start == mEnd - mStart)
  2249. { while (i < map.length - 3 && map[i + 3] == map[i + 4] && !map[i + 5].insertLeft) {
  2250. node = map[(i += 3) + 2];
  2251. collapse = "right";
  2252. } }
  2253. break
  2254. }
  2255. }
  2256. return {node: node, start: start, end: end, collapse: collapse, coverStart: mStart, coverEnd: mEnd}
  2257. }
  2258. function getUsefulRect(rects, bias) {
  2259. var rect = nullRect;
  2260. if (bias == "left") { for (var i = 0; i < rects.length; i++) {
  2261. if ((rect = rects[i]).left != rect.right) { break }
  2262. } } else { for (var i$1 = rects.length - 1; i$1 >= 0; i$1--) {
  2263. if ((rect = rects[i$1]).left != rect.right) { break }
  2264. } }
  2265. return rect
  2266. }
  2267. function measureCharInner(cm, prepared, ch, bias) {
  2268. var place = nodeAndOffsetInLineMap(prepared.map, ch, bias);
  2269. var node = place.node, start = place.start, end = place.end, collapse = place.collapse;
  2270. var rect;
  2271. if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates.
  2272. for (var i$1 = 0; i$1 < 4; i$1++) { // Retry a maximum of 4 times when nonsense rectangles are returned
  2273. while (start && isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) { --start; }
  2274. while (place.coverStart + end < place.coverEnd && isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) { ++end; }
  2275. if (ie && ie_version < 9 && start == 0 && end == place.coverEnd - place.coverStart)
  2276. { rect = node.parentNode.getBoundingClientRect(); }
  2277. else
  2278. { rect = getUsefulRect(range(node, start, end).getClientRects(), bias); }
  2279. if (rect.left || rect.right || start == 0) { break }
  2280. end = start;
  2281. start = start - 1;
  2282. collapse = "right";
  2283. }
  2284. if (ie && ie_version < 11) { rect = maybeUpdateRectForZooming(cm.display.measure, rect); }
  2285. } else { // If it is a widget, simply get the box for the whole widget.
  2286. if (start > 0) { collapse = bias = "right"; }
  2287. var rects;
  2288. if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1)
  2289. { rect = rects[bias == "right" ? rects.length - 1 : 0]; }
  2290. else
  2291. { rect = node.getBoundingClientRect(); }
  2292. }
  2293. if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) {
  2294. var rSpan = node.parentNode.getClientRects()[0];
  2295. if (rSpan)
  2296. { rect = {left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom}; }
  2297. else
  2298. { rect = nullRect; }
  2299. }
  2300. var rtop = rect.top - prepared.rect.top, rbot = rect.bottom - prepared.rect.top;
  2301. var mid = (rtop + rbot) / 2;
  2302. var heights = prepared.view.measure.heights;
  2303. var i = 0;
  2304. for (; i < heights.length - 1; i++)
  2305. { if (mid < heights[i]) { break } }
  2306. var top = i ? heights[i - 1] : 0, bot = heights[i];
  2307. var result = {left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left,
  2308. right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left,
  2309. top: top, bottom: bot};
  2310. if (!rect.left && !rect.right) { result.bogus = true; }
  2311. if (!cm.options.singleCursorHeightPerLine) { result.rtop = rtop; result.rbottom = rbot; }
  2312. return result
  2313. }
  2314. // Work around problem with bounding client rects on ranges being
  2315. // returned incorrectly when zoomed on IE10 and below.
  2316. function maybeUpdateRectForZooming(measure, rect) {
  2317. if (!window.screen || screen.logicalXDPI == null ||
  2318. screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure))
  2319. { return rect }
  2320. var scaleX = screen.logicalXDPI / screen.deviceXDPI;
  2321. var scaleY = screen.logicalYDPI / screen.deviceYDPI;
  2322. return {left: rect.left * scaleX, right: rect.right * scaleX,
  2323. top: rect.top * scaleY, bottom: rect.bottom * scaleY}
  2324. }
  2325. function clearLineMeasurementCacheFor(lineView) {
  2326. if (lineView.measure) {
  2327. lineView.measure.cache = {};
  2328. lineView.measure.heights = null;
  2329. if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++)
  2330. { lineView.measure.caches[i] = {}; } }
  2331. }
  2332. }
  2333. function clearLineMeasurementCache(cm) {
  2334. cm.display.externalMeasure = null;
  2335. removeChildren(cm.display.lineMeasure);
  2336. for (var i = 0; i < cm.display.view.length; i++)
  2337. { clearLineMeasurementCacheFor(cm.display.view[i]); }
  2338. }
  2339. function clearCaches(cm) {
  2340. clearLineMeasurementCache(cm);
  2341. cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null;
  2342. if (!cm.options.lineWrapping) { cm.display.maxLineChanged = true; }
  2343. cm.display.lineNumChars = null;
  2344. }
  2345. function pageScrollX() {
  2346. // Work around https://bugs.chromium.org/p/chromium/issues/detail?id=489206
  2347. // which causes page_Offset and bounding client rects to use
  2348. // different reference viewports and invalidate our calculations.
  2349. if (chrome && android) { return -(document.body.getBoundingClientRect().left - parseInt(getComputedStyle(document.body).marginLeft)) }
  2350. return window.pageXOffset || (document.documentElement || document.body).scrollLeft
  2351. }
  2352. function pageScrollY() {
  2353. if (chrome && android) { return -(document.body.getBoundingClientRect().top - parseInt(getComputedStyle(document.body).marginTop)) }
  2354. return window.pageYOffset || (document.documentElement || document.body).scrollTop
  2355. }
  2356. function widgetTopHeight(lineObj) {
  2357. var ref = visualLine(lineObj);
  2358. var widgets = ref.widgets;
  2359. var height = 0;
  2360. if (widgets) { for (var i = 0; i < widgets.length; ++i) { if (widgets[i].above)
  2361. { height += widgetHeight(widgets[i]); } } }
  2362. return height
  2363. }
  2364. // Converts a {top, bottom, left, right} box from line-local
  2365. // coordinates into another coordinate system. Context may be one of
  2366. // "line", "div" (display.lineDiv), "local"./null (editor), "window",
  2367. // or "page".
  2368. function intoCoordSystem(cm, lineObj, rect, context, includeWidgets) {
  2369. if (!includeWidgets) {
  2370. var height = widgetTopHeight(lineObj);
  2371. rect.top += height; rect.bottom += height;
  2372. }
  2373. if (context == "line") { return rect }
  2374. if (!context) { context = "local"; }
  2375. var yOff = heightAtLine(lineObj);
  2376. if (context == "local") { yOff += paddingTop(cm.display); }
  2377. else { yOff -= cm.display.viewOffset; }
  2378. if (context == "page" || context == "window") {
  2379. var lOff = cm.display.lineSpace.getBoundingClientRect();
  2380. yOff += lOff.top + (context == "window" ? 0 : pageScrollY());
  2381. var xOff = lOff.left + (context == "window" ? 0 : pageScrollX());
  2382. rect.left += xOff; rect.right += xOff;
  2383. }
  2384. rect.top += yOff; rect.bottom += yOff;
  2385. return rect
  2386. }
  2387. // Coverts a box from "div" coords to another coordinate system.
  2388. // Context may be "window", "page", "div", or "local"./null.
  2389. function fromCoordSystem(cm, coords, context) {
  2390. if (context == "div") { return coords }
  2391. var left = coords.left, top = coords.top;
  2392. // First move into "page" coordinate system
  2393. if (context == "page") {
  2394. left -= pageScrollX();
  2395. top -= pageScrollY();
  2396. } else if (context == "local" || !context) {
  2397. var localBox = cm.display.sizer.getBoundingClientRect();
  2398. left += localBox.left;
  2399. top += localBox.top;
  2400. }
  2401. var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect();
  2402. return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top}
  2403. }
  2404. function charCoords(cm, pos, context, lineObj, bias) {
  2405. if (!lineObj) { lineObj = getLine(cm.doc, pos.line); }
  2406. return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context)
  2407. }
  2408. // Returns a box for a given cursor position, which may have an
  2409. // 'other' property containing the position of the secondary cursor
  2410. // on a bidi boundary.
  2411. // A cursor Pos(line, char, "before") is on the same visual line as `char - 1`
  2412. // and after `char - 1` in writing order of `char - 1`
  2413. // A cursor Pos(line, char, "after") is on the same visual line as `char`
  2414. // and before `char` in writing order of `char`
  2415. // Examples (upper-case letters are RTL, lower-case are LTR):
  2416. // Pos(0, 1, ...)
  2417. // before after
  2418. // ab a|b a|b
  2419. // aB a|B aB|
  2420. // Ab |Ab A|b
  2421. // AB B|A B|A
  2422. // Every position after the last character on a line is considered to stick
  2423. // to the last character on the line.
  2424. function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) {
  2425. lineObj = lineObj || getLine(cm.doc, pos.line);
  2426. if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj); }
  2427. function get(ch, right) {
  2428. var m = measureCharPrepared(cm, preparedMeasure, ch, right ? "right" : "left", varHeight);
  2429. if (right) { m.left = m.right; } else { m.right = m.left; }
  2430. return intoCoordSystem(cm, lineObj, m, context)
  2431. }
  2432. var order = getOrder(lineObj, cm.doc.direction), ch = pos.ch, sticky = pos.sticky;
  2433. if (ch >= lineObj.text.length) {
  2434. ch = lineObj.text.length;
  2435. sticky = "before";
  2436. } else if (ch <= 0) {
  2437. ch = 0;
  2438. sticky = "after";
  2439. }
  2440. if (!order) { return get(sticky == "before" ? ch - 1 : ch, sticky == "before") }
  2441. function getBidi(ch, partPos, invert) {
  2442. var part = order[partPos], right = part.level == 1;
  2443. return get(invert ? ch - 1 : ch, right != invert)
  2444. }
  2445. var partPos = getBidiPartAt(order, ch, sticky);
  2446. var other = bidiOther;
  2447. var val = getBidi(ch, partPos, sticky == "before");
  2448. if (other != null) { val.other = getBidi(ch, other, sticky != "before"); }
  2449. return val
  2450. }
  2451. // Used to cheaply estimate the coordinates for a position. Used for
  2452. // intermediate scroll updates.
  2453. function estimateCoords(cm, pos) {
  2454. var left = 0;
  2455. pos = clipPos(cm.doc, pos);
  2456. if (!cm.options.lineWrapping) { left = charWidth(cm.display) * pos.ch; }
  2457. var lineObj = getLine(cm.doc, pos.line);
  2458. var top = heightAtLine(lineObj) + paddingTop(cm.display);
  2459. return {left: left, right: left, top: top, bottom: top + lineObj.height}
  2460. }
  2461. // Positions returned by coordsChar contain some extra information.
  2462. // xRel is the relative x position of the input coordinates compared
  2463. // to the found position (so xRel > 0 means the coordinates are to
  2464. // the right of the character position, for example). When outside
  2465. // is true, that means the coordinates lie outside the line's
  2466. // vertical range.
  2467. function PosWithInfo(line, ch, sticky, outside, xRel) {
  2468. var pos = Pos(line, ch, sticky);
  2469. pos.xRel = xRel;
  2470. if (outside) { pos.outside = outside; }
  2471. return pos
  2472. }
  2473. // Compute the character position closest to the given coordinates.
  2474. // Input must be lineSpace-local ("div" coordinate system).
  2475. function coordsChar(cm, x, y) {
  2476. var doc = cm.doc;
  2477. y += cm.display.viewOffset;
  2478. if (y < 0) { return PosWithInfo(doc.first, 0, null, -1, -1) }
  2479. var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1;
  2480. if (lineN > last)
  2481. { return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, null, 1, 1) }
  2482. if (x < 0) { x = 0; }
  2483. var lineObj = getLine(doc, lineN);
  2484. for (;;) {
  2485. var found = coordsCharInner(cm, lineObj, lineN, x, y);
  2486. var collapsed = collapsedSpanAround(lineObj, found.ch + (found.xRel > 0 || found.outside > 0 ? 1 : 0));
  2487. if (!collapsed) { return found }
  2488. var rangeEnd = collapsed.find(1);
  2489. if (rangeEnd.line == lineN) { return rangeEnd }
  2490. lineObj = getLine(doc, lineN = rangeEnd.line);
  2491. }
  2492. }
  2493. function wrappedLineExtent(cm, lineObj, preparedMeasure, y) {
  2494. y -= widgetTopHeight(lineObj);
  2495. var end = lineObj.text.length;
  2496. var begin = findFirst(function (ch) { return measureCharPrepared(cm, preparedMeasure, ch - 1).bottom <= y; }, end, 0);
  2497. end = findFirst(function (ch) { return measureCharPrepared(cm, preparedMeasure, ch).top > y; }, begin, end);
  2498. return {begin: begin, end: end}
  2499. }
  2500. function wrappedLineExtentChar(cm, lineObj, preparedMeasure, target) {
  2501. if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj); }
  2502. var targetTop = intoCoordSystem(cm, lineObj, measureCharPrepared(cm, preparedMeasure, target), "line").top;
  2503. return wrappedLineExtent(cm, lineObj, preparedMeasure, targetTop)
  2504. }
  2505. // Returns true if the given side of a box is after the given
  2506. // coordinates, in top-to-bottom, left-to-right order.
  2507. function boxIsAfter(box, x, y, left) {
  2508. return box.bottom <= y ? false : box.top > y ? true : (left ? box.left : box.right) > x
  2509. }
  2510. function coordsCharInner(cm, lineObj, lineNo, x, y) {
  2511. // Move y into line-local coordinate space
  2512. y -= heightAtLine(lineObj);
  2513. var preparedMeasure = prepareMeasureForLine(cm, lineObj);
  2514. // When directly calling `measureCharPrepared`, we have to adjust
  2515. // for the widgets at this line.
  2516. var widgetHeight = widgetTopHeight(lineObj);
  2517. var begin = 0, end = lineObj.text.length, ltr = true;
  2518. var order = getOrder(lineObj, cm.doc.direction);
  2519. // If the line isn't plain left-to-right text, first figure out
  2520. // which bidi section the coordinates fall into.
  2521. if (order) {
  2522. var part = (cm.options.lineWrapping ? coordsBidiPartWrapped : coordsBidiPart)
  2523. (cm, lineObj, lineNo, preparedMeasure, order, x, y);
  2524. ltr = part.level != 1;
  2525. // The awkward -1 offsets are needed because findFirst (called
  2526. // on these below) will treat its first bound as inclusive,
  2527. // second as exclusive, but we want to actually address the
  2528. // characters in the part's range
  2529. begin = ltr ? part.from : part.to - 1;
  2530. end = ltr ? part.to : part.from - 1;
  2531. }
  2532. // A binary search to find the first character whose bounding box
  2533. // starts after the coordinates. If we run across any whose box wrap
  2534. // the coordinates, store that.
  2535. var chAround = null, boxAround = null;
  2536. var ch = findFirst(function (ch) {
  2537. var box = measureCharPrepared(cm, preparedMeasure, ch);
  2538. box.top += widgetHeight; box.bottom += widgetHeight;
  2539. if (!boxIsAfter(box, x, y, false)) { return false }
  2540. if (box.top <= y && box.left <= x) {
  2541. chAround = ch;
  2542. boxAround = box;
  2543. }
  2544. return true
  2545. }, begin, end);
  2546. var baseX, sticky, outside = false;
  2547. // If a box around the coordinates was found, use that
  2548. if (boxAround) {
  2549. // Distinguish coordinates nearer to the left or right side of the box
  2550. var atLeft = x - boxAround.left < boxAround.right - x, atStart = atLeft == ltr;
  2551. ch = chAround + (atStart ? 0 : 1);
  2552. sticky = atStart ? "after" : "before";
  2553. baseX = atLeft ? boxAround.left : boxAround.right;
  2554. } else {
  2555. // (Adjust for extended bound, if necessary.)
  2556. if (!ltr && (ch == end || ch == begin)) { ch++; }
  2557. // To determine which side to associate with, get the box to the
  2558. // left of the character and compare it's vertical position to the
  2559. // coordinates
  2560. sticky = ch == 0 ? "after" : ch == lineObj.text.length ? "before" :
  2561. (measureCharPrepared(cm, preparedMeasure, ch - (ltr ? 1 : 0)).bottom + widgetHeight <= y) == ltr ?
  2562. "after" : "before";
  2563. // Now get accurate coordinates for this place, in order to get a
  2564. // base X position
  2565. var coords = cursorCoords(cm, Pos(lineNo, ch, sticky), "line", lineObj, preparedMeasure);
  2566. baseX = coords.left;
  2567. outside = y < coords.top ? -1 : y >= coords.bottom ? 1 : 0;
  2568. }
  2569. ch = skipExtendingChars(lineObj.text, ch, 1);
  2570. return PosWithInfo(lineNo, ch, sticky, outside, x - baseX)
  2571. }
  2572. function coordsBidiPart(cm, lineObj, lineNo, preparedMeasure, order, x, y) {
  2573. // Bidi parts are sorted left-to-right, and in a non-line-wrapping
  2574. // situation, we can take this ordering to correspond to the visual
  2575. // ordering. This finds the first part whose end is after the given
  2576. // coordinates.
  2577. var index = findFirst(function (i) {
  2578. var part = order[i], ltr = part.level != 1;
  2579. return boxIsAfter(cursorCoords(cm, Pos(lineNo, ltr ? part.to : part.from, ltr ? "before" : "after"),
  2580. "line", lineObj, preparedMeasure), x, y, true)
  2581. }, 0, order.length - 1);
  2582. var part = order[index];
  2583. // If this isn't the first part, the part's start is also after
  2584. // the coordinates, and the coordinates aren't on the same line as
  2585. // that start, move one part back.
  2586. if (index > 0) {
  2587. var ltr = part.level != 1;
  2588. var start = cursorCoords(cm, Pos(lineNo, ltr ? part.from : part.to, ltr ? "after" : "before"),
  2589. "line", lineObj, preparedMeasure);
  2590. if (boxIsAfter(start, x, y, true) && start.top > y)
  2591. { part = order[index - 1]; }
  2592. }
  2593. return part
  2594. }
  2595. function coordsBidiPartWrapped(cm, lineObj, _lineNo, preparedMeasure, order, x, y) {
  2596. // In a wrapped line, rtl text on wrapping boundaries can do things
  2597. // that don't correspond to the ordering in our `order` array at
  2598. // all, so a binary search doesn't work, and we want to return a
  2599. // part that only spans one line so that the binary search in
  2600. // coordsCharInner is safe. As such, we first find the extent of the
  2601. // wrapped line, and then do a flat search in which we discard any
  2602. // spans that aren't on the line.
  2603. var ref = wrappedLineExtent(cm, lineObj, preparedMeasure, y);
  2604. var begin = ref.begin;
  2605. var end = ref.end;
  2606. if (/\s/.test(lineObj.text.charAt(end - 1))) { end--; }
  2607. var part = null, closestDist = null;
  2608. for (var i = 0; i < order.length; i++) {
  2609. var p = order[i];
  2610. if (p.from >= end || p.to <= begin) { continue }
  2611. var ltr = p.level != 1;
  2612. var endX = measureCharPrepared(cm, preparedMeasure, ltr ? Math.min(end, p.to) - 1 : Math.max(begin, p.from)).right;
  2613. // Weigh against spans ending before this, so that they are only
  2614. // picked if nothing ends after
  2615. var dist = endX < x ? x - endX + 1e9 : endX - x;
  2616. if (!part || closestDist > dist) {
  2617. part = p;
  2618. closestDist = dist;
  2619. }
  2620. }
  2621. if (!part) { part = order[order.length - 1]; }
  2622. // Clip the part to the wrapped line.
  2623. if (part.from < begin) { part = {from: begin, to: part.to, level: part.level}; }
  2624. if (part.to > end) { part = {from: part.from, to: end, level: part.level}; }
  2625. return part
  2626. }
  2627. var measureText;
  2628. // Compute the default text height.
  2629. function textHeight(display) {
  2630. if (display.cachedTextHeight != null) { return display.cachedTextHeight }
  2631. if (measureText == null) {
  2632. measureText = elt("pre", null, "CodeMirror-line-like");
  2633. // Measure a bunch of lines, for browsers that compute
  2634. // fractional heights.
  2635. for (var i = 0; i < 49; ++i) {
  2636. measureText.appendChild(document.createTextNode("x"));
  2637. measureText.appendChild(elt("br"));
  2638. }
  2639. measureText.appendChild(document.createTextNode("x"));
  2640. }
  2641. removeChildrenAndAdd(display.measure, measureText);
  2642. var height = measureText.offsetHeight / 50;
  2643. if (height > 3) { display.cachedTextHeight = height; }
  2644. removeChildren(display.measure);
  2645. return height || 1
  2646. }
  2647. // Compute the default character width.
  2648. function charWidth(display) {
  2649. if (display.cachedCharWidth != null) { return display.cachedCharWidth }
  2650. var anchor = elt("span", "xxxxxxxxxx");
  2651. var pre = elt("pre", [anchor], "CodeMirror-line-like");
  2652. removeChildrenAndAdd(display.measure, pre);
  2653. var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10;
  2654. if (width > 2) { display.cachedCharWidth = width; }
  2655. return width || 10
  2656. }
  2657. // Do a bulk-read of the DOM positions and sizes needed to draw the
  2658. // view, so that we don't interleave reading and writing to the DOM.
  2659. function getDimensions(cm) {
  2660. var d = cm.display, left = {}, width = {};
  2661. var gutterLeft = d.gutters.clientLeft;
  2662. for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) {
  2663. var id = cm.display.gutterSpecs[i].className;
  2664. left[id] = n.offsetLeft + n.clientLeft + gutterLeft;
  2665. width[id] = n.clientWidth;
  2666. }
  2667. return {fixedPos: compensateForHScroll(d),
  2668. gutterTotalWidth: d.gutters.offsetWidth,
  2669. gutterLeft: left,
  2670. gutterWidth: width,
  2671. wrapperWidth: d.wrapper.clientWidth}
  2672. }
  2673. // Computes display.scroller.scrollLeft + display.gutters.offsetWidth,
  2674. // but using getBoundingClientRect to get a sub-pixel-accurate
  2675. // result.
  2676. function compensateForHScroll(display) {
  2677. return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left
  2678. }
  2679. // Returns a function that estimates the height of a line, to use as
  2680. // first approximation until the line becomes visible (and is thus
  2681. // properly measurable).
  2682. function estimateHeight(cm) {
  2683. var th = textHeight(cm.display), wrapping = cm.options.lineWrapping;
  2684. var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3);
  2685. return function (line) {
  2686. if (lineIsHidden(cm.doc, line)) { return 0 }
  2687. var widgetsHeight = 0;
  2688. if (line.widgets) { for (var i = 0; i < line.widgets.length; i++) {
  2689. if (line.widgets[i].height) { widgetsHeight += line.widgets[i].height; }
  2690. } }
  2691. if (wrapping)
  2692. { return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th }
  2693. else
  2694. { return widgetsHeight + th }
  2695. }
  2696. }
  2697. function estimateLineHeights(cm) {
  2698. var doc = cm.doc, est = estimateHeight(cm);
  2699. doc.iter(function (line) {
  2700. var estHeight = est(line);
  2701. if (estHeight != line.height) { updateLineHeight(line, estHeight); }
  2702. });
  2703. }
  2704. // Given a mouse event, find the corresponding position. If liberal
  2705. // is false, it checks whether a gutter or scrollbar was clicked,
  2706. // and returns null if it was. forRect is used by rectangular
  2707. // selections, and tries to estimate a character position even for
  2708. // coordinates beyond the right of the text.
  2709. function posFromMouse(cm, e, liberal, forRect) {
  2710. var display = cm.display;
  2711. if (!liberal && e_target(e).getAttribute("cm-not-content") == "true") { return null }
  2712. var x, y, space = display.lineSpace.getBoundingClientRect();
  2713. // Fails unpredictably on IE[67] when mouse is dragged around quickly.
  2714. try { x = e.clientX - space.left; y = e.clientY - space.top; }
  2715. catch (e$1) { return null }
  2716. var coords = coordsChar(cm, x, y), line;
  2717. if (forRect && coords.xRel > 0 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) {
  2718. var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length;
  2719. coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff));
  2720. }
  2721. return coords
  2722. }
  2723. // Find the view element corresponding to a given line. Return null
  2724. // when the line isn't visible.
  2725. function findViewIndex(cm, n) {
  2726. if (n >= cm.display.viewTo) { return null }
  2727. n -= cm.display.viewFrom;
  2728. if (n < 0) { return null }
  2729. var view = cm.display.view;
  2730. for (var i = 0; i < view.length; i++) {
  2731. n -= view[i].size;
  2732. if (n < 0) { return i }
  2733. }
  2734. }
  2735. // Updates the display.view data structure for a given change to the
  2736. // document. From and to are in pre-change coordinates. Lendiff is
  2737. // the amount of lines added or subtracted by the change. This is
  2738. // used for changes that span multiple lines, or change the way
  2739. // lines are divided into visual lines. regLineChange (below)
  2740. // registers single-line changes.
  2741. function regChange(cm, from, to, lendiff) {
  2742. if (from == null) { from = cm.doc.first; }
  2743. if (to == null) { to = cm.doc.first + cm.doc.size; }
  2744. if (!lendiff) { lendiff = 0; }
  2745. var display = cm.display;
  2746. if (lendiff && to < display.viewTo &&
  2747. (display.updateLineNumbers == null || display.updateLineNumbers > from))
  2748. { display.updateLineNumbers = from; }
  2749. cm.curOp.viewChanged = true;
  2750. if (from >= display.viewTo) { // Change after
  2751. if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo)
  2752. { resetView(cm); }
  2753. } else if (to <= display.viewFrom) { // Change before
  2754. if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) {
  2755. resetView(cm);
  2756. } else {
  2757. display.viewFrom += lendiff;
  2758. display.viewTo += lendiff;
  2759. }
  2760. } else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap
  2761. resetView(cm);
  2762. } else if (from <= display.viewFrom) { // Top overlap
  2763. var cut = viewCuttingPoint(cm, to, to + lendiff, 1);
  2764. if (cut) {
  2765. display.view = display.view.slice(cut.index);
  2766. display.viewFrom = cut.lineN;
  2767. display.viewTo += lendiff;
  2768. } else {
  2769. resetView(cm);
  2770. }
  2771. } else if (to >= display.viewTo) { // Bottom overlap
  2772. var cut$1 = viewCuttingPoint(cm, from, from, -1);
  2773. if (cut$1) {
  2774. display.view = display.view.slice(0, cut$1.index);
  2775. display.viewTo = cut$1.lineN;
  2776. } else {
  2777. resetView(cm);
  2778. }
  2779. } else { // Gap in the middle
  2780. var cutTop = viewCuttingPoint(cm, from, from, -1);
  2781. var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1);
  2782. if (cutTop && cutBot) {
  2783. display.view = display.view.slice(0, cutTop.index)
  2784. .concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN))
  2785. .concat(display.view.slice(cutBot.index));
  2786. display.viewTo += lendiff;
  2787. } else {
  2788. resetView(cm);
  2789. }
  2790. }
  2791. var ext = display.externalMeasured;
  2792. if (ext) {
  2793. if (to < ext.lineN)
  2794. { ext.lineN += lendiff; }
  2795. else if (from < ext.lineN + ext.size)
  2796. { display.externalMeasured = null; }
  2797. }
  2798. }
  2799. // Register a change to a single line. Type must be one of "text",
  2800. // "gutter", "class", "widget"
  2801. function regLineChange(cm, line, type) {
  2802. cm.curOp.viewChanged = true;
  2803. var display = cm.display, ext = cm.display.externalMeasured;
  2804. if (ext && line >= ext.lineN && line < ext.lineN + ext.size)
  2805. { display.externalMeasured = null; }
  2806. if (line < display.viewFrom || line >= display.viewTo) { return }
  2807. var lineView = display.view[findViewIndex(cm, line)];
  2808. if (lineView.node == null) { return }
  2809. var arr = lineView.changes || (lineView.changes = []);
  2810. if (indexOf(arr, type) == -1) { arr.push(type); }
  2811. }
  2812. // Clear the view.
  2813. function resetView(cm) {
  2814. cm.display.viewFrom = cm.display.viewTo = cm.doc.first;
  2815. cm.display.view = [];
  2816. cm.display.viewOffset = 0;
  2817. }
  2818. function viewCuttingPoint(cm, oldN, newN, dir) {
  2819. var index = findViewIndex(cm, oldN), diff, view = cm.display.view;
  2820. if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size)
  2821. { return {index: index, lineN: newN} }
  2822. var n = cm.display.viewFrom;
  2823. for (var i = 0; i < index; i++)
  2824. { n += view[i].size; }
  2825. if (n != oldN) {
  2826. if (dir > 0) {
  2827. if (index == view.length - 1) { return null }
  2828. diff = (n + view[index].size) - oldN;
  2829. index++;
  2830. } else {
  2831. diff = n - oldN;
  2832. }
  2833. oldN += diff; newN += diff;
  2834. }
  2835. while (visualLineNo(cm.doc, newN) != newN) {
  2836. if (index == (dir < 0 ? 0 : view.length - 1)) { return null }
  2837. newN += dir * view[index - (dir < 0 ? 1 : 0)].size;
  2838. index += dir;
  2839. }
  2840. return {index: index, lineN: newN}
  2841. }
  2842. // Force the view to cover a given range, adding empty view element
  2843. // or clipping off existing ones as needed.
  2844. function adjustView(cm, from, to) {
  2845. var display = cm.display, view = display.view;
  2846. if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) {
  2847. display.view = buildViewArray(cm, from, to);
  2848. display.viewFrom = from;
  2849. } else {
  2850. if (display.viewFrom > from)
  2851. { display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view); }
  2852. else if (display.viewFrom < from)
  2853. { display.view = display.view.slice(findViewIndex(cm, from)); }
  2854. display.viewFrom = from;
  2855. if (display.viewTo < to)
  2856. { display.view = display.view.concat(buildViewArray(cm, display.viewTo, to)); }
  2857. else if (display.viewTo > to)
  2858. { display.view = display.view.slice(0, findViewIndex(cm, to)); }
  2859. }
  2860. display.viewTo = to;
  2861. }
  2862. // Count the number of lines in the view whose DOM representation is
  2863. // out of date (or nonexistent).
  2864. function countDirtyView(cm) {
  2865. var view = cm.display.view, dirty = 0;
  2866. for (var i = 0; i < view.length; i++) {
  2867. var lineView = view[i];
  2868. if (!lineView.hidden && (!lineView.node || lineView.changes)) { ++dirty; }
  2869. }
  2870. return dirty
  2871. }
  2872. function updateSelection(cm) {
  2873. cm.display.input.showSelection(cm.display.input.prepareSelection());
  2874. }
  2875. function prepareSelection(cm, primary) {
  2876. if ( primary === void 0 ) primary = true;
  2877. var doc = cm.doc, result = {};
  2878. var curFragment = result.cursors = document.createDocumentFragment();
  2879. var selFragment = result.selection = document.createDocumentFragment();
  2880. var customCursor = cm.options.$customCursor;
  2881. if (customCursor) { primary = true; }
  2882. for (var i = 0; i < doc.sel.ranges.length; i++) {
  2883. if (!primary && i == doc.sel.primIndex) { continue }
  2884. var range = doc.sel.ranges[i];
  2885. if (range.from().line >= cm.display.viewTo || range.to().line < cm.display.viewFrom) { continue }
  2886. var collapsed = range.empty();
  2887. if (customCursor) {
  2888. var head = customCursor(cm, range);
  2889. if (head) { drawSelectionCursor(cm, head, curFragment); }
  2890. } else if (collapsed || cm.options.showCursorWhenSelecting) {
  2891. drawSelectionCursor(cm, range.head, curFragment);
  2892. }
  2893. if (!collapsed)
  2894. { drawSelectionRange(cm, range, selFragment); }
  2895. }
  2896. return result
  2897. }
  2898. // Draws a cursor for the given range
  2899. function drawSelectionCursor(cm, head, output) {
  2900. var pos = cursorCoords(cm, head, "div", null, null, !cm.options.singleCursorHeightPerLine);
  2901. var cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor"));
  2902. cursor.style.left = pos.left + "px";
  2903. cursor.style.top = pos.top + "px";
  2904. cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px";
  2905. if (/\bcm-fat-cursor\b/.test(cm.getWrapperElement().className)) {
  2906. var charPos = charCoords(cm, head, "div", null, null);
  2907. var width = charPos.right - charPos.left;
  2908. cursor.style.width = (width > 0 ? width : cm.defaultCharWidth()) + "px";
  2909. }
  2910. if (pos.other) {
  2911. // Secondary cursor, shown when on a 'jump' in bi-directional text
  2912. var otherCursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor"));
  2913. otherCursor.style.display = "";
  2914. otherCursor.style.left = pos.other.left + "px";
  2915. otherCursor.style.top = pos.other.top + "px";
  2916. otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px";
  2917. }
  2918. }
  2919. function cmpCoords(a, b) { return a.top - b.top || a.left - b.left }
  2920. // Draws the given range as a highlighted selection
  2921. function drawSelectionRange(cm, range, output) {
  2922. var display = cm.display, doc = cm.doc;
  2923. var fragment = document.createDocumentFragment();
  2924. var padding = paddingH(cm.display), leftSide = padding.left;
  2925. var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right;
  2926. var docLTR = doc.direction == "ltr";
  2927. function add(left, top, width, bottom) {
  2928. if (top < 0) { top = 0; }
  2929. top = Math.round(top);
  2930. bottom = Math.round(bottom);
  2931. 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")));
  2932. }
  2933. function drawForLine(line, fromArg, toArg) {
  2934. var lineObj = getLine(doc, line);
  2935. var lineLen = lineObj.text.length;
  2936. var start, end;
  2937. function coords(ch, bias) {
  2938. return charCoords(cm, Pos(line, ch), "div", lineObj, bias)
  2939. }
  2940. function wrapX(pos, dir, side) {
  2941. var extent = wrappedLineExtentChar(cm, lineObj, null, pos);
  2942. var prop = (dir == "ltr") == (side == "after") ? "left" : "right";
  2943. var ch = side == "after" ? extent.begin : extent.end - (/\s/.test(lineObj.text.charAt(extent.end - 1)) ? 2 : 1);
  2944. return coords(ch, prop)[prop]
  2945. }
  2946. var order = getOrder(lineObj, doc.direction);
  2947. iterateBidiSections(order, fromArg || 0, toArg == null ? lineLen : toArg, function (from, to, dir, i) {
  2948. var ltr = dir == "ltr";
  2949. var fromPos = coords(from, ltr ? "left" : "right");
  2950. var toPos = coords(to - 1, ltr ? "right" : "left");
  2951. var openStart = fromArg == null && from == 0, openEnd = toArg == null && to == lineLen;
  2952. var first = i == 0, last = !order || i == order.length - 1;
  2953. if (toPos.top - fromPos.top <= 3) { // Single line
  2954. var openLeft = (docLTR ? openStart : openEnd) && first;
  2955. var openRight = (docLTR ? openEnd : openStart) && last;
  2956. var left = openLeft ? leftSide : (ltr ? fromPos : toPos).left;
  2957. var right = openRight ? rightSide : (ltr ? toPos : fromPos).right;
  2958. add(left, fromPos.top, right - left, fromPos.bottom);
  2959. } else { // Multiple lines
  2960. var topLeft, topRight, botLeft, botRight;
  2961. if (ltr) {
  2962. topLeft = docLTR && openStart && first ? leftSide : fromPos.left;
  2963. topRight = docLTR ? rightSide : wrapX(from, dir, "before");
  2964. botLeft = docLTR ? leftSide : wrapX(to, dir, "after");
  2965. botRight = docLTR && openEnd && last ? rightSide : toPos.right;
  2966. } else {
  2967. topLeft = !docLTR ? leftSide : wrapX(from, dir, "before");
  2968. topRight = !docLTR && openStart && first ? rightSide : fromPos.right;
  2969. botLeft = !docLTR && openEnd && last ? leftSide : toPos.left;
  2970. botRight = !docLTR ? rightSide : wrapX(to, dir, "after");
  2971. }
  2972. add(topLeft, fromPos.top, topRight - topLeft, fromPos.bottom);
  2973. if (fromPos.bottom < toPos.top) { add(leftSide, fromPos.bottom, null, toPos.top); }
  2974. add(botLeft, toPos.top, botRight - botLeft, toPos.bottom);
  2975. }
  2976. if (!start || cmpCoords(fromPos, start) < 0) { start = fromPos; }
  2977. if (cmpCoords(toPos, start) < 0) { start = toPos; }
  2978. if (!end || cmpCoords(fromPos, end) < 0) { end = fromPos; }
  2979. if (cmpCoords(toPos, end) < 0) { end = toPos; }
  2980. });
  2981. return {start: start, end: end}
  2982. }
  2983. var sFrom = range.from(), sTo = range.to();
  2984. if (sFrom.line == sTo.line) {
  2985. drawForLine(sFrom.line, sFrom.ch, sTo.ch);
  2986. } else {
  2987. var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line);
  2988. var singleVLine = visualLine(fromLine) == visualLine(toLine);
  2989. var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end;
  2990. var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start;
  2991. if (singleVLine) {
  2992. if (leftEnd.top < rightStart.top - 2) {
  2993. add(leftEnd.right, leftEnd.top, null, leftEnd.bottom);
  2994. add(leftSide, rightStart.top, rightStart.left, rightStart.bottom);
  2995. } else {
  2996. add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom);
  2997. }
  2998. }
  2999. if (leftEnd.bottom < rightStart.top)
  3000. { add(leftSide, leftEnd.bottom, null, rightStart.top); }
  3001. }
  3002. output.appendChild(fragment);
  3003. }
  3004. // Cursor-blinking
  3005. function restartBlink(cm) {
  3006. if (!cm.state.focused) { return }
  3007. var display = cm.display;
  3008. clearInterval(display.blinker);
  3009. var on = true;
  3010. display.cursorDiv.style.visibility = "";
  3011. if (cm.options.cursorBlinkRate > 0)
  3012. { display.blinker = setInterval(function () {
  3013. if (!cm.hasFocus()) { onBlur(cm); }
  3014. display.cursorDiv.style.visibility = (on = !on) ? "" : "hidden";
  3015. }, cm.options.cursorBlinkRate); }
  3016. else if (cm.options.cursorBlinkRate < 0)
  3017. { display.cursorDiv.style.visibility = "hidden"; }
  3018. }
  3019. function ensureFocus(cm) {
  3020. if (!cm.hasFocus()) {
  3021. cm.display.input.focus();
  3022. if (!cm.state.focused) { onFocus(cm); }
  3023. }
  3024. }
  3025. function delayBlurEvent(cm) {
  3026. cm.state.delayingBlurEvent = true;
  3027. setTimeout(function () { if (cm.state.delayingBlurEvent) {
  3028. cm.state.delayingBlurEvent = false;
  3029. if (cm.state.focused) { onBlur(cm); }
  3030. } }, 100);
  3031. }
  3032. function onFocus(cm, e) {
  3033. if (cm.state.delayingBlurEvent && !cm.state.draggingText) { cm.state.delayingBlurEvent = false; }
  3034. if (cm.options.readOnly == "nocursor") { return }
  3035. if (!cm.state.focused) {
  3036. signal(cm, "focus", cm, e);
  3037. cm.state.focused = true;
  3038. addClass(cm.display.wrapper, "CodeMirror-focused");
  3039. // This test prevents this from firing when a context
  3040. // menu is closed (since the input reset would kill the
  3041. // select-all detection hack)
  3042. if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) {
  3043. cm.display.input.reset();
  3044. if (webkit) { setTimeout(function () { return cm.display.input.reset(true); }, 20); } // Issue #1730
  3045. }
  3046. cm.display.input.receivedFocus();
  3047. }
  3048. restartBlink(cm);
  3049. }
  3050. function onBlur(cm, e) {
  3051. if (cm.state.delayingBlurEvent) { return }
  3052. if (cm.state.focused) {
  3053. signal(cm, "blur", cm, e);
  3054. cm.state.focused = false;
  3055. rmClass(cm.display.wrapper, "CodeMirror-focused");
  3056. }
  3057. clearInterval(cm.display.blinker);
  3058. setTimeout(function () { if (!cm.state.focused) { cm.display.shift = false; } }, 150);
  3059. }
  3060. // Read the actual heights of the rendered lines, and update their
  3061. // stored heights to match.
  3062. function updateHeightsInViewport(cm) {
  3063. var display = cm.display;
  3064. var prevBottom = display.lineDiv.offsetTop;
  3065. var viewTop = Math.max(0, display.scroller.getBoundingClientRect().top);
  3066. var oldHeight = display.lineDiv.getBoundingClientRect().top;
  3067. var mustScroll = 0;
  3068. for (var i = 0; i < display.view.length; i++) {
  3069. var cur = display.view[i], wrapping = cm.options.lineWrapping;
  3070. var height = (void 0), width = 0;
  3071. if (cur.hidden) { continue }
  3072. oldHeight += cur.line.height;
  3073. if (ie && ie_version < 8) {
  3074. var bot = cur.node.offsetTop + cur.node.offsetHeight;
  3075. height = bot - prevBottom;
  3076. prevBottom = bot;
  3077. } else {
  3078. var box = cur.node.getBoundingClientRect();
  3079. height = box.bottom - box.top;
  3080. // Check that lines don't extend past the right of the current
  3081. // editor width
  3082. if (!wrapping && cur.text.firstChild)
  3083. { width = cur.text.firstChild.getBoundingClientRect().right - box.left - 1; }
  3084. }
  3085. var diff = cur.line.height - height;
  3086. if (diff > .005 || diff < -.005) {
  3087. if (oldHeight < viewTop) { mustScroll -= diff; }
  3088. updateLineHeight(cur.line, height);
  3089. updateWidgetHeight(cur.line);
  3090. if (cur.rest) { for (var j = 0; j < cur.rest.length; j++)
  3091. { updateWidgetHeight(cur.rest[j]); } }
  3092. }
  3093. if (width > cm.display.sizerWidth) {
  3094. var chWidth = Math.ceil(width / charWidth(cm.display));
  3095. if (chWidth > cm.display.maxLineLength) {
  3096. cm.display.maxLineLength = chWidth;
  3097. cm.display.maxLine = cur.line;
  3098. cm.display.maxLineChanged = true;
  3099. }
  3100. }
  3101. }
  3102. if (Math.abs(mustScroll) > 2) { display.scroller.scrollTop += mustScroll; }
  3103. }
  3104. // Read and store the height of line widgets associated with the
  3105. // given line.
  3106. function updateWidgetHeight(line) {
  3107. if (line.widgets) { for (var i = 0; i < line.widgets.length; ++i) {
  3108. var w = line.widgets[i], parent = w.node.parentNode;
  3109. if (parent) { w.height = parent.offsetHeight; }
  3110. } }
  3111. }
  3112. // Compute the lines that are visible in a given viewport (defaults
  3113. // the the current scroll position). viewport may contain top,
  3114. // height, and ensure (see op.scrollToPos) properties.
  3115. function visibleLines(display, doc, viewport) {
  3116. var top = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop;
  3117. top = Math.floor(top - paddingTop(display));
  3118. var bottom = viewport && viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight;
  3119. var from = lineAtHeight(doc, top), to = lineAtHeight(doc, bottom);
  3120. // Ensure is a {from: {line, ch}, to: {line, ch}} object, and
  3121. // forces those lines into the viewport (if possible).
  3122. if (viewport && viewport.ensure) {
  3123. var ensureFrom = viewport.ensure.from.line, ensureTo = viewport.ensure.to.line;
  3124. if (ensureFrom < from) {
  3125. from = ensureFrom;
  3126. to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight);
  3127. } else if (Math.min(ensureTo, doc.lastLine()) >= to) {
  3128. from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight);
  3129. to = ensureTo;
  3130. }
  3131. }
  3132. return {from: from, to: Math.max(to, from + 1)}
  3133. }
  3134. // SCROLLING THINGS INTO VIEW
  3135. // If an editor sits on the top or bottom of the window, partially
  3136. // scrolled out of view, this ensures that the cursor is visible.
  3137. function maybeScrollWindow(cm, rect) {
  3138. if (signalDOMEvent(cm, "scrollCursorIntoView")) { return }
  3139. var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null;
  3140. if (rect.top + box.top < 0) { doScroll = true; }
  3141. else if (rect.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) { doScroll = false; }
  3142. if (doScroll != null && !phantom) {
  3143. 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;"));
  3144. cm.display.lineSpace.appendChild(scrollNode);
  3145. scrollNode.scrollIntoView(doScroll);
  3146. cm.display.lineSpace.removeChild(scrollNode);
  3147. }
  3148. }
  3149. // Scroll a given position into view (immediately), verifying that
  3150. // it actually became visible (as line heights are accurately
  3151. // measured, the position of something may 'drift' during drawing).
  3152. function scrollPosIntoView(cm, pos, end, margin) {
  3153. if (margin == null) { margin = 0; }
  3154. var rect;
  3155. if (!cm.options.lineWrapping && pos == end) {
  3156. // Set pos and end to the cursor positions around the character pos sticks to
  3157. // If pos.sticky == "before", that is around pos.ch - 1, otherwise around pos.ch
  3158. // If pos == Pos(_, 0, "before"), pos and end are unchanged
  3159. end = pos.sticky == "before" ? Pos(pos.line, pos.ch + 1, "before") : pos;
  3160. pos = pos.ch ? Pos(pos.line, pos.sticky == "before" ? pos.ch - 1 : pos.ch, "after") : pos;
  3161. }
  3162. for (var limit = 0; limit < 5; limit++) {
  3163. var changed = false;
  3164. var coords = cursorCoords(cm, pos);
  3165. var endCoords = !end || end == pos ? coords : cursorCoords(cm, end);
  3166. rect = {left: Math.min(coords.left, endCoords.left),
  3167. top: Math.min(coords.top, endCoords.top) - margin,
  3168. right: Math.max(coords.left, endCoords.left),
  3169. bottom: Math.max(coords.bottom, endCoords.bottom) + margin};
  3170. var scrollPos = calculateScrollPos(cm, rect);
  3171. var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft;
  3172. if (scrollPos.scrollTop != null) {
  3173. updateScrollTop(cm, scrollPos.scrollTop);
  3174. if (Math.abs(cm.doc.scrollTop - startTop) > 1) { changed = true; }
  3175. }
  3176. if (scrollPos.scrollLeft != null) {
  3177. setScrollLeft(cm, scrollPos.scrollLeft);
  3178. if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) { changed = true; }
  3179. }
  3180. if (!changed) { break }
  3181. }
  3182. return rect
  3183. }
  3184. // Scroll a given set of coordinates into view (immediately).
  3185. function scrollIntoView(cm, rect) {
  3186. var scrollPos = calculateScrollPos(cm, rect);
  3187. if (scrollPos.scrollTop != null) { updateScrollTop(cm, scrollPos.scrollTop); }
  3188. if (scrollPos.scrollLeft != null) { setScrollLeft(cm, scrollPos.scrollLeft); }
  3189. }
  3190. // Calculate a new scroll position needed to scroll the given
  3191. // rectangle into view. Returns an object with scrollTop and
  3192. // scrollLeft properties. When these are undefined, the
  3193. // vertical/horizontal position does not need to be adjusted.
  3194. function calculateScrollPos(cm, rect) {
  3195. var display = cm.display, snapMargin = textHeight(cm.display);
  3196. if (rect.top < 0) { rect.top = 0; }
  3197. var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop;
  3198. var screen = displayHeight(cm), result = {};
  3199. if (rect.bottom - rect.top > screen) { rect.bottom = rect.top + screen; }
  3200. var docBottom = cm.doc.height + paddingVert(display);
  3201. var atTop = rect.top < snapMargin, atBottom = rect.bottom > docBottom - snapMargin;
  3202. if (rect.top < screentop) {
  3203. result.scrollTop = atTop ? 0 : rect.top;
  3204. } else if (rect.bottom > screentop + screen) {
  3205. var newTop = Math.min(rect.top, (atBottom ? docBottom : rect.bottom) - screen);
  3206. if (newTop != screentop) { result.scrollTop = newTop; }
  3207. }
  3208. var gutterSpace = cm.options.fixedGutter ? 0 : display.gutters.offsetWidth;
  3209. var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft - gutterSpace;
  3210. var screenw = displayWidth(cm) - display.gutters.offsetWidth;
  3211. var tooWide = rect.right - rect.left > screenw;
  3212. if (tooWide) { rect.right = rect.left + screenw; }
  3213. if (rect.left < 10)
  3214. { result.scrollLeft = 0; }
  3215. else if (rect.left < screenleft)
  3216. { result.scrollLeft = Math.max(0, rect.left + gutterSpace - (tooWide ? 0 : 10)); }
  3217. else if (rect.right > screenw + screenleft - 3)
  3218. { result.scrollLeft = rect.right + (tooWide ? 0 : 10) - screenw; }
  3219. return result
  3220. }
  3221. // Store a relative adjustment to the scroll position in the current
  3222. // operation (to be applied when the operation finishes).
  3223. function addToScrollTop(cm, top) {
  3224. if (top == null) { return }
  3225. resolveScrollToPos(cm);
  3226. cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top;
  3227. }
  3228. // Make sure that at the end of the operation the current cursor is
  3229. // shown.
  3230. function ensureCursorVisible(cm) {
  3231. resolveScrollToPos(cm);
  3232. var cur = cm.getCursor();
  3233. cm.curOp.scrollToPos = {from: cur, to: cur, margin: cm.options.cursorScrollMargin};
  3234. }
  3235. function scrollToCoords(cm, x, y) {
  3236. if (x != null || y != null) { resolveScrollToPos(cm); }
  3237. if (x != null) { cm.curOp.scrollLeft = x; }
  3238. if (y != null) { cm.curOp.scrollTop = y; }
  3239. }
  3240. function scrollToRange(cm, range) {
  3241. resolveScrollToPos(cm);
  3242. cm.curOp.scrollToPos = range;
  3243. }
  3244. // When an operation has its scrollToPos property set, and another
  3245. // scroll action is applied before the end of the operation, this
  3246. // 'simulates' scrolling that position into view in a cheap way, so
  3247. // that the effect of intermediate scroll commands is not ignored.
  3248. function resolveScrollToPos(cm) {
  3249. var range = cm.curOp.scrollToPos;
  3250. if (range) {
  3251. cm.curOp.scrollToPos = null;
  3252. var from = estimateCoords(cm, range.from), to = estimateCoords(cm, range.to);
  3253. scrollToCoordsRange(cm, from, to, range.margin);
  3254. }
  3255. }
  3256. function scrollToCoordsRange(cm, from, to, margin) {
  3257. var sPos = calculateScrollPos(cm, {
  3258. left: Math.min(from.left, to.left),
  3259. top: Math.min(from.top, to.top) - margin,
  3260. right: Math.max(from.right, to.right),
  3261. bottom: Math.max(from.bottom, to.bottom) + margin
  3262. });
  3263. scrollToCoords(cm, sPos.scrollLeft, sPos.scrollTop);
  3264. }
  3265. // Sync the scrollable area and scrollbars, ensure the viewport
  3266. // covers the visible area.
  3267. function updateScrollTop(cm, val) {
  3268. if (Math.abs(cm.doc.scrollTop - val) < 2) { return }
  3269. if (!gecko) { updateDisplaySimple(cm, {top: val}); }
  3270. setScrollTop(cm, val, true);
  3271. if (gecko) { updateDisplaySimple(cm); }
  3272. startWorker(cm, 100);
  3273. }
  3274. function setScrollTop(cm, val, forceScroll) {
  3275. val = Math.max(0, Math.min(cm.display.scroller.scrollHeight - cm.display.scroller.clientHeight, val));
  3276. if (cm.display.scroller.scrollTop == val && !forceScroll) { return }
  3277. cm.doc.scrollTop = val;
  3278. cm.display.scrollbars.setScrollTop(val);
  3279. if (cm.display.scroller.scrollTop != val) { cm.display.scroller.scrollTop = val; }
  3280. }
  3281. // Sync scroller and scrollbar, ensure the gutter elements are
  3282. // aligned.
  3283. function setScrollLeft(cm, val, isScroller, forceScroll) {
  3284. val = Math.max(0, Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth));
  3285. if ((isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) && !forceScroll) { return }
  3286. cm.doc.scrollLeft = val;
  3287. alignHorizontally(cm);
  3288. if (cm.display.scroller.scrollLeft != val) { cm.display.scroller.scrollLeft = val; }
  3289. cm.display.scrollbars.setScrollLeft(val);
  3290. }
  3291. // SCROLLBARS
  3292. // Prepare DOM reads needed to update the scrollbars. Done in one
  3293. // shot to minimize update/measure roundtrips.
  3294. function measureForScrollbars(cm) {
  3295. var d = cm.display, gutterW = d.gutters.offsetWidth;
  3296. var docH = Math.round(cm.doc.height + paddingVert(cm.display));
  3297. return {
  3298. clientHeight: d.scroller.clientHeight,
  3299. viewHeight: d.wrapper.clientHeight,
  3300. scrollWidth: d.scroller.scrollWidth, clientWidth: d.scroller.clientWidth,
  3301. viewWidth: d.wrapper.clientWidth,
  3302. barLeft: cm.options.fixedGutter ? gutterW : 0,
  3303. docHeight: docH,
  3304. scrollHeight: docH + scrollGap(cm) + d.barHeight,
  3305. nativeBarWidth: d.nativeBarWidth,
  3306. gutterWidth: gutterW
  3307. }
  3308. }
  3309. var NativeScrollbars = function(place, scroll, cm) {
  3310. this.cm = cm;
  3311. var vert = this.vert = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar");
  3312. var horiz = this.horiz = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar");
  3313. vert.tabIndex = horiz.tabIndex = -1;
  3314. place(vert); place(horiz);
  3315. on(vert, "scroll", function () {
  3316. if (vert.clientHeight) { scroll(vert.scrollTop, "vertical"); }
  3317. });
  3318. on(horiz, "scroll", function () {
  3319. if (horiz.clientWidth) { scroll(horiz.scrollLeft, "horizontal"); }
  3320. });
  3321. this.checkedZeroWidth = false;
  3322. // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8).
  3323. if (ie && ie_version < 8) { this.horiz.style.minHeight = this.vert.style.minWidth = "18px"; }
  3324. };
  3325. NativeScrollbars.prototype.update = function (measure) {
  3326. var needsH = measure.scrollWidth > measure.clientWidth + 1;
  3327. var needsV = measure.scrollHeight > measure.clientHeight + 1;
  3328. var sWidth = measure.nativeBarWidth;
  3329. if (needsV) {
  3330. this.vert.style.display = "block";
  3331. this.vert.style.bottom = needsH ? sWidth + "px" : "0";
  3332. var totalHeight = measure.viewHeight - (needsH ? sWidth : 0);
  3333. // A bug in IE8 can cause this value to be negative, so guard it.
  3334. this.vert.firstChild.style.height =
  3335. Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + "px";
  3336. } else {
  3337. this.vert.scrollTop = 0;
  3338. this.vert.style.display = "";
  3339. this.vert.firstChild.style.height = "0";
  3340. }
  3341. if (needsH) {
  3342. this.horiz.style.display = "block";
  3343. this.horiz.style.right = needsV ? sWidth + "px" : "0";
  3344. this.horiz.style.left = measure.barLeft + "px";
  3345. var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0);
  3346. this.horiz.firstChild.style.width =
  3347. Math.max(0, measure.scrollWidth - measure.clientWidth + totalWidth) + "px";
  3348. } else {
  3349. this.horiz.style.display = "";
  3350. this.horiz.firstChild.style.width = "0";
  3351. }
  3352. if (!this.checkedZeroWidth && measure.clientHeight > 0) {
  3353. if (sWidth == 0) { this.zeroWidthHack(); }
  3354. this.checkedZeroWidth = true;
  3355. }
  3356. return {right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0}
  3357. };
  3358. NativeScrollbars.prototype.setScrollLeft = function (pos) {
  3359. if (this.horiz.scrollLeft != pos) { this.horiz.scrollLeft = pos; }
  3360. if (this.disableHoriz) { this.enableZeroWidthBar(this.horiz, this.disableHoriz, "horiz"); }
  3361. };
  3362. NativeScrollbars.prototype.setScrollTop = function (pos) {
  3363. if (this.vert.scrollTop != pos) { this.vert.scrollTop = pos; }
  3364. if (this.disableVert) { this.enableZeroWidthBar(this.vert, this.disableVert, "vert"); }
  3365. };
  3366. NativeScrollbars.prototype.zeroWidthHack = function () {
  3367. var w = mac && !mac_geMountainLion ? "12px" : "18px";
  3368. this.horiz.style.height = this.vert.style.width = w;
  3369. this.horiz.style.pointerEvents = this.vert.style.pointerEvents = "none";
  3370. this.disableHoriz = new Delayed;
  3371. this.disableVert = new Delayed;
  3372. };
  3373. NativeScrollbars.prototype.enableZeroWidthBar = function (bar, delay, type) {
  3374. bar.style.pointerEvents = "auto";
  3375. function maybeDisable() {
  3376. // To find out whether the scrollbar is still visible, we
  3377. // check whether the element under the pixel in the bottom
  3378. // right corner of the scrollbar box is the scrollbar box
  3379. // itself (when the bar is still visible) or its filler child
  3380. // (when the bar is hidden). If it is still visible, we keep
  3381. // it enabled, if it's hidden, we disable pointer events.
  3382. var box = bar.getBoundingClientRect();
  3383. var elt = type == "vert" ? document.elementFromPoint(box.right - 1, (box.top + box.bottom) / 2)
  3384. : document.elementFromPoint((box.right + box.left) / 2, box.bottom - 1);
  3385. if (elt != bar) { bar.style.pointerEvents = "none"; }
  3386. else { delay.set(1000, maybeDisable); }
  3387. }
  3388. delay.set(1000, maybeDisable);
  3389. };
  3390. NativeScrollbars.prototype.clear = function () {
  3391. var parent = this.horiz.parentNode;
  3392. parent.removeChild(this.horiz);
  3393. parent.removeChild(this.vert);
  3394. };
  3395. var NullScrollbars = function () {};
  3396. NullScrollbars.prototype.update = function () { return {bottom: 0, right: 0} };
  3397. NullScrollbars.prototype.setScrollLeft = function () {};
  3398. NullScrollbars.prototype.setScrollTop = function () {};
  3399. NullScrollbars.prototype.clear = function () {};
  3400. function updateScrollbars(cm, measure) {
  3401. if (!measure) { measure = measureForScrollbars(cm); }
  3402. var startWidth = cm.display.barWidth, startHeight = cm.display.barHeight;
  3403. updateScrollbarsInner(cm, measure);
  3404. for (var i = 0; i < 4 && startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i++) {
  3405. if (startWidth != cm.display.barWidth && cm.options.lineWrapping)
  3406. { updateHeightsInViewport(cm); }
  3407. updateScrollbarsInner(cm, measureForScrollbars(cm));
  3408. startWidth = cm.display.barWidth; startHeight = cm.display.barHeight;
  3409. }
  3410. }
  3411. // Re-synchronize the fake scrollbars with the actual size of the
  3412. // content.
  3413. function updateScrollbarsInner(cm, measure) {
  3414. var d = cm.display;
  3415. var sizes = d.scrollbars.update(measure);
  3416. d.sizer.style.paddingRight = (d.barWidth = sizes.right) + "px";
  3417. d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + "px";
  3418. d.heightForcer.style.borderBottom = sizes.bottom + "px solid transparent";
  3419. if (sizes.right && sizes.bottom) {
  3420. d.scrollbarFiller.style.display = "block";
  3421. d.scrollbarFiller.style.height = sizes.bottom + "px";
  3422. d.scrollbarFiller.style.width = sizes.right + "px";
  3423. } else { d.scrollbarFiller.style.display = ""; }
  3424. if (sizes.bottom && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) {
  3425. d.gutterFiller.style.display = "block";
  3426. d.gutterFiller.style.height = sizes.bottom + "px";
  3427. d.gutterFiller.style.width = measure.gutterWidth + "px";
  3428. } else { d.gutterFiller.style.display = ""; }
  3429. }
  3430. var scrollbarModel = {"native": NativeScrollbars, "null": NullScrollbars};
  3431. function initScrollbars(cm) {
  3432. if (cm.display.scrollbars) {
  3433. cm.display.scrollbars.clear();
  3434. if (cm.display.scrollbars.addClass)
  3435. { rmClass(cm.display.wrapper, cm.display.scrollbars.addClass); }
  3436. }
  3437. cm.display.scrollbars = new scrollbarModel[cm.options.scrollbarStyle](function (node) {
  3438. cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller);
  3439. // Prevent clicks in the scrollbars from killing focus
  3440. on(node, "mousedown", function () {
  3441. if (cm.state.focused) { setTimeout(function () { return cm.display.input.focus(); }, 0); }
  3442. });
  3443. node.setAttribute("cm-not-content", "true");
  3444. }, function (pos, axis) {
  3445. if (axis == "horizontal") { setScrollLeft(cm, pos); }
  3446. else { updateScrollTop(cm, pos); }
  3447. }, cm);
  3448. if (cm.display.scrollbars.addClass)
  3449. { addClass(cm.display.wrapper, cm.display.scrollbars.addClass); }
  3450. }
  3451. // Operations are used to wrap a series of changes to the editor
  3452. // state in such a way that each change won't have to update the
  3453. // cursor and display (which would be awkward, slow, and
  3454. // error-prone). Instead, display updates are batched and then all
  3455. // combined and executed at once.
  3456. var nextOpId = 0;
  3457. // Start a new operation.
  3458. function startOperation(cm) {
  3459. cm.curOp = {
  3460. cm: cm,
  3461. viewChanged: false, // Flag that indicates that lines might need to be redrawn
  3462. startHeight: cm.doc.height, // Used to detect need to update scrollbar
  3463. forceUpdate: false, // Used to force a redraw
  3464. updateInput: 0, // Whether to reset the input textarea
  3465. typing: false, // Whether this reset should be careful to leave existing text (for compositing)
  3466. changeObjs: null, // Accumulated changes, for firing change events
  3467. cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on
  3468. cursorActivityCalled: 0, // Tracks which cursorActivity handlers have been called already
  3469. selectionChanged: false, // Whether the selection needs to be redrawn
  3470. updateMaxLine: false, // Set when the widest line needs to be determined anew
  3471. scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet
  3472. scrollToPos: null, // Used to scroll to a specific position
  3473. focus: false,
  3474. id: ++nextOpId, // Unique ID
  3475. markArrays: null // Used by addMarkedSpan
  3476. };
  3477. pushOperation(cm.curOp);
  3478. }
  3479. // Finish an operation, updating the display and signalling delayed events
  3480. function endOperation(cm) {
  3481. var op = cm.curOp;
  3482. if (op) { finishOperation(op, function (group) {
  3483. for (var i = 0; i < group.ops.length; i++)
  3484. { group.ops[i].cm.curOp = null; }
  3485. endOperations(group);
  3486. }); }
  3487. }
  3488. // The DOM updates done when an operation finishes are batched so
  3489. // that the minimum number of relayouts are required.
  3490. function endOperations(group) {
  3491. var ops = group.ops;
  3492. for (var i = 0; i < ops.length; i++) // Read DOM
  3493. { endOperation_R1(ops[i]); }
  3494. for (var i$1 = 0; i$1 < ops.length; i$1++) // Write DOM (maybe)
  3495. { endOperation_W1(ops[i$1]); }
  3496. for (var i$2 = 0; i$2 < ops.length; i$2++) // Read DOM
  3497. { endOperation_R2(ops[i$2]); }
  3498. for (var i$3 = 0; i$3 < ops.length; i$3++) // Write DOM (maybe)
  3499. { endOperation_W2(ops[i$3]); }
  3500. for (var i$4 = 0; i$4 < ops.length; i$4++) // Read DOM
  3501. { endOperation_finish(ops[i$4]); }
  3502. }
  3503. function endOperation_R1(op) {
  3504. var cm = op.cm, display = cm.display;
  3505. maybeClipScrollbars(cm);
  3506. if (op.updateMaxLine) { findMaxLine(cm); }
  3507. op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null ||
  3508. op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom ||
  3509. op.scrollToPos.to.line >= display.viewTo) ||
  3510. display.maxLineChanged && cm.options.lineWrapping;
  3511. op.update = op.mustUpdate &&
  3512. new DisplayUpdate(cm, op.mustUpdate && {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate);
  3513. }
  3514. function endOperation_W1(op) {
  3515. op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update);
  3516. }
  3517. function endOperation_R2(op) {
  3518. var cm = op.cm, display = cm.display;
  3519. if (op.updatedDisplay) { updateHeightsInViewport(cm); }
  3520. op.barMeasure = measureForScrollbars(cm);
  3521. // If the max line changed since it was last measured, measure it,
  3522. // and ensure the document's width matches it.
  3523. // updateDisplay_W2 will use these properties to do the actual resizing
  3524. if (display.maxLineChanged && !cm.options.lineWrapping) {
  3525. op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3;
  3526. cm.display.sizerWidth = op.adjustWidthTo;
  3527. op.barMeasure.scrollWidth =
  3528. Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth);
  3529. op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm));
  3530. }
  3531. if (op.updatedDisplay || op.selectionChanged)
  3532. { op.preparedSelection = display.input.prepareSelection(); }
  3533. }
  3534. function endOperation_W2(op) {
  3535. var cm = op.cm;
  3536. if (op.adjustWidthTo != null) {
  3537. cm.display.sizer.style.minWidth = op.adjustWidthTo + "px";
  3538. if (op.maxScrollLeft < cm.doc.scrollLeft)
  3539. { setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true); }
  3540. cm.display.maxLineChanged = false;
  3541. }
  3542. var takeFocus = op.focus && op.focus == activeElt();
  3543. if (op.preparedSelection)
  3544. { cm.display.input.showSelection(op.preparedSelection, takeFocus); }
  3545. if (op.updatedDisplay || op.startHeight != cm.doc.height)
  3546. { updateScrollbars(cm, op.barMeasure); }
  3547. if (op.updatedDisplay)
  3548. { setDocumentHeight(cm, op.barMeasure); }
  3549. if (op.selectionChanged) { restartBlink(cm); }
  3550. if (cm.state.focused && op.updateInput)
  3551. { cm.display.input.reset(op.typing); }
  3552. if (takeFocus) { ensureFocus(op.cm); }
  3553. }
  3554. function endOperation_finish(op) {
  3555. var cm = op.cm, display = cm.display, doc = cm.doc;
  3556. if (op.updatedDisplay) { postUpdateDisplay(cm, op.update); }
  3557. // Abort mouse wheel delta measurement, when scrolling explicitly
  3558. if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos))
  3559. { display.wheelStartX = display.wheelStartY = null; }
  3560. // Propagate the scroll position to the actual DOM scroller
  3561. if (op.scrollTop != null) { setScrollTop(cm, op.scrollTop, op.forceScroll); }
  3562. if (op.scrollLeft != null) { setScrollLeft(cm, op.scrollLeft, true, true); }
  3563. // If we need to scroll a specific position into view, do so.
  3564. if (op.scrollToPos) {
  3565. var rect = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from),
  3566. clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin);
  3567. maybeScrollWindow(cm, rect);
  3568. }
  3569. // Fire events for markers that are hidden/unidden by editing or
  3570. // undoing
  3571. var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers;
  3572. if (hidden) { for (var i = 0; i < hidden.length; ++i)
  3573. { if (!hidden[i].lines.length) { signal(hidden[i], "hide"); } } }
  3574. if (unhidden) { for (var i$1 = 0; i$1 < unhidden.length; ++i$1)
  3575. { if (unhidden[i$1].lines.length) { signal(unhidden[i$1], "unhide"); } } }
  3576. if (display.wrapper.offsetHeight)
  3577. { doc.scrollTop = cm.display.scroller.scrollTop; }
  3578. // Fire change events, and delayed event handlers
  3579. if (op.changeObjs)
  3580. { signal(cm, "changes", cm, op.changeObjs); }
  3581. if (op.update)
  3582. { op.update.finish(); }
  3583. }
  3584. // Run the given function in an operation
  3585. function runInOp(cm, f) {
  3586. if (cm.curOp) { return f() }
  3587. startOperation(cm);
  3588. try { return f() }
  3589. finally { endOperation(cm); }
  3590. }
  3591. // Wraps a function in an operation. Returns the wrapped function.
  3592. function operation(cm, f) {
  3593. return function() {
  3594. if (cm.curOp) { return f.apply(cm, arguments) }
  3595. startOperation(cm);
  3596. try { return f.apply(cm, arguments) }
  3597. finally { endOperation(cm); }
  3598. }
  3599. }
  3600. // Used to add methods to editor and doc instances, wrapping them in
  3601. // operations.
  3602. function methodOp(f) {
  3603. return function() {
  3604. if (this.curOp) { return f.apply(this, arguments) }
  3605. startOperation(this);
  3606. try { return f.apply(this, arguments) }
  3607. finally { endOperation(this); }
  3608. }
  3609. }
  3610. function docMethodOp(f) {
  3611. return function() {
  3612. var cm = this.cm;
  3613. if (!cm || cm.curOp) { return f.apply(this, arguments) }
  3614. startOperation(cm);
  3615. try { return f.apply(this, arguments) }
  3616. finally { endOperation(cm); }
  3617. }
  3618. }
  3619. // HIGHLIGHT WORKER
  3620. function startWorker(cm, time) {
  3621. if (cm.doc.highlightFrontier < cm.display.viewTo)
  3622. { cm.state.highlight.set(time, bind(highlightWorker, cm)); }
  3623. }
  3624. function highlightWorker(cm) {
  3625. var doc = cm.doc;
  3626. if (doc.highlightFrontier >= cm.display.viewTo) { return }
  3627. var end = +new Date + cm.options.workTime;
  3628. var context = getContextBefore(cm, doc.highlightFrontier);
  3629. var changedLines = [];
  3630. doc.iter(context.line, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function (line) {
  3631. if (context.line >= cm.display.viewFrom) { // Visible
  3632. var oldStyles = line.styles;
  3633. var resetState = line.text.length > cm.options.maxHighlightLength ? copyState(doc.mode, context.state) : null;
  3634. var highlighted = highlightLine(cm, line, context, true);
  3635. if (resetState) { context.state = resetState; }
  3636. line.styles = highlighted.styles;
  3637. var oldCls = line.styleClasses, newCls = highlighted.classes;
  3638. if (newCls) { line.styleClasses = newCls; }
  3639. else if (oldCls) { line.styleClasses = null; }
  3640. var ischange = !oldStyles || oldStyles.length != line.styles.length ||
  3641. oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass);
  3642. for (var i = 0; !ischange && i < oldStyles.length; ++i) { ischange = oldStyles[i] != line.styles[i]; }
  3643. if (ischange) { changedLines.push(context.line); }
  3644. line.stateAfter = context.save();
  3645. context.nextLine();
  3646. } else {
  3647. if (line.text.length <= cm.options.maxHighlightLength)
  3648. { processLine(cm, line.text, context); }
  3649. line.stateAfter = context.line % 5 == 0 ? context.save() : null;
  3650. context.nextLine();
  3651. }
  3652. if (+new Date > end) {
  3653. startWorker(cm, cm.options.workDelay);
  3654. return true
  3655. }
  3656. });
  3657. doc.highlightFrontier = context.line;
  3658. doc.modeFrontier = Math.max(doc.modeFrontier, context.line);
  3659. if (changedLines.length) { runInOp(cm, function () {
  3660. for (var i = 0; i < changedLines.length; i++)
  3661. { regLineChange(cm, changedLines[i], "text"); }
  3662. }); }
  3663. }
  3664. // DISPLAY DRAWING
  3665. var DisplayUpdate = function(cm, viewport, force) {
  3666. var display = cm.display;
  3667. this.viewport = viewport;
  3668. // Store some values that we'll need later (but don't want to force a relayout for)
  3669. this.visible = visibleLines(display, cm.doc, viewport);
  3670. this.editorIsHidden = !display.wrapper.offsetWidth;
  3671. this.wrapperHeight = display.wrapper.clientHeight;
  3672. this.wrapperWidth = display.wrapper.clientWidth;
  3673. this.oldDisplayWidth = displayWidth(cm);
  3674. this.force = force;
  3675. this.dims = getDimensions(cm);
  3676. this.events = [];
  3677. };
  3678. DisplayUpdate.prototype.signal = function (emitter, type) {
  3679. if (hasHandler(emitter, type))
  3680. { this.events.push(arguments); }
  3681. };
  3682. DisplayUpdate.prototype.finish = function () {
  3683. for (var i = 0; i < this.events.length; i++)
  3684. { signal.apply(null, this.events[i]); }
  3685. };
  3686. function maybeClipScrollbars(cm) {
  3687. var display = cm.display;
  3688. if (!display.scrollbarsClipped && display.scroller.offsetWidth) {
  3689. display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth;
  3690. display.heightForcer.style.height = scrollGap(cm) + "px";
  3691. display.sizer.style.marginBottom = -display.nativeBarWidth + "px";
  3692. display.sizer.style.borderRightWidth = scrollGap(cm) + "px";
  3693. display.scrollbarsClipped = true;
  3694. }
  3695. }
  3696. function selectionSnapshot(cm) {
  3697. if (cm.hasFocus()) { return null }
  3698. var active = activeElt();
  3699. if (!active || !contains(cm.display.lineDiv, active)) { return null }
  3700. var result = {activeElt: active};
  3701. if (window.getSelection) {
  3702. var sel = window.getSelection();
  3703. if (sel.anchorNode && sel.extend && contains(cm.display.lineDiv, sel.anchorNode)) {
  3704. result.anchorNode = sel.anchorNode;
  3705. result.anchorOffset = sel.anchorOffset;
  3706. result.focusNode = sel.focusNode;
  3707. result.focusOffset = sel.focusOffset;
  3708. }
  3709. }
  3710. return result
  3711. }
  3712. function restoreSelection(snapshot) {
  3713. if (!snapshot || !snapshot.activeElt || snapshot.activeElt == activeElt()) { return }
  3714. snapshot.activeElt.focus();
  3715. if (!/^(INPUT|TEXTAREA)$/.test(snapshot.activeElt.nodeName) &&
  3716. snapshot.anchorNode && contains(document.body, snapshot.anchorNode) && contains(document.body, snapshot.focusNode)) {
  3717. var sel = window.getSelection(), range = document.createRange();
  3718. range.setEnd(snapshot.anchorNode, snapshot.anchorOffset);
  3719. range.collapse(false);
  3720. sel.removeAllRanges();
  3721. sel.addRange(range);
  3722. sel.extend(snapshot.focusNode, snapshot.focusOffset);
  3723. }
  3724. }
  3725. // Does the actual updating of the line display. Bails out
  3726. // (returning false) when there is nothing to be done and forced is
  3727. // false.
  3728. function updateDisplayIfNeeded(cm, update) {
  3729. var display = cm.display, doc = cm.doc;
  3730. if (update.editorIsHidden) {
  3731. resetView(cm);
  3732. return false
  3733. }
  3734. // Bail out if the visible area is already rendered and nothing changed.
  3735. if (!update.force &&
  3736. update.visible.from >= display.viewFrom && update.visible.to <= display.viewTo &&
  3737. (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) &&
  3738. display.renderedView == display.view && countDirtyView(cm) == 0)
  3739. { return false }
  3740. if (maybeUpdateLineNumberWidth(cm)) {
  3741. resetView(cm);
  3742. update.dims = getDimensions(cm);
  3743. }
  3744. // Compute a suitable new viewport (from & to)
  3745. var end = doc.first + doc.size;
  3746. var from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first);
  3747. var to = Math.min(end, update.visible.to + cm.options.viewportMargin);
  3748. if (display.viewFrom < from && from - display.viewFrom < 20) { from = Math.max(doc.first, display.viewFrom); }
  3749. if (display.viewTo > to && display.viewTo - to < 20) { to = Math.min(end, display.viewTo); }
  3750. if (sawCollapsedSpans) {
  3751. from = visualLineNo(cm.doc, from);
  3752. to = visualLineEndNo(cm.doc, to);
  3753. }
  3754. var different = from != display.viewFrom || to != display.viewTo ||
  3755. display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth;
  3756. adjustView(cm, from, to);
  3757. display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom));
  3758. // Position the mover div to align with the current scroll position
  3759. cm.display.mover.style.top = display.viewOffset + "px";
  3760. var toUpdate = countDirtyView(cm);
  3761. if (!different && toUpdate == 0 && !update.force && display.renderedView == display.view &&
  3762. (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo))
  3763. { return false }
  3764. // For big changes, we hide the enclosing element during the
  3765. // update, since that speeds up the operations on most browsers.
  3766. var selSnapshot = selectionSnapshot(cm);
  3767. if (toUpdate > 4) { display.lineDiv.style.display = "none"; }
  3768. patchDisplay(cm, display.updateLineNumbers, update.dims);
  3769. if (toUpdate > 4) { display.lineDiv.style.display = ""; }
  3770. display.renderedView = display.view;
  3771. // There might have been a widget with a focused element that got
  3772. // hidden or updated, if so re-focus it.
  3773. restoreSelection(selSnapshot);
  3774. // Prevent selection and cursors from interfering with the scroll
  3775. // width and height.
  3776. removeChildren(display.cursorDiv);
  3777. removeChildren(display.selectionDiv);
  3778. display.gutters.style.height = display.sizer.style.minHeight = 0;
  3779. if (different) {
  3780. display.lastWrapHeight = update.wrapperHeight;
  3781. display.lastWrapWidth = update.wrapperWidth;
  3782. startWorker(cm, 400);
  3783. }
  3784. display.updateLineNumbers = null;
  3785. return true
  3786. }
  3787. function postUpdateDisplay(cm, update) {
  3788. var viewport = update.viewport;
  3789. for (var first = true;; first = false) {
  3790. if (!first || !cm.options.lineWrapping || update.oldDisplayWidth == displayWidth(cm)) {
  3791. // Clip forced viewport to actual scrollable area.
  3792. if (viewport && viewport.top != null)
  3793. { viewport = {top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top)}; }
  3794. // Updated line heights might result in the drawn area not
  3795. // actually covering the viewport. Keep looping until it does.
  3796. update.visible = visibleLines(cm.display, cm.doc, viewport);
  3797. if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo)
  3798. { break }
  3799. } else if (first) {
  3800. update.visible = visibleLines(cm.display, cm.doc, viewport);
  3801. }
  3802. if (!updateDisplayIfNeeded(cm, update)) { break }
  3803. updateHeightsInViewport(cm);
  3804. var barMeasure = measureForScrollbars(cm);
  3805. updateSelection(cm);
  3806. updateScrollbars(cm, barMeasure);
  3807. setDocumentHeight(cm, barMeasure);
  3808. update.force = false;
  3809. }
  3810. update.signal(cm, "update", cm);
  3811. if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) {
  3812. update.signal(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo);
  3813. cm.display.reportedViewFrom = cm.display.viewFrom; cm.display.reportedViewTo = cm.display.viewTo;
  3814. }
  3815. }
  3816. function updateDisplaySimple(cm, viewport) {
  3817. var update = new DisplayUpdate(cm, viewport);
  3818. if (updateDisplayIfNeeded(cm, update)) {
  3819. updateHeightsInViewport(cm);
  3820. postUpdateDisplay(cm, update);
  3821. var barMeasure = measureForScrollbars(cm);
  3822. updateSelection(cm);
  3823. updateScrollbars(cm, barMeasure);
  3824. setDocumentHeight(cm, barMeasure);
  3825. update.finish();
  3826. }
  3827. }
  3828. // Sync the actual display DOM structure with display.view, removing
  3829. // nodes for lines that are no longer in view, and creating the ones
  3830. // that are not there yet, and updating the ones that are out of
  3831. // date.
  3832. function patchDisplay(cm, updateNumbersFrom, dims) {
  3833. var display = cm.display, lineNumbers = cm.options.lineNumbers;
  3834. var container = display.lineDiv, cur = container.firstChild;
  3835. function rm(node) {
  3836. var next = node.nextSibling;
  3837. // Works around a throw-scroll bug in OS X Webkit
  3838. if (webkit && mac && cm.display.currentWheelTarget == node)
  3839. { node.style.display = "none"; }
  3840. else
  3841. { node.parentNode.removeChild(node); }
  3842. return next
  3843. }
  3844. var view = display.view, lineN = display.viewFrom;
  3845. // Loop over the elements in the view, syncing cur (the DOM nodes
  3846. // in display.lineDiv) with the view as we go.
  3847. for (var i = 0; i < view.length; i++) {
  3848. var lineView = view[i];
  3849. if (lineView.hidden) ; else if (!lineView.node || lineView.node.parentNode != container) { // Not drawn yet
  3850. var node = buildLineElement(cm, lineView, lineN, dims);
  3851. container.insertBefore(node, cur);
  3852. } else { // Already drawn
  3853. while (cur != lineView.node) { cur = rm(cur); }
  3854. var updateNumber = lineNumbers && updateNumbersFrom != null &&
  3855. updateNumbersFrom <= lineN && lineView.lineNumber;
  3856. if (lineView.changes) {
  3857. if (indexOf(lineView.changes, "gutter") > -1) { updateNumber = false; }
  3858. updateLineForChanges(cm, lineView, lineN, dims);
  3859. }
  3860. if (updateNumber) {
  3861. removeChildren(lineView.lineNumber);
  3862. lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN)));
  3863. }
  3864. cur = lineView.node.nextSibling;
  3865. }
  3866. lineN += lineView.size;
  3867. }
  3868. while (cur) { cur = rm(cur); }
  3869. }
  3870. function updateGutterSpace(display) {
  3871. var width = display.gutters.offsetWidth;
  3872. display.sizer.style.marginLeft = width + "px";
  3873. // Send an event to consumers responding to changes in gutter width.
  3874. signalLater(display, "gutterChanged", display);
  3875. }
  3876. function setDocumentHeight(cm, measure) {
  3877. cm.display.sizer.style.minHeight = measure.docHeight + "px";
  3878. cm.display.heightForcer.style.top = measure.docHeight + "px";
  3879. cm.display.gutters.style.height = (measure.docHeight + cm.display.barHeight + scrollGap(cm)) + "px";
  3880. }
  3881. // Re-align line numbers and gutter marks to compensate for
  3882. // horizontal scrolling.
  3883. function alignHorizontally(cm) {
  3884. var display = cm.display, view = display.view;
  3885. if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) { return }
  3886. var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft;
  3887. var gutterW = display.gutters.offsetWidth, left = comp + "px";
  3888. for (var i = 0; i < view.length; i++) { if (!view[i].hidden) {
  3889. if (cm.options.fixedGutter) {
  3890. if (view[i].gutter)
  3891. { view[i].gutter.style.left = left; }
  3892. if (view[i].gutterBackground)
  3893. { view[i].gutterBackground.style.left = left; }
  3894. }
  3895. var align = view[i].alignable;
  3896. if (align) { for (var j = 0; j < align.length; j++)
  3897. { align[j].style.left = left; } }
  3898. } }
  3899. if (cm.options.fixedGutter)
  3900. { display.gutters.style.left = (comp + gutterW) + "px"; }
  3901. }
  3902. // Used to ensure that the line number gutter is still the right
  3903. // size for the current document size. Returns true when an update
  3904. // is needed.
  3905. function maybeUpdateLineNumberWidth(cm) {
  3906. if (!cm.options.lineNumbers) { return false }
  3907. var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display;
  3908. if (last.length != display.lineNumChars) {
  3909. var test = display.measure.appendChild(elt("div", [elt("div", last)],
  3910. "CodeMirror-linenumber CodeMirror-gutter-elt"));
  3911. var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW;
  3912. display.lineGutter.style.width = "";
  3913. display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding) + 1;
  3914. display.lineNumWidth = display.lineNumInnerWidth + padding;
  3915. display.lineNumChars = display.lineNumInnerWidth ? last.length : -1;
  3916. display.lineGutter.style.width = display.lineNumWidth + "px";
  3917. updateGutterSpace(cm.display);
  3918. return true
  3919. }
  3920. return false
  3921. }
  3922. function getGutters(gutters, lineNumbers) {
  3923. var result = [], sawLineNumbers = false;
  3924. for (var i = 0; i < gutters.length; i++) {
  3925. var name = gutters[i], style = null;
  3926. if (typeof name != "string") { style = name.style; name = name.className; }
  3927. if (name == "CodeMirror-linenumbers") {
  3928. if (!lineNumbers) { continue }
  3929. else { sawLineNumbers = true; }
  3930. }
  3931. result.push({className: name, style: style});
  3932. }
  3933. if (lineNumbers && !sawLineNumbers) { result.push({className: "CodeMirror-linenumbers", style: null}); }
  3934. return result
  3935. }
  3936. // Rebuild the gutter elements, ensure the margin to the left of the
  3937. // code matches their width.
  3938. function renderGutters(display) {
  3939. var gutters = display.gutters, specs = display.gutterSpecs;
  3940. removeChildren(gutters);
  3941. display.lineGutter = null;
  3942. for (var i = 0; i < specs.length; ++i) {
  3943. var ref = specs[i];
  3944. var className = ref.className;
  3945. var style = ref.style;
  3946. var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + className));
  3947. if (style) { gElt.style.cssText = style; }
  3948. if (className == "CodeMirror-linenumbers") {
  3949. display.lineGutter = gElt;
  3950. gElt.style.width = (display.lineNumWidth || 1) + "px";
  3951. }
  3952. }
  3953. gutters.style.display = specs.length ? "" : "none";
  3954. updateGutterSpace(display);
  3955. }
  3956. function updateGutters(cm) {
  3957. renderGutters(cm.display);
  3958. regChange(cm);
  3959. alignHorizontally(cm);
  3960. }
  3961. // The display handles the DOM integration, both for input reading
  3962. // and content drawing. It holds references to DOM nodes and
  3963. // display-related state.
  3964. function Display(place, doc, input, options) {
  3965. var d = this;
  3966. this.input = input;
  3967. // Covers bottom-right square when both scrollbars are present.
  3968. d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler");
  3969. d.scrollbarFiller.setAttribute("cm-not-content", "true");
  3970. // Covers bottom of gutter when coverGutterNextToScrollbar is on
  3971. // and h scrollbar is present.
  3972. d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler");
  3973. d.gutterFiller.setAttribute("cm-not-content", "true");
  3974. // Will contain the actual code, positioned to cover the viewport.
  3975. d.lineDiv = eltP("div", null, "CodeMirror-code");
  3976. // Elements are added to these to represent selection and cursors.
  3977. d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1");
  3978. d.cursorDiv = elt("div", null, "CodeMirror-cursors");
  3979. // A visibility: hidden element used to find the size of things.
  3980. d.measure = elt("div", null, "CodeMirror-measure");
  3981. // When lines outside of the viewport are measured, they are drawn in this.
  3982. d.lineMeasure = elt("div", null, "CodeMirror-measure");
  3983. // Wraps everything that needs to exist inside the vertically-padded coordinate system
  3984. d.lineSpace = eltP("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv],
  3985. null, "position: relative; outline: none");
  3986. var lines = eltP("div", [d.lineSpace], "CodeMirror-lines");
  3987. // Moved around its parent to cover visible view.
  3988. d.mover = elt("div", [lines], null, "position: relative");
  3989. // Set to the height of the document, allowing scrolling.
  3990. d.sizer = elt("div", [d.mover], "CodeMirror-sizer");
  3991. d.sizerWidth = null;
  3992. // Behavior of elts with overflow: auto and padding is
  3993. // inconsistent across browsers. This is used to ensure the
  3994. // scrollable area is big enough.
  3995. d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerGap + "px; width: 1px;");
  3996. // Will contain the gutters, if any.
  3997. d.gutters = elt("div", null, "CodeMirror-gutters");
  3998. d.lineGutter = null;
  3999. // Actual scrollable element.
  4000. d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll");
  4001. d.scroller.setAttribute("tabIndex", "-1");
  4002. // The element in which the editor lives.
  4003. d.wrapper = elt("div", [d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror");
  4004. // This attribute is respected by automatic translation systems such as Google Translate,
  4005. // and may also be respected by tools used by human translators.
  4006. d.wrapper.setAttribute('translate', 'no');
  4007. // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported)
  4008. if (ie && ie_version < 8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; }
  4009. if (!webkit && !(gecko && mobile)) { d.scroller.draggable = true; }
  4010. if (place) {
  4011. if (place.appendChild) { place.appendChild(d.wrapper); }
  4012. else { place(d.wrapper); }
  4013. }
  4014. // Current rendered range (may be bigger than the view window).
  4015. d.viewFrom = d.viewTo = doc.first;
  4016. d.reportedViewFrom = d.reportedViewTo = doc.first;
  4017. // Information about the rendered lines.
  4018. d.view = [];
  4019. d.renderedView = null;
  4020. // Holds info about a single rendered line when it was rendered
  4021. // for measurement, while not in view.
  4022. d.externalMeasured = null;
  4023. // Empty space (in pixels) above the view
  4024. d.viewOffset = 0;
  4025. d.lastWrapHeight = d.lastWrapWidth = 0;
  4026. d.updateLineNumbers = null;
  4027. d.nativeBarWidth = d.barHeight = d.barWidth = 0;
  4028. d.scrollbarsClipped = false;
  4029. // Used to only resize the line number gutter when necessary (when
  4030. // the amount of lines crosses a boundary that makes its width change)
  4031. d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null;
  4032. // Set to true when a non-horizontal-scrolling line widget is
  4033. // added. As an optimization, line widget aligning is skipped when
  4034. // this is false.
  4035. d.alignWidgets = false;
  4036. d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
  4037. // Tracks the maximum line length so that the horizontal scrollbar
  4038. // can be kept static when scrolling.
  4039. d.maxLine = null;
  4040. d.maxLineLength = 0;
  4041. d.maxLineChanged = false;
  4042. // Used for measuring wheel scrolling granularity
  4043. d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null;
  4044. // True when shift is held down.
  4045. d.shift = false;
  4046. // Used to track whether anything happened since the context menu
  4047. // was opened.
  4048. d.selForContextMenu = null;
  4049. d.activeTouch = null;
  4050. d.gutterSpecs = getGutters(options.gutters, options.lineNumbers);
  4051. renderGutters(d);
  4052. input.init(d);
  4053. }
  4054. // Since the delta values reported on mouse wheel events are
  4055. // unstandardized between browsers and even browser versions, and
  4056. // generally horribly unpredictable, this code starts by measuring
  4057. // the scroll effect that the first few mouse wheel events have,
  4058. // and, from that, detects the way it can convert deltas to pixel
  4059. // offsets afterwards.
  4060. //
  4061. // The reason we want to know the amount a wheel event will scroll
  4062. // is that it gives us a chance to update the display before the
  4063. // actual scrolling happens, reducing flickering.
  4064. var wheelSamples = 0, wheelPixelsPerUnit = null;
  4065. // Fill in a browser-detected starting value on browsers where we
  4066. // know one. These don't have to be accurate -- the result of them
  4067. // being wrong would just be a slight flicker on the first wheel
  4068. // scroll (if it is large enough).
  4069. if (ie) { wheelPixelsPerUnit = -.53; }
  4070. else if (gecko) { wheelPixelsPerUnit = 15; }
  4071. else if (chrome) { wheelPixelsPerUnit = -.7; }
  4072. else if (safari) { wheelPixelsPerUnit = -1/3; }
  4073. function wheelEventDelta(e) {
  4074. var dx = e.wheelDeltaX, dy = e.wheelDeltaY;
  4075. if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) { dx = e.detail; }
  4076. if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) { dy = e.detail; }
  4077. else if (dy == null) { dy = e.wheelDelta; }
  4078. return {x: dx, y: dy}
  4079. }
  4080. function wheelEventPixels(e) {
  4081. var delta = wheelEventDelta(e);
  4082. delta.x *= wheelPixelsPerUnit;
  4083. delta.y *= wheelPixelsPerUnit;
  4084. return delta
  4085. }
  4086. function onScrollWheel(cm, e) {
  4087. var delta = wheelEventDelta(e), dx = delta.x, dy = delta.y;
  4088. var pixelsPerUnit = wheelPixelsPerUnit;
  4089. if (e.deltaMode === 0) {
  4090. dx = e.deltaX;
  4091. dy = e.deltaY;
  4092. pixelsPerUnit = 1;
  4093. }
  4094. var display = cm.display, scroll = display.scroller;
  4095. // Quit if there's nothing to scroll here
  4096. var canScrollX = scroll.scrollWidth > scroll.clientWidth;
  4097. var canScrollY = scroll.scrollHeight > scroll.clientHeight;
  4098. if (!(dx && canScrollX || dy && canScrollY)) { return }
  4099. // Webkit browsers on OS X abort momentum scrolls when the target
  4100. // of the scroll event is removed from the scrollable element.
  4101. // This hack (see related code in patchDisplay) makes sure the
  4102. // element is kept around.
  4103. if (dy && mac && webkit) {
  4104. outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) {
  4105. for (var i = 0; i < view.length; i++) {
  4106. if (view[i].node == cur) {
  4107. cm.display.currentWheelTarget = cur;
  4108. break outer
  4109. }
  4110. }
  4111. }
  4112. }
  4113. // On some browsers, horizontal scrolling will cause redraws to
  4114. // happen before the gutter has been realigned, causing it to
  4115. // wriggle around in a most unseemly way. When we have an
  4116. // estimated pixels/delta value, we just handle horizontal
  4117. // scrolling entirely here. It'll be slightly off from native, but
  4118. // better than glitching out.
  4119. if (dx && !gecko && !presto && pixelsPerUnit != null) {
  4120. if (dy && canScrollY)
  4121. { updateScrollTop(cm, Math.max(0, scroll.scrollTop + dy * pixelsPerUnit)); }
  4122. setScrollLeft(cm, Math.max(0, scroll.scrollLeft + dx * pixelsPerUnit));
  4123. // Only prevent default scrolling if vertical scrolling is
  4124. // actually possible. Otherwise, it causes vertical scroll
  4125. // jitter on OSX trackpads when deltaX is small and deltaY
  4126. // is large (issue #3579)
  4127. if (!dy || (dy && canScrollY))
  4128. { e_preventDefault(e); }
  4129. display.wheelStartX = null; // Abort measurement, if in progress
  4130. return
  4131. }
  4132. // 'Project' the visible viewport to cover the area that is being
  4133. // scrolled into view (if we know enough to estimate it).
  4134. if (dy && pixelsPerUnit != null) {
  4135. var pixels = dy * pixelsPerUnit;
  4136. var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight;
  4137. if (pixels < 0) { top = Math.max(0, top + pixels - 50); }
  4138. else { bot = Math.min(cm.doc.height, bot + pixels + 50); }
  4139. updateDisplaySimple(cm, {top: top, bottom: bot});
  4140. }
  4141. if (wheelSamples < 20 && e.deltaMode !== 0) {
  4142. if (display.wheelStartX == null) {
  4143. display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop;
  4144. display.wheelDX = dx; display.wheelDY = dy;
  4145. setTimeout(function () {
  4146. if (display.wheelStartX == null) { return }
  4147. var movedX = scroll.scrollLeft - display.wheelStartX;
  4148. var movedY = scroll.scrollTop - display.wheelStartY;
  4149. var sample = (movedY && display.wheelDY && movedY / display.wheelDY) ||
  4150. (movedX && display.wheelDX && movedX / display.wheelDX);
  4151. display.wheelStartX = display.wheelStartY = null;
  4152. if (!sample) { return }
  4153. wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1);
  4154. ++wheelSamples;
  4155. }, 200);
  4156. } else {
  4157. display.wheelDX += dx; display.wheelDY += dy;
  4158. }
  4159. }
  4160. }
  4161. // Selection objects are immutable. A new one is created every time
  4162. // the selection changes. A selection is one or more non-overlapping
  4163. // (and non-touching) ranges, sorted, and an integer that indicates
  4164. // which one is the primary selection (the one that's scrolled into
  4165. // view, that getCursor returns, etc).
  4166. var Selection = function(ranges, primIndex) {
  4167. this.ranges = ranges;
  4168. this.primIndex = primIndex;
  4169. };
  4170. Selection.prototype.primary = function () { return this.ranges[this.primIndex] };
  4171. Selection.prototype.equals = function (other) {
  4172. if (other == this) { return true }
  4173. if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) { return false }
  4174. for (var i = 0; i < this.ranges.length; i++) {
  4175. var here = this.ranges[i], there = other.ranges[i];
  4176. if (!equalCursorPos(here.anchor, there.anchor) || !equalCursorPos(here.head, there.head)) { return false }
  4177. }
  4178. return true
  4179. };
  4180. Selection.prototype.deepCopy = function () {
  4181. var out = [];
  4182. for (var i = 0; i < this.ranges.length; i++)
  4183. { out[i] = new Range(copyPos(this.ranges[i].anchor), copyPos(this.ranges[i].head)); }
  4184. return new Selection(out, this.primIndex)
  4185. };
  4186. Selection.prototype.somethingSelected = function () {
  4187. for (var i = 0; i < this.ranges.length; i++)
  4188. { if (!this.ranges[i].empty()) { return true } }
  4189. return false
  4190. };
  4191. Selection.prototype.contains = function (pos, end) {
  4192. if (!end) { end = pos; }
  4193. for (var i = 0; i < this.ranges.length; i++) {
  4194. var range = this.ranges[i];
  4195. if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0)
  4196. { return i }
  4197. }
  4198. return -1
  4199. };
  4200. var Range = function(anchor, head) {
  4201. this.anchor = anchor; this.head = head;
  4202. };
  4203. Range.prototype.from = function () { return minPos(this.anchor, this.head) };
  4204. Range.prototype.to = function () { return maxPos(this.anchor, this.head) };
  4205. Range.prototype.empty = function () { return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch };
  4206. // Take an unsorted, potentially overlapping set of ranges, and
  4207. // build a selection out of it. 'Consumes' ranges array (modifying
  4208. // it).
  4209. function normalizeSelection(cm, ranges, primIndex) {
  4210. var mayTouch = cm && cm.options.selectionsMayTouch;
  4211. var prim = ranges[primIndex];
  4212. ranges.sort(function (a, b) { return cmp(a.from(), b.from()); });
  4213. primIndex = indexOf(ranges, prim);
  4214. for (var i = 1; i < ranges.length; i++) {
  4215. var cur = ranges[i], prev = ranges[i - 1];
  4216. var diff = cmp(prev.to(), cur.from());
  4217. if (mayTouch && !cur.empty() ? diff > 0 : diff >= 0) {
  4218. var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to());
  4219. var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head;
  4220. if (i <= primIndex) { --primIndex; }
  4221. ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to));
  4222. }
  4223. }
  4224. return new Selection(ranges, primIndex)
  4225. }
  4226. function simpleSelection(anchor, head) {
  4227. return new Selection([new Range(anchor, head || anchor)], 0)
  4228. }
  4229. // Compute the position of the end of a change (its 'to' property
  4230. // refers to the pre-change end).
  4231. function changeEnd(change) {
  4232. if (!change.text) { return change.to }
  4233. return Pos(change.from.line + change.text.length - 1,
  4234. lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0))
  4235. }
  4236. // Adjust a position to refer to the post-change position of the
  4237. // same text, or the end of the change if the change covers it.
  4238. function adjustForChange(pos, change) {
  4239. if (cmp(pos, change.from) < 0) { return pos }
  4240. if (cmp(pos, change.to) <= 0) { return changeEnd(change) }
  4241. var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch;
  4242. if (pos.line == change.to.line) { ch += changeEnd(change).ch - change.to.ch; }
  4243. return Pos(line, ch)
  4244. }
  4245. function computeSelAfterChange(doc, change) {
  4246. var out = [];
  4247. for (var i = 0; i < doc.sel.ranges.length; i++) {
  4248. var range = doc.sel.ranges[i];
  4249. out.push(new Range(adjustForChange(range.anchor, change),
  4250. adjustForChange(range.head, change)));
  4251. }
  4252. return normalizeSelection(doc.cm, out, doc.sel.primIndex)
  4253. }
  4254. function offsetPos(pos, old, nw) {
  4255. if (pos.line == old.line)
  4256. { return Pos(nw.line, pos.ch - old.ch + nw.ch) }
  4257. else
  4258. { return Pos(nw.line + (pos.line - old.line), pos.ch) }
  4259. }
  4260. // Used by replaceSelections to allow moving the selection to the
  4261. // start or around the replaced test. Hint may be "start" or "around".
  4262. function computeReplacedSel(doc, changes, hint) {
  4263. var out = [];
  4264. var oldPrev = Pos(doc.first, 0), newPrev = oldPrev;
  4265. for (var i = 0; i < changes.length; i++) {
  4266. var change = changes[i];
  4267. var from = offsetPos(change.from, oldPrev, newPrev);
  4268. var to = offsetPos(changeEnd(change), oldPrev, newPrev);
  4269. oldPrev = change.to;
  4270. newPrev = to;
  4271. if (hint == "around") {
  4272. var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) < 0;
  4273. out[i] = new Range(inv ? to : from, inv ? from : to);
  4274. } else {
  4275. out[i] = new Range(from, from);
  4276. }
  4277. }
  4278. return new Selection(out, doc.sel.primIndex)
  4279. }
  4280. // Used to get the editor into a consistent state again when options change.
  4281. function loadMode(cm) {
  4282. cm.doc.mode = getMode(cm.options, cm.doc.modeOption);
  4283. resetModeState(cm);
  4284. }
  4285. function resetModeState(cm) {
  4286. cm.doc.iter(function (line) {
  4287. if (line.stateAfter) { line.stateAfter = null; }
  4288. if (line.styles) { line.styles = null; }
  4289. });
  4290. cm.doc.modeFrontier = cm.doc.highlightFrontier = cm.doc.first;
  4291. startWorker(cm, 100);
  4292. cm.state.modeGen++;
  4293. if (cm.curOp) { regChange(cm); }
  4294. }
  4295. // DOCUMENT DATA STRUCTURE
  4296. // By default, updates that start and end at the beginning of a line
  4297. // are treated specially, in order to make the association of line
  4298. // widgets and marker elements with the text behave more intuitive.
  4299. function isWholeLineUpdate(doc, change) {
  4300. return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" &&
  4301. (!doc.cm || doc.cm.options.wholeLineUpdateBefore)
  4302. }
  4303. // Perform a change on the document data structure.
  4304. function updateDoc(doc, change, markedSpans, estimateHeight) {
  4305. function spansFor(n) {return markedSpans ? markedSpans[n] : null}
  4306. function update(line, text, spans) {
  4307. updateLine(line, text, spans, estimateHeight);
  4308. signalLater(line, "change", line, change);
  4309. }
  4310. function linesFor(start, end) {
  4311. var result = [];
  4312. for (var i = start; i < end; ++i)
  4313. { result.push(new Line(text[i], spansFor(i), estimateHeight)); }
  4314. return result
  4315. }
  4316. var from = change.from, to = change.to, text = change.text;
  4317. var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line);
  4318. var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line;
  4319. // Adjust the line structure
  4320. if (change.full) {
  4321. doc.insert(0, linesFor(0, text.length));
  4322. doc.remove(text.length, doc.size - text.length);
  4323. } else if (isWholeLineUpdate(doc, change)) {
  4324. // This is a whole-line replace. Treated specially to make
  4325. // sure line objects move the way they are supposed to.
  4326. var added = linesFor(0, text.length - 1);
  4327. update(lastLine, lastLine.text, lastSpans);
  4328. if (nlines) { doc.remove(from.line, nlines); }
  4329. if (added.length) { doc.insert(from.line, added); }
  4330. } else if (firstLine == lastLine) {
  4331. if (text.length == 1) {
  4332. update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans);
  4333. } else {
  4334. var added$1 = linesFor(1, text.length - 1);
  4335. added$1.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight));
  4336. update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
  4337. doc.insert(from.line + 1, added$1);
  4338. }
  4339. } else if (text.length == 1) {
  4340. update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0));
  4341. doc.remove(from.line + 1, nlines);
  4342. } else {
  4343. update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
  4344. update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans);
  4345. var added$2 = linesFor(1, text.length - 1);
  4346. if (nlines > 1) { doc.remove(from.line + 1, nlines - 1); }
  4347. doc.insert(from.line + 1, added$2);
  4348. }
  4349. signalLater(doc, "change", doc, change);
  4350. }
  4351. // Call f for all linked documents.
  4352. function linkedDocs(doc, f, sharedHistOnly) {
  4353. function propagate(doc, skip, sharedHist) {
  4354. if (doc.linked) { for (var i = 0; i < doc.linked.length; ++i) {
  4355. var rel = doc.linked[i];
  4356. if (rel.doc == skip) { continue }
  4357. var shared = sharedHist && rel.sharedHist;
  4358. if (sharedHistOnly && !shared) { continue }
  4359. f(rel.doc, shared);
  4360. propagate(rel.doc, doc, shared);
  4361. } }
  4362. }
  4363. propagate(doc, null, true);
  4364. }
  4365. // Attach a document to an editor.
  4366. function attachDoc(cm, doc) {
  4367. if (doc.cm) { throw new Error("This document is already in use.") }
  4368. cm.doc = doc;
  4369. doc.cm = cm;
  4370. estimateLineHeights(cm);
  4371. loadMode(cm);
  4372. setDirectionClass(cm);
  4373. cm.options.direction = doc.direction;
  4374. if (!cm.options.lineWrapping) { findMaxLine(cm); }
  4375. cm.options.mode = doc.modeOption;
  4376. regChange(cm);
  4377. }
  4378. function setDirectionClass(cm) {
  4379. (cm.doc.direction == "rtl" ? addClass : rmClass)(cm.display.lineDiv, "CodeMirror-rtl");
  4380. }
  4381. function directionChanged(cm) {
  4382. runInOp(cm, function () {
  4383. setDirectionClass(cm);
  4384. regChange(cm);
  4385. });
  4386. }
  4387. function History(prev) {
  4388. // Arrays of change events and selections. Doing something adds an
  4389. // event to done and clears undo. Undoing moves events from done
  4390. // to undone, redoing moves them in the other direction.
  4391. this.done = []; this.undone = [];
  4392. this.undoDepth = prev ? prev.undoDepth : Infinity;
  4393. // Used to track when changes can be merged into a single undo
  4394. // event
  4395. this.lastModTime = this.lastSelTime = 0;
  4396. this.lastOp = this.lastSelOp = null;
  4397. this.lastOrigin = this.lastSelOrigin = null;
  4398. // Used by the isClean() method
  4399. this.generation = this.maxGeneration = prev ? prev.maxGeneration : 1;
  4400. }
  4401. // Create a history change event from an updateDoc-style change
  4402. // object.
  4403. function historyChangeFromChange(doc, change) {
  4404. var histChange = {from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to)};
  4405. attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);
  4406. linkedDocs(doc, function (doc) { return attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1); }, true);
  4407. return histChange
  4408. }
  4409. // Pop all selection events off the end of a history array. Stop at
  4410. // a change event.
  4411. function clearSelectionEvents(array) {
  4412. while (array.length) {
  4413. var last = lst(array);
  4414. if (last.ranges) { array.pop(); }
  4415. else { break }
  4416. }
  4417. }
  4418. // Find the top change event in the history. Pop off selection
  4419. // events that are in the way.
  4420. function lastChangeEvent(hist, force) {
  4421. if (force) {
  4422. clearSelectionEvents(hist.done);
  4423. return lst(hist.done)
  4424. } else if (hist.done.length && !lst(hist.done).ranges) {
  4425. return lst(hist.done)
  4426. } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) {
  4427. hist.done.pop();
  4428. return lst(hist.done)
  4429. }
  4430. }
  4431. // Register a change in the history. Merges changes that are within
  4432. // a single operation, or are close together with an origin that
  4433. // allows merging (starting with "+") into a single event.
  4434. function addChangeToHistory(doc, change, selAfter, opId) {
  4435. var hist = doc.history;
  4436. hist.undone.length = 0;
  4437. var time = +new Date, cur;
  4438. var last;
  4439. if ((hist.lastOp == opId ||
  4440. hist.lastOrigin == change.origin && change.origin &&
  4441. ((change.origin.charAt(0) == "+" && hist.lastModTime > time - (doc.cm ? doc.cm.options.historyEventDelay : 500)) ||
  4442. change.origin.charAt(0) == "*")) &&
  4443. (cur = lastChangeEvent(hist, hist.lastOp == opId))) {
  4444. // Merge this change into the last event
  4445. last = lst(cur.changes);
  4446. if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) {
  4447. // Optimized case for simple insertion -- don't want to add
  4448. // new changesets for every character typed
  4449. last.to = changeEnd(change);
  4450. } else {
  4451. // Add new sub-event
  4452. cur.changes.push(historyChangeFromChange(doc, change));
  4453. }
  4454. } else {
  4455. // Can not be merged, start a new event.
  4456. var before = lst(hist.done);
  4457. if (!before || !before.ranges)
  4458. { pushSelectionToHistory(doc.sel, hist.done); }
  4459. cur = {changes: [historyChangeFromChange(doc, change)],
  4460. generation: hist.generation};
  4461. hist.done.push(cur);
  4462. while (hist.done.length > hist.undoDepth) {
  4463. hist.done.shift();
  4464. if (!hist.done[0].ranges) { hist.done.shift(); }
  4465. }
  4466. }
  4467. hist.done.push(selAfter);
  4468. hist.generation = ++hist.maxGeneration;
  4469. hist.lastModTime = hist.lastSelTime = time;
  4470. hist.lastOp = hist.lastSelOp = opId;
  4471. hist.lastOrigin = hist.lastSelOrigin = change.origin;
  4472. if (!last) { signal(doc, "historyAdded"); }
  4473. }
  4474. function selectionEventCanBeMerged(doc, origin, prev, sel) {
  4475. var ch = origin.charAt(0);
  4476. return ch == "*" ||
  4477. ch == "+" &&
  4478. prev.ranges.length == sel.ranges.length &&
  4479. prev.somethingSelected() == sel.somethingSelected() &&
  4480. new Date - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500)
  4481. }
  4482. // Called whenever the selection changes, sets the new selection as
  4483. // the pending selection in the history, and pushes the old pending
  4484. // selection into the 'done' array when it was significantly
  4485. // different (in number of selected ranges, emptiness, or time).
  4486. function addSelectionToHistory(doc, sel, opId, options) {
  4487. var hist = doc.history, origin = options && options.origin;
  4488. // A new event is started when the previous origin does not match
  4489. // the current, or the origins don't allow matching. Origins
  4490. // starting with * are always merged, those starting with + are
  4491. // merged when similar and close together in time.
  4492. if (opId == hist.lastSelOp ||
  4493. (origin && hist.lastSelOrigin == origin &&
  4494. (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin ||
  4495. selectionEventCanBeMerged(doc, origin, lst(hist.done), sel))))
  4496. { hist.done[hist.done.length - 1] = sel; }
  4497. else
  4498. { pushSelectionToHistory(sel, hist.done); }
  4499. hist.lastSelTime = +new Date;
  4500. hist.lastSelOrigin = origin;
  4501. hist.lastSelOp = opId;
  4502. if (options && options.clearRedo !== false)
  4503. { clearSelectionEvents(hist.undone); }
  4504. }
  4505. function pushSelectionToHistory(sel, dest) {
  4506. var top = lst(dest);
  4507. if (!(top && top.ranges && top.equals(sel)))
  4508. { dest.push(sel); }
  4509. }
  4510. // Used to store marked span information in the history.
  4511. function attachLocalSpans(doc, change, from, to) {
  4512. var existing = change["spans_" + doc.id], n = 0;
  4513. doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function (line) {
  4514. if (line.markedSpans)
  4515. { (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans; }
  4516. ++n;
  4517. });
  4518. }
  4519. // When un/re-doing restores text containing marked spans, those
  4520. // that have been explicitly cleared should not be restored.
  4521. function removeClearedSpans(spans) {
  4522. if (!spans) { return null }
  4523. var out;
  4524. for (var i = 0; i < spans.length; ++i) {
  4525. if (spans[i].marker.explicitlyCleared) { if (!out) { out = spans.slice(0, i); } }
  4526. else if (out) { out.push(spans[i]); }
  4527. }
  4528. return !out ? spans : out.length ? out : null
  4529. }
  4530. // Retrieve and filter the old marked spans stored in a change event.
  4531. function getOldSpans(doc, change) {
  4532. var found = change["spans_" + doc.id];
  4533. if (!found) { return null }
  4534. var nw = [];
  4535. for (var i = 0; i < change.text.length; ++i)
  4536. { nw.push(removeClearedSpans(found[i])); }
  4537. return nw
  4538. }
  4539. // Used for un/re-doing changes from the history. Combines the
  4540. // result of computing the existing spans with the set of spans that
  4541. // existed in the history (so that deleting around a span and then
  4542. // undoing brings back the span).
  4543. function mergeOldSpans(doc, change) {
  4544. var old = getOldSpans(doc, change);
  4545. var stretched = stretchSpansOverChange(doc, change);
  4546. if (!old) { return stretched }
  4547. if (!stretched) { return old }
  4548. for (var i = 0; i < old.length; ++i) {
  4549. var oldCur = old[i], stretchCur = stretched[i];
  4550. if (oldCur && stretchCur) {
  4551. spans: for (var j = 0; j < stretchCur.length; ++j) {
  4552. var span = stretchCur[j];
  4553. for (var k = 0; k < oldCur.length; ++k)
  4554. { if (oldCur[k].marker == span.marker) { continue spans } }
  4555. oldCur.push(span);
  4556. }
  4557. } else if (stretchCur) {
  4558. old[i] = stretchCur;
  4559. }
  4560. }
  4561. return old
  4562. }
  4563. // Used both to provide a JSON-safe object in .getHistory, and, when
  4564. // detaching a document, to split the history in two
  4565. function copyHistoryArray(events, newGroup, instantiateSel) {
  4566. var copy = [];
  4567. for (var i = 0; i < events.length; ++i) {
  4568. var event = events[i];
  4569. if (event.ranges) {
  4570. copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event);
  4571. continue
  4572. }
  4573. var changes = event.changes, newChanges = [];
  4574. copy.push({changes: newChanges});
  4575. for (var j = 0; j < changes.length; ++j) {
  4576. var change = changes[j], m = (void 0);
  4577. newChanges.push({from: change.from, to: change.to, text: change.text});
  4578. if (newGroup) { for (var prop in change) { if (m = prop.match(/^spans_(\d+)$/)) {
  4579. if (indexOf(newGroup, Number(m[1])) > -1) {
  4580. lst(newChanges)[prop] = change[prop];
  4581. delete change[prop];
  4582. }
  4583. } } }
  4584. }
  4585. }
  4586. return copy
  4587. }
  4588. // The 'scroll' parameter given to many of these indicated whether
  4589. // the new cursor position should be scrolled into view after
  4590. // modifying the selection.
  4591. // If shift is held or the extend flag is set, extends a range to
  4592. // include a given position (and optionally a second position).
  4593. // Otherwise, simply returns the range between the given positions.
  4594. // Used for cursor motion and such.
  4595. function extendRange(range, head, other, extend) {
  4596. if (extend) {
  4597. var anchor = range.anchor;
  4598. if (other) {
  4599. var posBefore = cmp(head, anchor) < 0;
  4600. if (posBefore != (cmp(other, anchor) < 0)) {
  4601. anchor = head;
  4602. head = other;
  4603. } else if (posBefore != (cmp(head, other) < 0)) {
  4604. head = other;
  4605. }
  4606. }
  4607. return new Range(anchor, head)
  4608. } else {
  4609. return new Range(other || head, head)
  4610. }
  4611. }
  4612. // Extend the primary selection range, discard the rest.
  4613. function extendSelection(doc, head, other, options, extend) {
  4614. if (extend == null) { extend = doc.cm && (doc.cm.display.shift || doc.extend); }
  4615. setSelection(doc, new Selection([extendRange(doc.sel.primary(), head, other, extend)], 0), options);
  4616. }
  4617. // Extend all selections (pos is an array of selections with length
  4618. // equal the number of selections)
  4619. function extendSelections(doc, heads, options) {
  4620. var out = [];
  4621. var extend = doc.cm && (doc.cm.display.shift || doc.extend);
  4622. for (var i = 0; i < doc.sel.ranges.length; i++)
  4623. { out[i] = extendRange(doc.sel.ranges[i], heads[i], null, extend); }
  4624. var newSel = normalizeSelection(doc.cm, out, doc.sel.primIndex);
  4625. setSelection(doc, newSel, options);
  4626. }
  4627. // Updates a single range in the selection.
  4628. function replaceOneSelection(doc, i, range, options) {
  4629. var ranges = doc.sel.ranges.slice(0);
  4630. ranges[i] = range;
  4631. setSelection(doc, normalizeSelection(doc.cm, ranges, doc.sel.primIndex), options);
  4632. }
  4633. // Reset the selection to a single range.
  4634. function setSimpleSelection(doc, anchor, head, options) {
  4635. setSelection(doc, simpleSelection(anchor, head), options);
  4636. }
  4637. // Give beforeSelectionChange handlers a change to influence a
  4638. // selection update.
  4639. function filterSelectionChange(doc, sel, options) {
  4640. var obj = {
  4641. ranges: sel.ranges,
  4642. update: function(ranges) {
  4643. this.ranges = [];
  4644. for (var i = 0; i < ranges.length; i++)
  4645. { this.ranges[i] = new Range(clipPos(doc, ranges[i].anchor),
  4646. clipPos(doc, ranges[i].head)); }
  4647. },
  4648. origin: options && options.origin
  4649. };
  4650. signal(doc, "beforeSelectionChange", doc, obj);
  4651. if (doc.cm) { signal(doc.cm, "beforeSelectionChange", doc.cm, obj); }
  4652. if (obj.ranges != sel.ranges) { return normalizeSelection(doc.cm, obj.ranges, obj.ranges.length - 1) }
  4653. else { return sel }
  4654. }
  4655. function setSelectionReplaceHistory(doc, sel, options) {
  4656. var done = doc.history.done, last = lst(done);
  4657. if (last && last.ranges) {
  4658. done[done.length - 1] = sel;
  4659. setSelectionNoUndo(doc, sel, options);
  4660. } else {
  4661. setSelection(doc, sel, options);
  4662. }
  4663. }
  4664. // Set a new selection.
  4665. function setSelection(doc, sel, options) {
  4666. setSelectionNoUndo(doc, sel, options);
  4667. addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options);
  4668. }
  4669. function setSelectionNoUndo(doc, sel, options) {
  4670. if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange"))
  4671. { sel = filterSelectionChange(doc, sel, options); }
  4672. var bias = options && options.bias ||
  4673. (cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1);
  4674. setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true));
  4675. if (!(options && options.scroll === false) && doc.cm && doc.cm.getOption("readOnly") != "nocursor")
  4676. { ensureCursorVisible(doc.cm); }
  4677. }
  4678. function setSelectionInner(doc, sel) {
  4679. if (sel.equals(doc.sel)) { return }
  4680. doc.sel = sel;
  4681. if (doc.cm) {
  4682. doc.cm.curOp.updateInput = 1;
  4683. doc.cm.curOp.selectionChanged = true;
  4684. signalCursorActivity(doc.cm);
  4685. }
  4686. signalLater(doc, "cursorActivity", doc);
  4687. }
  4688. // Verify that the selection does not partially select any atomic
  4689. // marked ranges.
  4690. function reCheckSelection(doc) {
  4691. setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false));
  4692. }
  4693. // Return a selection that does not partially select any atomic
  4694. // ranges.
  4695. function skipAtomicInSelection(doc, sel, bias, mayClear) {
  4696. var out;
  4697. for (var i = 0; i < sel.ranges.length; i++) {
  4698. var range = sel.ranges[i];
  4699. var old = sel.ranges.length == doc.sel.ranges.length && doc.sel.ranges[i];
  4700. var newAnchor = skipAtomic(doc, range.anchor, old && old.anchor, bias, mayClear);
  4701. var newHead = skipAtomic(doc, range.head, old && old.head, bias, mayClear);
  4702. if (out || newAnchor != range.anchor || newHead != range.head) {
  4703. if (!out) { out = sel.ranges.slice(0, i); }
  4704. out[i] = new Range(newAnchor, newHead);
  4705. }
  4706. }
  4707. return out ? normalizeSelection(doc.cm, out, sel.primIndex) : sel
  4708. }
  4709. function skipAtomicInner(doc, pos, oldPos, dir, mayClear) {
  4710. var line = getLine(doc, pos.line);
  4711. if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) {
  4712. var sp = line.markedSpans[i], m = sp.marker;
  4713. // Determine if we should prevent the cursor being placed to the left/right of an atomic marker
  4714. // Historically this was determined using the inclusiveLeft/Right option, but the new way to control it
  4715. // is with selectLeft/Right
  4716. var preventCursorLeft = ("selectLeft" in m) ? !m.selectLeft : m.inclusiveLeft;
  4717. var preventCursorRight = ("selectRight" in m) ? !m.selectRight : m.inclusiveRight;
  4718. if ((sp.from == null || (preventCursorLeft ? sp.from <= pos.ch : sp.from < pos.ch)) &&
  4719. (sp.to == null || (preventCursorRight ? sp.to >= pos.ch : sp.to > pos.ch))) {
  4720. if (mayClear) {
  4721. signal(m, "beforeCursorEnter");
  4722. if (m.explicitlyCleared) {
  4723. if (!line.markedSpans) { break }
  4724. else {--i; continue}
  4725. }
  4726. }
  4727. if (!m.atomic) { continue }
  4728. if (oldPos) {
  4729. var near = m.find(dir < 0 ? 1 : -1), diff = (void 0);
  4730. if (dir < 0 ? preventCursorRight : preventCursorLeft)
  4731. { near = movePos(doc, near, -dir, near && near.line == pos.line ? line : null); }
  4732. if (near && near.line == pos.line && (diff = cmp(near, oldPos)) && (dir < 0 ? diff < 0 : diff > 0))
  4733. { return skipAtomicInner(doc, near, pos, dir, mayClear) }
  4734. }
  4735. var far = m.find(dir < 0 ? -1 : 1);
  4736. if (dir < 0 ? preventCursorLeft : preventCursorRight)
  4737. { far = movePos(doc, far, dir, far.line == pos.line ? line : null); }
  4738. return far ? skipAtomicInner(doc, far, pos, dir, mayClear) : null
  4739. }
  4740. } }
  4741. return pos
  4742. }
  4743. // Ensure a given position is not inside an atomic range.
  4744. function skipAtomic(doc, pos, oldPos, bias, mayClear) {
  4745. var dir = bias || 1;
  4746. var found = skipAtomicInner(doc, pos, oldPos, dir, mayClear) ||
  4747. (!mayClear && skipAtomicInner(doc, pos, oldPos, dir, true)) ||
  4748. skipAtomicInner(doc, pos, oldPos, -dir, mayClear) ||
  4749. (!mayClear && skipAtomicInner(doc, pos, oldPos, -dir, true));
  4750. if (!found) {
  4751. doc.cantEdit = true;
  4752. return Pos(doc.first, 0)
  4753. }
  4754. return found
  4755. }
  4756. function movePos(doc, pos, dir, line) {
  4757. if (dir < 0 && pos.ch == 0) {
  4758. if (pos.line > doc.first) { return clipPos(doc, Pos(pos.line - 1)) }
  4759. else { return null }
  4760. } else if (dir > 0 && pos.ch == (line || getLine(doc, pos.line)).text.length) {
  4761. if (pos.line < doc.first + doc.size - 1) { return Pos(pos.line + 1, 0) }
  4762. else { return null }
  4763. } else {
  4764. return new Pos(pos.line, pos.ch + dir)
  4765. }
  4766. }
  4767. function selectAll(cm) {
  4768. cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll);
  4769. }
  4770. // UPDATING
  4771. // Allow "beforeChange" event handlers to influence a change
  4772. function filterChange(doc, change, update) {
  4773. var obj = {
  4774. canceled: false,
  4775. from: change.from,
  4776. to: change.to,
  4777. text: change.text,
  4778. origin: change.origin,
  4779. cancel: function () { return obj.canceled = true; }
  4780. };
  4781. if (update) { obj.update = function (from, to, text, origin) {
  4782. if (from) { obj.from = clipPos(doc, from); }
  4783. if (to) { obj.to = clipPos(doc, to); }
  4784. if (text) { obj.text = text; }
  4785. if (origin !== undefined) { obj.origin = origin; }
  4786. }; }
  4787. signal(doc, "beforeChange", doc, obj);
  4788. if (doc.cm) { signal(doc.cm, "beforeChange", doc.cm, obj); }
  4789. if (obj.canceled) {
  4790. if (doc.cm) { doc.cm.curOp.updateInput = 2; }
  4791. return null
  4792. }
  4793. return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin}
  4794. }
  4795. // Apply a change to a document, and add it to the document's
  4796. // history, and propagating it to all linked documents.
  4797. function makeChange(doc, change, ignoreReadOnly) {
  4798. if (doc.cm) {
  4799. if (!doc.cm.curOp) { return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly) }
  4800. if (doc.cm.state.suppressEdits) { return }
  4801. }
  4802. if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) {
  4803. change = filterChange(doc, change, true);
  4804. if (!change) { return }
  4805. }
  4806. // Possibly split or suppress the update based on the presence
  4807. // of read-only spans in its range.
  4808. var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to);
  4809. if (split) {
  4810. for (var i = split.length - 1; i >= 0; --i)
  4811. { makeChangeInner(doc, {from: split[i].from, to: split[i].to, text: i ? [""] : change.text, origin: change.origin}); }
  4812. } else {
  4813. makeChangeInner(doc, change);
  4814. }
  4815. }
  4816. function makeChangeInner(doc, change) {
  4817. if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) { return }
  4818. var selAfter = computeSelAfterChange(doc, change);
  4819. addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN);
  4820. makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change));
  4821. var rebased = [];
  4822. linkedDocs(doc, function (doc, sharedHist) {
  4823. if (!sharedHist && indexOf(rebased, doc.history) == -1) {
  4824. rebaseHist(doc.history, change);
  4825. rebased.push(doc.history);
  4826. }
  4827. makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change));
  4828. });
  4829. }
  4830. // Revert a change stored in a document's history.
  4831. function makeChangeFromHistory(doc, type, allowSelectionOnly) {
  4832. var suppress = doc.cm && doc.cm.state.suppressEdits;
  4833. if (suppress && !allowSelectionOnly) { return }
  4834. var hist = doc.history, event, selAfter = doc.sel;
  4835. var source = type == "undo" ? hist.done : hist.undone, dest = type == "undo" ? hist.undone : hist.done;
  4836. // Verify that there is a useable event (so that ctrl-z won't
  4837. // needlessly clear selection events)
  4838. var i = 0;
  4839. for (; i < source.length; i++) {
  4840. event = source[i];
  4841. if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges)
  4842. { break }
  4843. }
  4844. if (i == source.length) { return }
  4845. hist.lastOrigin = hist.lastSelOrigin = null;
  4846. for (;;) {
  4847. event = source.pop();
  4848. if (event.ranges) {
  4849. pushSelectionToHistory(event, dest);
  4850. if (allowSelectionOnly && !event.equals(doc.sel)) {
  4851. setSelection(doc, event, {clearRedo: false});
  4852. return
  4853. }
  4854. selAfter = event;
  4855. } else if (suppress) {
  4856. source.push(event);
  4857. return
  4858. } else { break }
  4859. }
  4860. // Build up a reverse change object to add to the opposite history
  4861. // stack (redo when undoing, and vice versa).
  4862. var antiChanges = [];
  4863. pushSelectionToHistory(selAfter, dest);
  4864. dest.push({changes: antiChanges, generation: hist.generation});
  4865. hist.generation = event.generation || ++hist.maxGeneration;
  4866. var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange");
  4867. var loop = function ( i ) {
  4868. var change = event.changes[i];
  4869. change.origin = type;
  4870. if (filter && !filterChange(doc, change, false)) {
  4871. source.length = 0;
  4872. return {}
  4873. }
  4874. antiChanges.push(historyChangeFromChange(doc, change));
  4875. var after = i ? computeSelAfterChange(doc, change) : lst(source);
  4876. makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change));
  4877. if (!i && doc.cm) { doc.cm.scrollIntoView({from: change.from, to: changeEnd(change)}); }
  4878. var rebased = [];
  4879. // Propagate to the linked documents
  4880. linkedDocs(doc, function (doc, sharedHist) {
  4881. if (!sharedHist && indexOf(rebased, doc.history) == -1) {
  4882. rebaseHist(doc.history, change);
  4883. rebased.push(doc.history);
  4884. }
  4885. makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change));
  4886. });
  4887. };
  4888. for (var i$1 = event.changes.length - 1; i$1 >= 0; --i$1) {
  4889. var returned = loop( i$1 );
  4890. if ( returned ) return returned.v;
  4891. }
  4892. }
  4893. // Sub-views need their line numbers shifted when text is added
  4894. // above or below them in the parent document.
  4895. function shiftDoc(doc, distance) {
  4896. if (distance == 0) { return }
  4897. doc.first += distance;
  4898. doc.sel = new Selection(map(doc.sel.ranges, function (range) { return new Range(
  4899. Pos(range.anchor.line + distance, range.anchor.ch),
  4900. Pos(range.head.line + distance, range.head.ch)
  4901. ); }), doc.sel.primIndex);
  4902. if (doc.cm) {
  4903. regChange(doc.cm, doc.first, doc.first - distance, distance);
  4904. for (var d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++)
  4905. { regLineChange(doc.cm, l, "gutter"); }
  4906. }
  4907. }
  4908. // More lower-level change function, handling only a single document
  4909. // (not linked ones).
  4910. function makeChangeSingleDoc(doc, change, selAfter, spans) {
  4911. if (doc.cm && !doc.cm.curOp)
  4912. { return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans) }
  4913. if (change.to.line < doc.first) {
  4914. shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line));
  4915. return
  4916. }
  4917. if (change.from.line > doc.lastLine()) { return }
  4918. // Clip the change to the size of this doc
  4919. if (change.from.line < doc.first) {
  4920. var shift = change.text.length - 1 - (doc.first - change.from.line);
  4921. shiftDoc(doc, shift);
  4922. change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch),
  4923. text: [lst(change.text)], origin: change.origin};
  4924. }
  4925. var last = doc.lastLine();
  4926. if (change.to.line > last) {
  4927. change = {from: change.from, to: Pos(last, getLine(doc, last).text.length),
  4928. text: [change.text[0]], origin: change.origin};
  4929. }
  4930. change.removed = getBetween(doc, change.from, change.to);
  4931. if (!selAfter) { selAfter = computeSelAfterChange(doc, change); }
  4932. if (doc.cm) { makeChangeSingleDocInEditor(doc.cm, change, spans); }
  4933. else { updateDoc(doc, change, spans); }
  4934. setSelectionNoUndo(doc, selAfter, sel_dontScroll);
  4935. if (doc.cantEdit && skipAtomic(doc, Pos(doc.firstLine(), 0)))
  4936. { doc.cantEdit = false; }
  4937. }
  4938. // Handle the interaction of a change to a document with the editor
  4939. // that this document is part of.
  4940. function makeChangeSingleDocInEditor(cm, change, spans) {
  4941. var doc = cm.doc, display = cm.display, from = change.from, to = change.to;
  4942. var recomputeMaxLength = false, checkWidthStart = from.line;
  4943. if (!cm.options.lineWrapping) {
  4944. checkWidthStart = lineNo(visualLine(getLine(doc, from.line)));
  4945. doc.iter(checkWidthStart, to.line + 1, function (line) {
  4946. if (line == display.maxLine) {
  4947. recomputeMaxLength = true;
  4948. return true
  4949. }
  4950. });
  4951. }
  4952. if (doc.sel.contains(change.from, change.to) > -1)
  4953. { signalCursorActivity(cm); }
  4954. updateDoc(doc, change, spans, estimateHeight(cm));
  4955. if (!cm.options.lineWrapping) {
  4956. doc.iter(checkWidthStart, from.line + change.text.length, function (line) {
  4957. var len = lineLength(line);
  4958. if (len > display.maxLineLength) {
  4959. display.maxLine = line;
  4960. display.maxLineLength = len;
  4961. display.maxLineChanged = true;
  4962. recomputeMaxLength = false;
  4963. }
  4964. });
  4965. if (recomputeMaxLength) { cm.curOp.updateMaxLine = true; }
  4966. }
  4967. retreatFrontier(doc, from.line);
  4968. startWorker(cm, 400);
  4969. var lendiff = change.text.length - (to.line - from.line) - 1;
  4970. // Remember that these lines changed, for updating the display
  4971. if (change.full)
  4972. { regChange(cm); }
  4973. else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change))
  4974. { regLineChange(cm, from.line, "text"); }
  4975. else
  4976. { regChange(cm, from.line, to.line + 1, lendiff); }
  4977. var changesHandler = hasHandler(cm, "changes"), changeHandler = hasHandler(cm, "change");
  4978. if (changeHandler || changesHandler) {
  4979. var obj = {
  4980. from: from, to: to,
  4981. text: change.text,
  4982. removed: change.removed,
  4983. origin: change.origin
  4984. };
  4985. if (changeHandler) { signalLater(cm, "change", cm, obj); }
  4986. if (changesHandler) { (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj); }
  4987. }
  4988. cm.display.selForContextMenu = null;
  4989. }
  4990. function replaceRange(doc, code, from, to, origin) {
  4991. var assign;
  4992. if (!to) { to = from; }
  4993. if (cmp(to, from) < 0) { (assign = [to, from], from = assign[0], to = assign[1]); }
  4994. if (typeof code == "string") { code = doc.splitLines(code); }
  4995. makeChange(doc, {from: from, to: to, text: code, origin: origin});
  4996. }
  4997. // Rebasing/resetting history to deal with externally-sourced changes
  4998. function rebaseHistSelSingle(pos, from, to, diff) {
  4999. if (to < pos.line) {
  5000. pos.line += diff;
  5001. } else if (from < pos.line) {
  5002. pos.line = from;
  5003. pos.ch = 0;
  5004. }
  5005. }
  5006. // Tries to rebase an array of history events given a change in the
  5007. // document. If the change touches the same lines as the event, the
  5008. // event, and everything 'behind' it, is discarded. If the change is
  5009. // before the event, the event's positions are updated. Uses a
  5010. // copy-on-write scheme for the positions, to avoid having to
  5011. // reallocate them all on every rebase, but also avoid problems with
  5012. // shared position objects being unsafely updated.
  5013. function rebaseHistArray(array, from, to, diff) {
  5014. for (var i = 0; i < array.length; ++i) {
  5015. var sub = array[i], ok = true;
  5016. if (sub.ranges) {
  5017. if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true; }
  5018. for (var j = 0; j < sub.ranges.length; j++) {
  5019. rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff);
  5020. rebaseHistSelSingle(sub.ranges[j].head, from, to, diff);
  5021. }
  5022. continue
  5023. }
  5024. for (var j$1 = 0; j$1 < sub.changes.length; ++j$1) {
  5025. var cur = sub.changes[j$1];
  5026. if (to < cur.from.line) {
  5027. cur.from = Pos(cur.from.line + diff, cur.from.ch);
  5028. cur.to = Pos(cur.to.line + diff, cur.to.ch);
  5029. } else if (from <= cur.to.line) {
  5030. ok = false;
  5031. break
  5032. }
  5033. }
  5034. if (!ok) {
  5035. array.splice(0, i + 1);
  5036. i = 0;
  5037. }
  5038. }
  5039. }
  5040. function rebaseHist(hist, change) {
  5041. var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1;
  5042. rebaseHistArray(hist.done, from, to, diff);
  5043. rebaseHistArray(hist.undone, from, to, diff);
  5044. }
  5045. // Utility for applying a change to a line by handle or number,
  5046. // returning the number and optionally registering the line as
  5047. // changed.
  5048. function changeLine(doc, handle, changeType, op) {
  5049. var no = handle, line = handle;
  5050. if (typeof handle == "number") { line = getLine(doc, clipLine(doc, handle)); }
  5051. else { no = lineNo(handle); }
  5052. if (no == null) { return null }
  5053. if (op(line, no) && doc.cm) { regLineChange(doc.cm, no, changeType); }
  5054. return line
  5055. }
  5056. // The document is represented as a BTree consisting of leaves, with
  5057. // chunk of lines in them, and branches, with up to ten leaves or
  5058. // other branch nodes below them. The top node is always a branch
  5059. // node, and is the document object itself (meaning it has
  5060. // additional methods and properties).
  5061. //
  5062. // All nodes have parent links. The tree is used both to go from
  5063. // line numbers to line objects, and to go from objects to numbers.
  5064. // It also indexes by height, and is used to convert between height
  5065. // and line object, and to find the total height of the document.
  5066. //
  5067. // See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html
  5068. function LeafChunk(lines) {
  5069. this.lines = lines;
  5070. this.parent = null;
  5071. var height = 0;
  5072. for (var i = 0; i < lines.length; ++i) {
  5073. lines[i].parent = this;
  5074. height += lines[i].height;
  5075. }
  5076. this.height = height;
  5077. }
  5078. LeafChunk.prototype = {
  5079. chunkSize: function() { return this.lines.length },
  5080. // Remove the n lines at offset 'at'.
  5081. removeInner: function(at, n) {
  5082. for (var i = at, e = at + n; i < e; ++i) {
  5083. var line = this.lines[i];
  5084. this.height -= line.height;
  5085. cleanUpLine(line);
  5086. signalLater(line, "delete");
  5087. }
  5088. this.lines.splice(at, n);
  5089. },
  5090. // Helper used to collapse a small branch into a single leaf.
  5091. collapse: function(lines) {
  5092. lines.push.apply(lines, this.lines);
  5093. },
  5094. // Insert the given array of lines at offset 'at', count them as
  5095. // having the given height.
  5096. insertInner: function(at, lines, height) {
  5097. this.height += height;
  5098. this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at));
  5099. for (var i = 0; i < lines.length; ++i) { lines[i].parent = this; }
  5100. },
  5101. // Used to iterate over a part of the tree.
  5102. iterN: function(at, n, op) {
  5103. for (var e = at + n; at < e; ++at)
  5104. { if (op(this.lines[at])) { return true } }
  5105. }
  5106. };
  5107. function BranchChunk(children) {
  5108. this.children = children;
  5109. var size = 0, height = 0;
  5110. for (var i = 0; i < children.length; ++i) {
  5111. var ch = children[i];
  5112. size += ch.chunkSize(); height += ch.height;
  5113. ch.parent = this;
  5114. }
  5115. this.size = size;
  5116. this.height = height;
  5117. this.parent = null;
  5118. }
  5119. BranchChunk.prototype = {
  5120. chunkSize: function() { return this.size },
  5121. removeInner: function(at, n) {
  5122. this.size -= n;
  5123. for (var i = 0; i < this.children.length; ++i) {
  5124. var child = this.children[i], sz = child.chunkSize();
  5125. if (at < sz) {
  5126. var rm = Math.min(n, sz - at), oldHeight = child.height;
  5127. child.removeInner(at, rm);
  5128. this.height -= oldHeight - child.height;
  5129. if (sz == rm) { this.children.splice(i--, 1); child.parent = null; }
  5130. if ((n -= rm) == 0) { break }
  5131. at = 0;
  5132. } else { at -= sz; }
  5133. }
  5134. // If the result is smaller than 25 lines, ensure that it is a
  5135. // single leaf node.
  5136. if (this.size - n < 25 &&
  5137. (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) {
  5138. var lines = [];
  5139. this.collapse(lines);
  5140. this.children = [new LeafChunk(lines)];
  5141. this.children[0].parent = this;
  5142. }
  5143. },
  5144. collapse: function(lines) {
  5145. for (var i = 0; i < this.children.length; ++i) { this.children[i].collapse(lines); }
  5146. },
  5147. insertInner: function(at, lines, height) {
  5148. this.size += lines.length;
  5149. this.height += height;
  5150. for (var i = 0; i < this.children.length; ++i) {
  5151. var child = this.children[i], sz = child.chunkSize();
  5152. if (at <= sz) {
  5153. child.insertInner(at, lines, height);
  5154. if (child.lines && child.lines.length > 50) {
  5155. // To avoid memory thrashing when child.lines is huge (e.g. first view of a large file), it's never spliced.
  5156. // Instead, small slices are taken. They're taken in order because sequential memory accesses are fastest.
  5157. var remaining = child.lines.length % 25 + 25;
  5158. for (var pos = remaining; pos < child.lines.length;) {
  5159. var leaf = new LeafChunk(child.lines.slice(pos, pos += 25));
  5160. child.height -= leaf.height;
  5161. this.children.splice(++i, 0, leaf);
  5162. leaf.parent = this;
  5163. }
  5164. child.lines = child.lines.slice(0, remaining);
  5165. this.maybeSpill();
  5166. }
  5167. break
  5168. }
  5169. at -= sz;
  5170. }
  5171. },
  5172. // When a node has grown, check whether it should be split.
  5173. maybeSpill: function() {
  5174. if (this.children.length <= 10) { return }
  5175. var me = this;
  5176. do {
  5177. var spilled = me.children.splice(me.children.length - 5, 5);
  5178. var sibling = new BranchChunk(spilled);
  5179. if (!me.parent) { // Become the parent node
  5180. var copy = new BranchChunk(me.children);
  5181. copy.parent = me;
  5182. me.children = [copy, sibling];
  5183. me = copy;
  5184. } else {
  5185. me.size -= sibling.size;
  5186. me.height -= sibling.height;
  5187. var myIndex = indexOf(me.parent.children, me);
  5188. me.parent.children.splice(myIndex + 1, 0, sibling);
  5189. }
  5190. sibling.parent = me.parent;
  5191. } while (me.children.length > 10)
  5192. me.parent.maybeSpill();
  5193. },
  5194. iterN: function(at, n, op) {
  5195. for (var i = 0; i < this.children.length; ++i) {
  5196. var child = this.children[i], sz = child.chunkSize();
  5197. if (at < sz) {
  5198. var used = Math.min(n, sz - at);
  5199. if (child.iterN(at, used, op)) { return true }
  5200. if ((n -= used) == 0) { break }
  5201. at = 0;
  5202. } else { at -= sz; }
  5203. }
  5204. }
  5205. };
  5206. // Line widgets are block elements displayed above or below a line.
  5207. var LineWidget = function(doc, node, options) {
  5208. if (options) { for (var opt in options) { if (options.hasOwnProperty(opt))
  5209. { this[opt] = options[opt]; } } }
  5210. this.doc = doc;
  5211. this.node = node;
  5212. };
  5213. LineWidget.prototype.clear = function () {
  5214. var cm = this.doc.cm, ws = this.line.widgets, line = this.line, no = lineNo(line);
  5215. if (no == null || !ws) { return }
  5216. for (var i = 0; i < ws.length; ++i) { if (ws[i] == this) { ws.splice(i--, 1); } }
  5217. if (!ws.length) { line.widgets = null; }
  5218. var height = widgetHeight(this);
  5219. updateLineHeight(line, Math.max(0, line.height - height));
  5220. if (cm) {
  5221. runInOp(cm, function () {
  5222. adjustScrollWhenAboveVisible(cm, line, -height);
  5223. regLineChange(cm, no, "widget");
  5224. });
  5225. signalLater(cm, "lineWidgetCleared", cm, this, no);
  5226. }
  5227. };
  5228. LineWidget.prototype.changed = function () {
  5229. var this$1 = this;
  5230. var oldH = this.height, cm = this.doc.cm, line = this.line;
  5231. this.height = null;
  5232. var diff = widgetHeight(this) - oldH;
  5233. if (!diff) { return }
  5234. if (!lineIsHidden(this.doc, line)) { updateLineHeight(line, line.height + diff); }
  5235. if (cm) {
  5236. runInOp(cm, function () {
  5237. cm.curOp.forceUpdate = true;
  5238. adjustScrollWhenAboveVisible(cm, line, diff);
  5239. signalLater(cm, "lineWidgetChanged", cm, this$1, lineNo(line));
  5240. });
  5241. }
  5242. };
  5243. eventMixin(LineWidget);
  5244. function adjustScrollWhenAboveVisible(cm, line, diff) {
  5245. if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop))
  5246. { addToScrollTop(cm, diff); }
  5247. }
  5248. function addLineWidget(doc, handle, node, options) {
  5249. var widget = new LineWidget(doc, node, options);
  5250. var cm = doc.cm;
  5251. if (cm && widget.noHScroll) { cm.display.alignWidgets = true; }
  5252. changeLine(doc, handle, "widget", function (line) {
  5253. var widgets = line.widgets || (line.widgets = []);
  5254. if (widget.insertAt == null) { widgets.push(widget); }
  5255. else { widgets.splice(Math.min(widgets.length, Math.max(0, widget.insertAt)), 0, widget); }
  5256. widget.line = line;
  5257. if (cm && !lineIsHidden(doc, line)) {
  5258. var aboveVisible = heightAtLine(line) < doc.scrollTop;
  5259. updateLineHeight(line, line.height + widgetHeight(widget));
  5260. if (aboveVisible) { addToScrollTop(cm, widget.height); }
  5261. cm.curOp.forceUpdate = true;
  5262. }
  5263. return true
  5264. });
  5265. if (cm) { signalLater(cm, "lineWidgetAdded", cm, widget, typeof handle == "number" ? handle : lineNo(handle)); }
  5266. return widget
  5267. }
  5268. // TEXTMARKERS
  5269. // Created with markText and setBookmark methods. A TextMarker is a
  5270. // handle that can be used to clear or find a marked position in the
  5271. // document. Line objects hold arrays (markedSpans) containing
  5272. // {from, to, marker} object pointing to such marker objects, and
  5273. // indicating that such a marker is present on that line. Multiple
  5274. // lines may point to the same marker when it spans across lines.
  5275. // The spans will have null for their from/to properties when the
  5276. // marker continues beyond the start/end of the line. Markers have
  5277. // links back to the lines they currently touch.
  5278. // Collapsed markers have unique ids, in order to be able to order
  5279. // them, which is needed for uniquely determining an outer marker
  5280. // when they overlap (they may nest, but not partially overlap).
  5281. var nextMarkerId = 0;
  5282. var TextMarker = function(doc, type) {
  5283. this.lines = [];
  5284. this.type = type;
  5285. this.doc = doc;
  5286. this.id = ++nextMarkerId;
  5287. };
  5288. // Clear the marker.
  5289. TextMarker.prototype.clear = function () {
  5290. if (this.explicitlyCleared) { return }
  5291. var cm = this.doc.cm, withOp = cm && !cm.curOp;
  5292. if (withOp) { startOperation(cm); }
  5293. if (hasHandler(this, "clear")) {
  5294. var found = this.find();
  5295. if (found) { signalLater(this, "clear", found.from, found.to); }
  5296. }
  5297. var min = null, max = null;
  5298. for (var i = 0; i < this.lines.length; ++i) {
  5299. var line = this.lines[i];
  5300. var span = getMarkedSpanFor(line.markedSpans, this);
  5301. if (cm && !this.collapsed) { regLineChange(cm, lineNo(line), "text"); }
  5302. else if (cm) {
  5303. if (span.to != null) { max = lineNo(line); }
  5304. if (span.from != null) { min = lineNo(line); }
  5305. }
  5306. line.markedSpans = removeMarkedSpan(line.markedSpans, span);
  5307. if (span.from == null && this.collapsed && !lineIsHidden(this.doc, line) && cm)
  5308. { updateLineHeight(line, textHeight(cm.display)); }
  5309. }
  5310. if (cm && this.collapsed && !cm.options.lineWrapping) { for (var i$1 = 0; i$1 < this.lines.length; ++i$1) {
  5311. var visual = visualLine(this.lines[i$1]), len = lineLength(visual);
  5312. if (len > cm.display.maxLineLength) {
  5313. cm.display.maxLine = visual;
  5314. cm.display.maxLineLength = len;
  5315. cm.display.maxLineChanged = true;
  5316. }
  5317. } }
  5318. if (min != null && cm && this.collapsed) { regChange(cm, min, max + 1); }
  5319. this.lines.length = 0;
  5320. this.explicitlyCleared = true;
  5321. if (this.atomic && this.doc.cantEdit) {
  5322. this.doc.cantEdit = false;
  5323. if (cm) { reCheckSelection(cm.doc); }
  5324. }
  5325. if (cm) { signalLater(cm, "markerCleared", cm, this, min, max); }
  5326. if (withOp) { endOperation(cm); }
  5327. if (this.parent) { this.parent.clear(); }
  5328. };
  5329. // Find the position of the marker in the document. Returns a {from,
  5330. // to} object by default. Side can be passed to get a specific side
  5331. // -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the
  5332. // Pos objects returned contain a line object, rather than a line
  5333. // number (used to prevent looking up the same line twice).
  5334. TextMarker.prototype.find = function (side, lineObj) {
  5335. if (side == null && this.type == "bookmark") { side = 1; }
  5336. var from, to;
  5337. for (var i = 0; i < this.lines.length; ++i) {
  5338. var line = this.lines[i];
  5339. var span = getMarkedSpanFor(line.markedSpans, this);
  5340. if (span.from != null) {
  5341. from = Pos(lineObj ? line : lineNo(line), span.from);
  5342. if (side == -1) { return from }
  5343. }
  5344. if (span.to != null) {
  5345. to = Pos(lineObj ? line : lineNo(line), span.to);
  5346. if (side == 1) { return to }
  5347. }
  5348. }
  5349. return from && {from: from, to: to}
  5350. };
  5351. // Signals that the marker's widget changed, and surrounding layout
  5352. // should be recomputed.
  5353. TextMarker.prototype.changed = function () {
  5354. var this$1 = this;
  5355. var pos = this.find(-1, true), widget = this, cm = this.doc.cm;
  5356. if (!pos || !cm) { return }
  5357. runInOp(cm, function () {
  5358. var line = pos.line, lineN = lineNo(pos.line);
  5359. var view = findViewForLine(cm, lineN);
  5360. if (view) {
  5361. clearLineMeasurementCacheFor(view);
  5362. cm.curOp.selectionChanged = cm.curOp.forceUpdate = true;
  5363. }
  5364. cm.curOp.updateMaxLine = true;
  5365. if (!lineIsHidden(widget.doc, line) && widget.height != null) {
  5366. var oldHeight = widget.height;
  5367. widget.height = null;
  5368. var dHeight = widgetHeight(widget) - oldHeight;
  5369. if (dHeight)
  5370. { updateLineHeight(line, line.height + dHeight); }
  5371. }
  5372. signalLater(cm, "markerChanged", cm, this$1);
  5373. });
  5374. };
  5375. TextMarker.prototype.attachLine = function (line) {
  5376. if (!this.lines.length && this.doc.cm) {
  5377. var op = this.doc.cm.curOp;
  5378. if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1)
  5379. { (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this); }
  5380. }
  5381. this.lines.push(line);
  5382. };
  5383. TextMarker.prototype.detachLine = function (line) {
  5384. this.lines.splice(indexOf(this.lines, line), 1);
  5385. if (!this.lines.length && this.doc.cm) {
  5386. var op = this.doc.cm.curOp
  5387. ;(op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this);
  5388. }
  5389. };
  5390. eventMixin(TextMarker);
  5391. // Create a marker, wire it up to the right lines, and
  5392. function markText(doc, from, to, options, type) {
  5393. // Shared markers (across linked documents) are handled separately
  5394. // (markTextShared will call out to this again, once per
  5395. // document).
  5396. if (options && options.shared) { return markTextShared(doc, from, to, options, type) }
  5397. // Ensure we are in an operation.
  5398. if (doc.cm && !doc.cm.curOp) { return operation(doc.cm, markText)(doc, from, to, options, type) }
  5399. var marker = new TextMarker(doc, type), diff = cmp(from, to);
  5400. if (options) { copyObj(options, marker, false); }
  5401. // Don't connect empty markers unless clearWhenEmpty is false
  5402. if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false)
  5403. { return marker }
  5404. if (marker.replacedWith) {
  5405. // Showing up as a widget implies collapsed (widget replaces text)
  5406. marker.collapsed = true;
  5407. marker.widgetNode = eltP("span", [marker.replacedWith], "CodeMirror-widget");
  5408. if (!options.handleMouseEvents) { marker.widgetNode.setAttribute("cm-ignore-events", "true"); }
  5409. if (options.insertLeft) { marker.widgetNode.insertLeft = true; }
  5410. }
  5411. if (marker.collapsed) {
  5412. if (conflictingCollapsedRange(doc, from.line, from, to, marker) ||
  5413. from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker))
  5414. { throw new Error("Inserting collapsed marker partially overlapping an existing one") }
  5415. seeCollapsedSpans();
  5416. }
  5417. if (marker.addToHistory)
  5418. { addChangeToHistory(doc, {from: from, to: to, origin: "markText"}, doc.sel, NaN); }
  5419. var curLine = from.line, cm = doc.cm, updateMaxLine;
  5420. doc.iter(curLine, to.line + 1, function (line) {
  5421. if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine)
  5422. { updateMaxLine = true; }
  5423. if (marker.collapsed && curLine != from.line) { updateLineHeight(line, 0); }
  5424. addMarkedSpan(line, new MarkedSpan(marker,
  5425. curLine == from.line ? from.ch : null,
  5426. curLine == to.line ? to.ch : null), doc.cm && doc.cm.curOp);
  5427. ++curLine;
  5428. });
  5429. // lineIsHidden depends on the presence of the spans, so needs a second pass
  5430. if (marker.collapsed) { doc.iter(from.line, to.line + 1, function (line) {
  5431. if (lineIsHidden(doc, line)) { updateLineHeight(line, 0); }
  5432. }); }
  5433. if (marker.clearOnEnter) { on(marker, "beforeCursorEnter", function () { return marker.clear(); }); }
  5434. if (marker.readOnly) {
  5435. seeReadOnlySpans();
  5436. if (doc.history.done.length || doc.history.undone.length)
  5437. { doc.clearHistory(); }
  5438. }
  5439. if (marker.collapsed) {
  5440. marker.id = ++nextMarkerId;
  5441. marker.atomic = true;
  5442. }
  5443. if (cm) {
  5444. // Sync editor state
  5445. if (updateMaxLine) { cm.curOp.updateMaxLine = true; }
  5446. if (marker.collapsed)
  5447. { regChange(cm, from.line, to.line + 1); }
  5448. else if (marker.className || marker.startStyle || marker.endStyle || marker.css ||
  5449. marker.attributes || marker.title)
  5450. { for (var i = from.line; i <= to.line; i++) { regLineChange(cm, i, "text"); } }
  5451. if (marker.atomic) { reCheckSelection(cm.doc); }
  5452. signalLater(cm, "markerAdded", cm, marker);
  5453. }
  5454. return marker
  5455. }
  5456. // SHARED TEXTMARKERS
  5457. // A shared marker spans multiple linked documents. It is
  5458. // implemented as a meta-marker-object controlling multiple normal
  5459. // markers.
  5460. var SharedTextMarker = function(markers, primary) {
  5461. this.markers = markers;
  5462. this.primary = primary;
  5463. for (var i = 0; i < markers.length; ++i)
  5464. { markers[i].parent = this; }
  5465. };
  5466. SharedTextMarker.prototype.clear = function () {
  5467. if (this.explicitlyCleared) { return }
  5468. this.explicitlyCleared = true;
  5469. for (var i = 0; i < this.markers.length; ++i)
  5470. { this.markers[i].clear(); }
  5471. signalLater(this, "clear");
  5472. };
  5473. SharedTextMarker.prototype.find = function (side, lineObj) {
  5474. return this.primary.find(side, lineObj)
  5475. };
  5476. eventMixin(SharedTextMarker);
  5477. function markTextShared(doc, from, to, options, type) {
  5478. options = copyObj(options);
  5479. options.shared = false;
  5480. var markers = [markText(doc, from, to, options, type)], primary = markers[0];
  5481. var widget = options.widgetNode;
  5482. linkedDocs(doc, function (doc) {
  5483. if (widget) { options.widgetNode = widget.cloneNode(true); }
  5484. markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type));
  5485. for (var i = 0; i < doc.linked.length; ++i)
  5486. { if (doc.linked[i].isParent) { return } }
  5487. primary = lst(markers);
  5488. });
  5489. return new SharedTextMarker(markers, primary)
  5490. }
  5491. function findSharedMarkers(doc) {
  5492. return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())), function (m) { return m.parent; })
  5493. }
  5494. function copySharedMarkers(doc, markers) {
  5495. for (var i = 0; i < markers.length; i++) {
  5496. var marker = markers[i], pos = marker.find();
  5497. var mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to);
  5498. if (cmp(mFrom, mTo)) {
  5499. var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type);
  5500. marker.markers.push(subMark);
  5501. subMark.parent = marker;
  5502. }
  5503. }
  5504. }
  5505. function detachSharedMarkers(markers) {
  5506. var loop = function ( i ) {
  5507. var marker = markers[i], linked = [marker.primary.doc];
  5508. linkedDocs(marker.primary.doc, function (d) { return linked.push(d); });
  5509. for (var j = 0; j < marker.markers.length; j++) {
  5510. var subMarker = marker.markers[j];
  5511. if (indexOf(linked, subMarker.doc) == -1) {
  5512. subMarker.parent = null;
  5513. marker.markers.splice(j--, 1);
  5514. }
  5515. }
  5516. };
  5517. for (var i = 0; i < markers.length; i++) loop( i );
  5518. }
  5519. var nextDocId = 0;
  5520. var Doc = function(text, mode, firstLine, lineSep, direction) {
  5521. if (!(this instanceof Doc)) { return new Doc(text, mode, firstLine, lineSep, direction) }
  5522. if (firstLine == null) { firstLine = 0; }
  5523. BranchChunk.call(this, [new LeafChunk([new Line("", null)])]);
  5524. this.first = firstLine;
  5525. this.scrollTop = this.scrollLeft = 0;
  5526. this.cantEdit = false;
  5527. this.cleanGeneration = 1;
  5528. this.modeFrontier = this.highlightFrontier = firstLine;
  5529. var start = Pos(firstLine, 0);
  5530. this.sel = simpleSelection(start);
  5531. this.history = new History(null);
  5532. this.id = ++nextDocId;
  5533. this.modeOption = mode;
  5534. this.lineSep = lineSep;
  5535. this.direction = (direction == "rtl") ? "rtl" : "ltr";
  5536. this.extend = false;
  5537. if (typeof text == "string") { text = this.splitLines(text); }
  5538. updateDoc(this, {from: start, to: start, text: text});
  5539. setSelection(this, simpleSelection(start), sel_dontScroll);
  5540. };
  5541. Doc.prototype = createObj(BranchChunk.prototype, {
  5542. constructor: Doc,
  5543. // Iterate over the document. Supports two forms -- with only one
  5544. // argument, it calls that for each line in the document. With
  5545. // three, it iterates over the range given by the first two (with
  5546. // the second being non-inclusive).
  5547. iter: function(from, to, op) {
  5548. if (op) { this.iterN(from - this.first, to - from, op); }
  5549. else { this.iterN(this.first, this.first + this.size, from); }
  5550. },
  5551. // Non-public interface for adding and removing lines.
  5552. insert: function(at, lines) {
  5553. var height = 0;
  5554. for (var i = 0; i < lines.length; ++i) { height += lines[i].height; }
  5555. this.insertInner(at - this.first, lines, height);
  5556. },
  5557. remove: function(at, n) { this.removeInner(at - this.first, n); },
  5558. // From here, the methods are part of the public interface. Most
  5559. // are also available from CodeMirror (editor) instances.
  5560. getValue: function(lineSep) {
  5561. var lines = getLines(this, this.first, this.first + this.size);
  5562. if (lineSep === false) { return lines }
  5563. return lines.join(lineSep || this.lineSeparator())
  5564. },
  5565. setValue: docMethodOp(function(code) {
  5566. var top = Pos(this.first, 0), last = this.first + this.size - 1;
  5567. makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length),
  5568. text: this.splitLines(code), origin: "setValue", full: true}, true);
  5569. if (this.cm) { scrollToCoords(this.cm, 0, 0); }
  5570. setSelection(this, simpleSelection(top), sel_dontScroll);
  5571. }),
  5572. replaceRange: function(code, from, to, origin) {
  5573. from = clipPos(this, from);
  5574. to = to ? clipPos(this, to) : from;
  5575. replaceRange(this, code, from, to, origin);
  5576. },
  5577. getRange: function(from, to, lineSep) {
  5578. var lines = getBetween(this, clipPos(this, from), clipPos(this, to));
  5579. if (lineSep === false) { return lines }
  5580. if (lineSep === '') { return lines.join('') }
  5581. return lines.join(lineSep || this.lineSeparator())
  5582. },
  5583. getLine: function(line) {var l = this.getLineHandle(line); return l && l.text},
  5584. getLineHandle: function(line) {if (isLine(this, line)) { return getLine(this, line) }},
  5585. getLineNumber: function(line) {return lineNo(line)},
  5586. getLineHandleVisualStart: function(line) {
  5587. if (typeof line == "number") { line = getLine(this, line); }
  5588. return visualLine(line)
  5589. },
  5590. lineCount: function() {return this.size},
  5591. firstLine: function() {return this.first},
  5592. lastLine: function() {return this.first + this.size - 1},
  5593. clipPos: function(pos) {return clipPos(this, pos)},
  5594. getCursor: function(start) {
  5595. var range = this.sel.primary(), pos;
  5596. if (start == null || start == "head") { pos = range.head; }
  5597. else if (start == "anchor") { pos = range.anchor; }
  5598. else if (start == "end" || start == "to" || start === false) { pos = range.to(); }
  5599. else { pos = range.from(); }
  5600. return pos
  5601. },
  5602. listSelections: function() { return this.sel.ranges },
  5603. somethingSelected: function() {return this.sel.somethingSelected()},
  5604. setCursor: docMethodOp(function(line, ch, options) {
  5605. setSimpleSelection(this, clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line), null, options);
  5606. }),
  5607. setSelection: docMethodOp(function(anchor, head, options) {
  5608. setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options);
  5609. }),
  5610. extendSelection: docMethodOp(function(head, other, options) {
  5611. extendSelection(this, clipPos(this, head), other && clipPos(this, other), options);
  5612. }),
  5613. extendSelections: docMethodOp(function(heads, options) {
  5614. extendSelections(this, clipPosArray(this, heads), options);
  5615. }),
  5616. extendSelectionsBy: docMethodOp(function(f, options) {
  5617. var heads = map(this.sel.ranges, f);
  5618. extendSelections(this, clipPosArray(this, heads), options);
  5619. }),
  5620. setSelections: docMethodOp(function(ranges, primary, options) {
  5621. if (!ranges.length) { return }
  5622. var out = [];
  5623. for (var i = 0; i < ranges.length; i++)
  5624. { out[i] = new Range(clipPos(this, ranges[i].anchor),
  5625. clipPos(this, ranges[i].head || ranges[i].anchor)); }
  5626. if (primary == null) { primary = Math.min(ranges.length - 1, this.sel.primIndex); }
  5627. setSelection(this, normalizeSelection(this.cm, out, primary), options);
  5628. }),
  5629. addSelection: docMethodOp(function(anchor, head, options) {
  5630. var ranges = this.sel.ranges.slice(0);
  5631. ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor)));
  5632. setSelection(this, normalizeSelection(this.cm, ranges, ranges.length - 1), options);
  5633. }),
  5634. getSelection: function(lineSep) {
  5635. var ranges = this.sel.ranges, lines;
  5636. for (var i = 0; i < ranges.length; i++) {
  5637. var sel = getBetween(this, ranges[i].from(), ranges[i].to());
  5638. lines = lines ? lines.concat(sel) : sel;
  5639. }
  5640. if (lineSep === false) { return lines }
  5641. else { return lines.join(lineSep || this.lineSeparator()) }
  5642. },
  5643. getSelections: function(lineSep) {
  5644. var parts = [], ranges = this.sel.ranges;
  5645. for (var i = 0; i < ranges.length; i++) {
  5646. var sel = getBetween(this, ranges[i].from(), ranges[i].to());
  5647. if (lineSep !== false) { sel = sel.join(lineSep || this.lineSeparator()); }
  5648. parts[i] = sel;
  5649. }
  5650. return parts
  5651. },
  5652. replaceSelection: function(code, collapse, origin) {
  5653. var dup = [];
  5654. for (var i = 0; i < this.sel.ranges.length; i++)
  5655. { dup[i] = code; }
  5656. this.replaceSelections(dup, collapse, origin || "+input");
  5657. },
  5658. replaceSelections: docMethodOp(function(code, collapse, origin) {
  5659. var changes = [], sel = this.sel;
  5660. for (var i = 0; i < sel.ranges.length; i++) {
  5661. var range = sel.ranges[i];
  5662. changes[i] = {from: range.from(), to: range.to(), text: this.splitLines(code[i]), origin: origin};
  5663. }
  5664. var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse);
  5665. for (var i$1 = changes.length - 1; i$1 >= 0; i$1--)
  5666. { makeChange(this, changes[i$1]); }
  5667. if (newSel) { setSelectionReplaceHistory(this, newSel); }
  5668. else if (this.cm) { ensureCursorVisible(this.cm); }
  5669. }),
  5670. undo: docMethodOp(function() {makeChangeFromHistory(this, "undo");}),
  5671. redo: docMethodOp(function() {makeChangeFromHistory(this, "redo");}),
  5672. undoSelection: docMethodOp(function() {makeChangeFromHistory(this, "undo", true);}),
  5673. redoSelection: docMethodOp(function() {makeChangeFromHistory(this, "redo", true);}),
  5674. setExtending: function(val) {this.extend = val;},
  5675. getExtending: function() {return this.extend},
  5676. historySize: function() {
  5677. var hist = this.history, done = 0, undone = 0;
  5678. for (var i = 0; i < hist.done.length; i++) { if (!hist.done[i].ranges) { ++done; } }
  5679. for (var i$1 = 0; i$1 < hist.undone.length; i$1++) { if (!hist.undone[i$1].ranges) { ++undone; } }
  5680. return {undo: done, redo: undone}
  5681. },
  5682. clearHistory: function() {
  5683. var this$1 = this;
  5684. this.history = new History(this.history);
  5685. linkedDocs(this, function (doc) { return doc.history = this$1.history; }, true);
  5686. },
  5687. markClean: function() {
  5688. this.cleanGeneration = this.changeGeneration(true);
  5689. },
  5690. changeGeneration: function(forceSplit) {
  5691. if (forceSplit)
  5692. { this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null; }
  5693. return this.history.generation
  5694. },
  5695. isClean: function (gen) {
  5696. return this.history.generation == (gen || this.cleanGeneration)
  5697. },
  5698. getHistory: function() {
  5699. return {done: copyHistoryArray(this.history.done),
  5700. undone: copyHistoryArray(this.history.undone)}
  5701. },
  5702. setHistory: function(histData) {
  5703. var hist = this.history = new History(this.history);
  5704. hist.done = copyHistoryArray(histData.done.slice(0), null, true);
  5705. hist.undone = copyHistoryArray(histData.undone.slice(0), null, true);
  5706. },
  5707. setGutterMarker: docMethodOp(function(line, gutterID, value) {
  5708. return changeLine(this, line, "gutter", function (line) {
  5709. var markers = line.gutterMarkers || (line.gutterMarkers = {});
  5710. markers[gutterID] = value;
  5711. if (!value && isEmpty(markers)) { line.gutterMarkers = null; }
  5712. return true
  5713. })
  5714. }),
  5715. clearGutter: docMethodOp(function(gutterID) {
  5716. var this$1 = this;
  5717. this.iter(function (line) {
  5718. if (line.gutterMarkers && line.gutterMarkers[gutterID]) {
  5719. changeLine(this$1, line, "gutter", function () {
  5720. line.gutterMarkers[gutterID] = null;
  5721. if (isEmpty(line.gutterMarkers)) { line.gutterMarkers = null; }
  5722. return true
  5723. });
  5724. }
  5725. });
  5726. }),
  5727. lineInfo: function(line) {
  5728. var n;
  5729. if (typeof line == "number") {
  5730. if (!isLine(this, line)) { return null }
  5731. n = line;
  5732. line = getLine(this, line);
  5733. if (!line) { return null }
  5734. } else {
  5735. n = lineNo(line);
  5736. if (n == null) { return null }
  5737. }
  5738. return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers,
  5739. textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass,
  5740. widgets: line.widgets}
  5741. },
  5742. addLineClass: docMethodOp(function(handle, where, cls) {
  5743. return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) {
  5744. var prop = where == "text" ? "textClass"
  5745. : where == "background" ? "bgClass"
  5746. : where == "gutter" ? "gutterClass" : "wrapClass";
  5747. if (!line[prop]) { line[prop] = cls; }
  5748. else if (classTest(cls).test(line[prop])) { return false }
  5749. else { line[prop] += " " + cls; }
  5750. return true
  5751. })
  5752. }),
  5753. removeLineClass: docMethodOp(function(handle, where, cls) {
  5754. return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) {
  5755. var prop = where == "text" ? "textClass"
  5756. : where == "background" ? "bgClass"
  5757. : where == "gutter" ? "gutterClass" : "wrapClass";
  5758. var cur = line[prop];
  5759. if (!cur) { return false }
  5760. else if (cls == null) { line[prop] = null; }
  5761. else {
  5762. var found = cur.match(classTest(cls));
  5763. if (!found) { return false }
  5764. var end = found.index + found[0].length;
  5765. line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null;
  5766. }
  5767. return true
  5768. })
  5769. }),
  5770. addLineWidget: docMethodOp(function(handle, node, options) {
  5771. return addLineWidget(this, handle, node, options)
  5772. }),
  5773. removeLineWidget: function(widget) { widget.clear(); },
  5774. markText: function(from, to, options) {
  5775. return markText(this, clipPos(this, from), clipPos(this, to), options, options && options.type || "range")
  5776. },
  5777. setBookmark: function(pos, options) {
  5778. var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options),
  5779. insertLeft: options && options.insertLeft,
  5780. clearWhenEmpty: false, shared: options && options.shared,
  5781. handleMouseEvents: options && options.handleMouseEvents};
  5782. pos = clipPos(this, pos);
  5783. return markText(this, pos, pos, realOpts, "bookmark")
  5784. },
  5785. findMarksAt: function(pos) {
  5786. pos = clipPos(this, pos);
  5787. var markers = [], spans = getLine(this, pos.line).markedSpans;
  5788. if (spans) { for (var i = 0; i < spans.length; ++i) {
  5789. var span = spans[i];
  5790. if ((span.from == null || span.from <= pos.ch) &&
  5791. (span.to == null || span.to >= pos.ch))
  5792. { markers.push(span.marker.parent || span.marker); }
  5793. } }
  5794. return markers
  5795. },
  5796. findMarks: function(from, to, filter) {
  5797. from = clipPos(this, from); to = clipPos(this, to);
  5798. var found = [], lineNo = from.line;
  5799. this.iter(from.line, to.line + 1, function (line) {
  5800. var spans = line.markedSpans;
  5801. if (spans) { for (var i = 0; i < spans.length; i++) {
  5802. var span = spans[i];
  5803. if (!(span.to != null && lineNo == from.line && from.ch >= span.to ||
  5804. span.from == null && lineNo != from.line ||
  5805. span.from != null && lineNo == to.line && span.from >= to.ch) &&
  5806. (!filter || filter(span.marker)))
  5807. { found.push(span.marker.parent || span.marker); }
  5808. } }
  5809. ++lineNo;
  5810. });
  5811. return found
  5812. },
  5813. getAllMarks: function() {
  5814. var markers = [];
  5815. this.iter(function (line) {
  5816. var sps = line.markedSpans;
  5817. if (sps) { for (var i = 0; i < sps.length; ++i)
  5818. { if (sps[i].from != null) { markers.push(sps[i].marker); } } }
  5819. });
  5820. return markers
  5821. },
  5822. posFromIndex: function(off) {
  5823. var ch, lineNo = this.first, sepSize = this.lineSeparator().length;
  5824. this.iter(function (line) {
  5825. var sz = line.text.length + sepSize;
  5826. if (sz > off) { ch = off; return true }
  5827. off -= sz;
  5828. ++lineNo;
  5829. });
  5830. return clipPos(this, Pos(lineNo, ch))
  5831. },
  5832. indexFromPos: function (coords) {
  5833. coords = clipPos(this, coords);
  5834. var index = coords.ch;
  5835. if (coords.line < this.first || coords.ch < 0) { return 0 }
  5836. var sepSize = this.lineSeparator().length;
  5837. this.iter(this.first, coords.line, function (line) { // iter aborts when callback returns a truthy value
  5838. index += line.text.length + sepSize;
  5839. });
  5840. return index
  5841. },
  5842. copy: function(copyHistory) {
  5843. var doc = new Doc(getLines(this, this.first, this.first + this.size),
  5844. this.modeOption, this.first, this.lineSep, this.direction);
  5845. doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft;
  5846. doc.sel = this.sel;
  5847. doc.extend = false;
  5848. if (copyHistory) {
  5849. doc.history.undoDepth = this.history.undoDepth;
  5850. doc.setHistory(this.getHistory());
  5851. }
  5852. return doc
  5853. },
  5854. linkedDoc: function(options) {
  5855. if (!options) { options = {}; }
  5856. var from = this.first, to = this.first + this.size;
  5857. if (options.from != null && options.from > from) { from = options.from; }
  5858. if (options.to != null && options.to < to) { to = options.to; }
  5859. var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from, this.lineSep, this.direction);
  5860. if (options.sharedHist) { copy.history = this.history
  5861. ; }(this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist});
  5862. copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}];
  5863. copySharedMarkers(copy, findSharedMarkers(this));
  5864. return copy
  5865. },
  5866. unlinkDoc: function(other) {
  5867. if (other instanceof CodeMirror) { other = other.doc; }
  5868. if (this.linked) { for (var i = 0; i < this.linked.length; ++i) {
  5869. var link = this.linked[i];
  5870. if (link.doc != other) { continue }
  5871. this.linked.splice(i, 1);
  5872. other.unlinkDoc(this);
  5873. detachSharedMarkers(findSharedMarkers(this));
  5874. break
  5875. } }
  5876. // If the histories were shared, split them again
  5877. if (other.history == this.history) {
  5878. var splitIds = [other.id];
  5879. linkedDocs(other, function (doc) { return splitIds.push(doc.id); }, true);
  5880. other.history = new History(null);
  5881. other.history.done = copyHistoryArray(this.history.done, splitIds);
  5882. other.history.undone = copyHistoryArray(this.history.undone, splitIds);
  5883. }
  5884. },
  5885. iterLinkedDocs: function(f) {linkedDocs(this, f);},
  5886. getMode: function() {return this.mode},
  5887. getEditor: function() {return this.cm},
  5888. splitLines: function(str) {
  5889. if (this.lineSep) { return str.split(this.lineSep) }
  5890. return splitLinesAuto(str)
  5891. },
  5892. lineSeparator: function() { return this.lineSep || "\n" },
  5893. setDirection: docMethodOp(function (dir) {
  5894. if (dir != "rtl") { dir = "ltr"; }
  5895. if (dir == this.direction) { return }
  5896. this.direction = dir;
  5897. this.iter(function (line) { return line.order = null; });
  5898. if (this.cm) { directionChanged(this.cm); }
  5899. })
  5900. });
  5901. // Public alias.
  5902. Doc.prototype.eachLine = Doc.prototype.iter;
  5903. // Kludge to work around strange IE behavior where it'll sometimes
  5904. // re-fire a series of drag-related events right after the drop (#1551)
  5905. var lastDrop = 0;
  5906. function onDrop(e) {
  5907. var cm = this;
  5908. clearDragCursor(cm);
  5909. if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e))
  5910. { return }
  5911. e_preventDefault(e);
  5912. if (ie) { lastDrop = +new Date; }
  5913. var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files;
  5914. if (!pos || cm.isReadOnly()) { return }
  5915. // Might be a file drop, in which case we simply extract the text
  5916. // and insert it.
  5917. if (files && files.length && window.FileReader && window.File) {
  5918. var n = files.length, text = Array(n), read = 0;
  5919. var markAsReadAndPasteIfAllFilesAreRead = function () {
  5920. if (++read == n) {
  5921. operation(cm, function () {
  5922. pos = clipPos(cm.doc, pos);
  5923. var change = {from: pos, to: pos,
  5924. text: cm.doc.splitLines(
  5925. text.filter(function (t) { return t != null; }).join(cm.doc.lineSeparator())),
  5926. origin: "paste"};
  5927. makeChange(cm.doc, change);
  5928. setSelectionReplaceHistory(cm.doc, simpleSelection(clipPos(cm.doc, pos), clipPos(cm.doc, changeEnd(change))));
  5929. })();
  5930. }
  5931. };
  5932. var readTextFromFile = function (file, i) {
  5933. if (cm.options.allowDropFileTypes &&
  5934. indexOf(cm.options.allowDropFileTypes, file.type) == -1) {
  5935. markAsReadAndPasteIfAllFilesAreRead();
  5936. return
  5937. }
  5938. var reader = new FileReader;
  5939. reader.onerror = function () { return markAsReadAndPasteIfAllFilesAreRead(); };
  5940. reader.onload = function () {
  5941. var content = reader.result;
  5942. if (/[\x00-\x08\x0e-\x1f]{2}/.test(content)) {
  5943. markAsReadAndPasteIfAllFilesAreRead();
  5944. return
  5945. }
  5946. text[i] = content;
  5947. markAsReadAndPasteIfAllFilesAreRead();
  5948. };
  5949. reader.readAsText(file);
  5950. };
  5951. for (var i = 0; i < files.length; i++) { readTextFromFile(files[i], i); }
  5952. } else { // Normal drop
  5953. // Don't do a replace if the drop happened inside of the selected text.
  5954. if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) {
  5955. cm.state.draggingText(e);
  5956. // Ensure the editor is re-focused
  5957. setTimeout(function () { return cm.display.input.focus(); }, 20);
  5958. return
  5959. }
  5960. try {
  5961. var text$1 = e.dataTransfer.getData("Text");
  5962. if (text$1) {
  5963. var selected;
  5964. if (cm.state.draggingText && !cm.state.draggingText.copy)
  5965. { selected = cm.listSelections(); }
  5966. setSelectionNoUndo(cm.doc, simpleSelection(pos, pos));
  5967. if (selected) { for (var i$1 = 0; i$1 < selected.length; ++i$1)
  5968. { replaceRange(cm.doc, "", selected[i$1].anchor, selected[i$1].head, "drag"); } }
  5969. cm.replaceSelection(text$1, "around", "paste");
  5970. cm.display.input.focus();
  5971. }
  5972. }
  5973. catch(e$1){}
  5974. }
  5975. }
  5976. function onDragStart(cm, e) {
  5977. if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return }
  5978. if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) { return }
  5979. e.dataTransfer.setData("Text", cm.getSelection());
  5980. e.dataTransfer.effectAllowed = "copyMove";
  5981. // Use dummy image instead of default browsers image.
  5982. // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there.
  5983. if (e.dataTransfer.setDragImage && !safari) {
  5984. var img = elt("img", null, null, "position: fixed; left: 0; top: 0;");
  5985. img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";
  5986. if (presto) {
  5987. img.width = img.height = 1;
  5988. cm.display.wrapper.appendChild(img);
  5989. // Force a relayout, or Opera won't use our image for some obscure reason
  5990. img._top = img.offsetTop;
  5991. }
  5992. e.dataTransfer.setDragImage(img, 0, 0);
  5993. if (presto) { img.parentNode.removeChild(img); }
  5994. }
  5995. }
  5996. function onDragOver(cm, e) {
  5997. var pos = posFromMouse(cm, e);
  5998. if (!pos) { return }
  5999. var frag = document.createDocumentFragment();
  6000. drawSelectionCursor(cm, pos, frag);
  6001. if (!cm.display.dragCursor) {
  6002. cm.display.dragCursor = elt("div", null, "CodeMirror-cursors CodeMirror-dragcursors");
  6003. cm.display.lineSpace.insertBefore(cm.display.dragCursor, cm.display.cursorDiv);
  6004. }
  6005. removeChildrenAndAdd(cm.display.dragCursor, frag);
  6006. }
  6007. function clearDragCursor(cm) {
  6008. if (cm.display.dragCursor) {
  6009. cm.display.lineSpace.removeChild(cm.display.dragCursor);
  6010. cm.display.dragCursor = null;
  6011. }
  6012. }
  6013. // These must be handled carefully, because naively registering a
  6014. // handler for each editor will cause the editors to never be
  6015. // garbage collected.
  6016. function forEachCodeMirror(f) {
  6017. if (!document.getElementsByClassName) { return }
  6018. var byClass = document.getElementsByClassName("CodeMirror"), editors = [];
  6019. for (var i = 0; i < byClass.length; i++) {
  6020. var cm = byClass[i].CodeMirror;
  6021. if (cm) { editors.push(cm); }
  6022. }
  6023. if (editors.length) { editors[0].operation(function () {
  6024. for (var i = 0; i < editors.length; i++) { f(editors[i]); }
  6025. }); }
  6026. }
  6027. var globalsRegistered = false;
  6028. function ensureGlobalHandlers() {
  6029. if (globalsRegistered) { return }
  6030. registerGlobalHandlers();
  6031. globalsRegistered = true;
  6032. }
  6033. function registerGlobalHandlers() {
  6034. // When the window resizes, we need to refresh active editors.
  6035. var resizeTimer;
  6036. on(window, "resize", function () {
  6037. if (resizeTimer == null) { resizeTimer = setTimeout(function () {
  6038. resizeTimer = null;
  6039. forEachCodeMirror(onResize);
  6040. }, 100); }
  6041. });
  6042. // When the window loses focus, we want to show the editor as blurred
  6043. on(window, "blur", function () { return forEachCodeMirror(onBlur); });
  6044. }
  6045. // Called when the window resizes
  6046. function onResize(cm) {
  6047. var d = cm.display;
  6048. // Might be a text scaling operation, clear size caches.
  6049. d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
  6050. d.scrollbarsClipped = false;
  6051. cm.setSize();
  6052. }
  6053. var keyNames = {
  6054. 3: "Pause", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt",
  6055. 19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End",
  6056. 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert",
  6057. 46: "Delete", 59: ";", 61: "=", 91: "Mod", 92: "Mod", 93: "Mod",
  6058. 106: "*", 107: "=", 109: "-", 110: ".", 111: "/", 145: "ScrollLock",
  6059. 173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\",
  6060. 221: "]", 222: "'", 224: "Mod", 63232: "Up", 63233: "Down", 63234: "Left", 63235: "Right", 63272: "Delete",
  6061. 63273: "Home", 63275: "End", 63276: "PageUp", 63277: "PageDown", 63302: "Insert"
  6062. };
  6063. // Number keys
  6064. for (var i = 0; i < 10; i++) { keyNames[i + 48] = keyNames[i + 96] = String(i); }
  6065. // Alphabetic keys
  6066. for (var i$1 = 65; i$1 <= 90; i$1++) { keyNames[i$1] = String.fromCharCode(i$1); }
  6067. // Function keys
  6068. for (var i$2 = 1; i$2 <= 12; i$2++) { keyNames[i$2 + 111] = keyNames[i$2 + 63235] = "F" + i$2; }
  6069. var keyMap = {};
  6070. keyMap.basic = {
  6071. "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown",
  6072. "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown",
  6073. "Delete": "delCharAfter", "Backspace": "delCharBefore", "Shift-Backspace": "delCharBefore",
  6074. "Tab": "defaultTab", "Shift-Tab": "indentAuto",
  6075. "Enter": "newlineAndIndent", "Insert": "toggleOverwrite",
  6076. "Esc": "singleSelection"
  6077. };
  6078. // Note that the save and find-related commands aren't defined by
  6079. // default. User code or addons can define them. Unknown commands
  6080. // are simply ignored.
  6081. keyMap.pcDefault = {
  6082. "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo",
  6083. "Ctrl-Home": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Up": "goLineUp", "Ctrl-Down": "goLineDown",
  6084. "Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd",
  6085. "Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find",
  6086. "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll",
  6087. "Ctrl-[": "indentLess", "Ctrl-]": "indentMore",
  6088. "Ctrl-U": "undoSelection", "Shift-Ctrl-U": "redoSelection", "Alt-U": "redoSelection",
  6089. "fallthrough": "basic"
  6090. };
  6091. // Very basic readline/emacs-style bindings, which are standard on Mac.
  6092. keyMap.emacsy = {
  6093. "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown",
  6094. "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd", "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp",
  6095. "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine",
  6096. "Ctrl-T": "transposeChars", "Ctrl-O": "openLine"
  6097. };
  6098. keyMap.macDefault = {
  6099. "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo",
  6100. "Cmd-Home": "goDocStart", "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft",
  6101. "Alt-Right": "goGroupRight", "Cmd-Left": "goLineLeft", "Cmd-Right": "goLineRight", "Alt-Backspace": "delGroupBefore",
  6102. "Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find",
  6103. "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll",
  6104. "Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delWrappedLineLeft", "Cmd-Delete": "delWrappedLineRight",
  6105. "Cmd-U": "undoSelection", "Shift-Cmd-U": "redoSelection", "Ctrl-Up": "goDocStart", "Ctrl-Down": "goDocEnd",
  6106. "fallthrough": ["basic", "emacsy"]
  6107. };
  6108. keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault;
  6109. // KEYMAP DISPATCH
  6110. function normalizeKeyName(name) {
  6111. var parts = name.split(/-(?!$)/);
  6112. name = parts[parts.length - 1];
  6113. var alt, ctrl, shift, cmd;
  6114. for (var i = 0; i < parts.length - 1; i++) {
  6115. var mod = parts[i];
  6116. if (/^(cmd|meta|m)$/i.test(mod)) { cmd = true; }
  6117. else if (/^a(lt)?$/i.test(mod)) { alt = true; }
  6118. else if (/^(c|ctrl|control)$/i.test(mod)) { ctrl = true; }
  6119. else if (/^s(hift)?$/i.test(mod)) { shift = true; }
  6120. else { throw new Error("Unrecognized modifier name: " + mod) }
  6121. }
  6122. if (alt) { name = "Alt-" + name; }
  6123. if (ctrl) { name = "Ctrl-" + name; }
  6124. if (cmd) { name = "Cmd-" + name; }
  6125. if (shift) { name = "Shift-" + name; }
  6126. return name
  6127. }
  6128. // This is a kludge to keep keymaps mostly working as raw objects
  6129. // (backwards compatibility) while at the same time support features
  6130. // like normalization and multi-stroke key bindings. It compiles a
  6131. // new normalized keymap, and then updates the old object to reflect
  6132. // this.
  6133. function normalizeKeyMap(keymap) {
  6134. var copy = {};
  6135. for (var keyname in keymap) { if (keymap.hasOwnProperty(keyname)) {
  6136. var value = keymap[keyname];
  6137. if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) { continue }
  6138. if (value == "...") { delete keymap[keyname]; continue }
  6139. var keys = map(keyname.split(" "), normalizeKeyName);
  6140. for (var i = 0; i < keys.length; i++) {
  6141. var val = (void 0), name = (void 0);
  6142. if (i == keys.length - 1) {
  6143. name = keys.join(" ");
  6144. val = value;
  6145. } else {
  6146. name = keys.slice(0, i + 1).join(" ");
  6147. val = "...";
  6148. }
  6149. var prev = copy[name];
  6150. if (!prev) { copy[name] = val; }
  6151. else if (prev != val) { throw new Error("Inconsistent bindings for " + name) }
  6152. }
  6153. delete keymap[keyname];
  6154. } }
  6155. for (var prop in copy) { keymap[prop] = copy[prop]; }
  6156. return keymap
  6157. }
  6158. function lookupKey(key, map, handle, context) {
  6159. map = getKeyMap(map);
  6160. var found = map.call ? map.call(key, context) : map[key];
  6161. if (found === false) { return "nothing" }
  6162. if (found === "...") { return "multi" }
  6163. if (found != null && handle(found)) { return "handled" }
  6164. if (map.fallthrough) {
  6165. if (Object.prototype.toString.call(map.fallthrough) != "[object Array]")
  6166. { return lookupKey(key, map.fallthrough, handle, context) }
  6167. for (var i = 0; i < map.fallthrough.length; i++) {
  6168. var result = lookupKey(key, map.fallthrough[i], handle, context);
  6169. if (result) { return result }
  6170. }
  6171. }
  6172. }
  6173. // Modifier key presses don't count as 'real' key presses for the
  6174. // purpose of keymap fallthrough.
  6175. function isModifierKey(value) {
  6176. var name = typeof value == "string" ? value : keyNames[value.keyCode];
  6177. return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod"
  6178. }
  6179. function addModifierNames(name, event, noShift) {
  6180. var base = name;
  6181. if (event.altKey && base != "Alt") { name = "Alt-" + name; }
  6182. if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != "Ctrl") { name = "Ctrl-" + name; }
  6183. if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != "Mod") { name = "Cmd-" + name; }
  6184. if (!noShift && event.shiftKey && base != "Shift") { name = "Shift-" + name; }
  6185. return name
  6186. }
  6187. // Look up the name of a key as indicated by an event object.
  6188. function keyName(event, noShift) {
  6189. if (presto && event.keyCode == 34 && event["char"]) { return false }
  6190. var name = keyNames[event.keyCode];
  6191. if (name == null || event.altGraphKey) { return false }
  6192. // Ctrl-ScrollLock has keyCode 3, same as Ctrl-Pause,
  6193. // so we'll use event.code when available (Chrome 48+, FF 38+, Safari 10.1+)
  6194. if (event.keyCode == 3 && event.code) { name = event.code; }
  6195. return addModifierNames(name, event, noShift)
  6196. }
  6197. function getKeyMap(val) {
  6198. return typeof val == "string" ? keyMap[val] : val
  6199. }
  6200. // Helper for deleting text near the selection(s), used to implement
  6201. // backspace, delete, and similar functionality.
  6202. function deleteNearSelection(cm, compute) {
  6203. var ranges = cm.doc.sel.ranges, kill = [];
  6204. // Build up a set of ranges to kill first, merging overlapping
  6205. // ranges.
  6206. for (var i = 0; i < ranges.length; i++) {
  6207. var toKill = compute(ranges[i]);
  6208. while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) {
  6209. var replaced = kill.pop();
  6210. if (cmp(replaced.from, toKill.from) < 0) {
  6211. toKill.from = replaced.from;
  6212. break
  6213. }
  6214. }
  6215. kill.push(toKill);
  6216. }
  6217. // Next, remove those actual ranges.
  6218. runInOp(cm, function () {
  6219. for (var i = kill.length - 1; i >= 0; i--)
  6220. { replaceRange(cm.doc, "", kill[i].from, kill[i].to, "+delete"); }
  6221. ensureCursorVisible(cm);
  6222. });
  6223. }
  6224. function moveCharLogically(line, ch, dir) {
  6225. var target = skipExtendingChars(line.text, ch + dir, dir);
  6226. return target < 0 || target > line.text.length ? null : target
  6227. }
  6228. function moveLogically(line, start, dir) {
  6229. var ch = moveCharLogically(line, start.ch, dir);
  6230. return ch == null ? null : new Pos(start.line, ch, dir < 0 ? "after" : "before")
  6231. }
  6232. function endOfLine(visually, cm, lineObj, lineNo, dir) {
  6233. if (visually) {
  6234. if (cm.doc.direction == "rtl") { dir = -dir; }
  6235. var order = getOrder(lineObj, cm.doc.direction);
  6236. if (order) {
  6237. var part = dir < 0 ? lst(order) : order[0];
  6238. var moveInStorageOrder = (dir < 0) == (part.level == 1);
  6239. var sticky = moveInStorageOrder ? "after" : "before";
  6240. var ch;
  6241. // With a wrapped rtl chunk (possibly spanning multiple bidi parts),
  6242. // it could be that the last bidi part is not on the last visual line,
  6243. // since visual lines contain content order-consecutive chunks.
  6244. // Thus, in rtl, we are looking for the first (content-order) character
  6245. // in the rtl chunk that is on the last line (that is, the same line
  6246. // as the last (content-order) character).
  6247. if (part.level > 0 || cm.doc.direction == "rtl") {
  6248. var prep = prepareMeasureForLine(cm, lineObj);
  6249. ch = dir < 0 ? lineObj.text.length - 1 : 0;
  6250. var targetTop = measureCharPrepared(cm, prep, ch).top;
  6251. ch = findFirst(function (ch) { return measureCharPrepared(cm, prep, ch).top == targetTop; }, (dir < 0) == (part.level == 1) ? part.from : part.to - 1, ch);
  6252. if (sticky == "before") { ch = moveCharLogically(lineObj, ch, 1); }
  6253. } else { ch = dir < 0 ? part.to : part.from; }
  6254. return new Pos(lineNo, ch, sticky)
  6255. }
  6256. }
  6257. return new Pos(lineNo, dir < 0 ? lineObj.text.length : 0, dir < 0 ? "before" : "after")
  6258. }
  6259. function moveVisually(cm, line, start, dir) {
  6260. var bidi = getOrder(line, cm.doc.direction);
  6261. if (!bidi) { return moveLogically(line, start, dir) }
  6262. if (start.ch >= line.text.length) {
  6263. start.ch = line.text.length;
  6264. start.sticky = "before";
  6265. } else if (start.ch <= 0) {
  6266. start.ch = 0;
  6267. start.sticky = "after";
  6268. }
  6269. var partPos = getBidiPartAt(bidi, start.ch, start.sticky), part = bidi[partPos];
  6270. if (cm.doc.direction == "ltr" && part.level % 2 == 0 && (dir > 0 ? part.to > start.ch : part.from < start.ch)) {
  6271. // Case 1: We move within an ltr part in an ltr editor. Even with wrapped lines,
  6272. // nothing interesting happens.
  6273. return moveLogically(line, start, dir)
  6274. }
  6275. var mv = function (pos, dir) { return moveCharLogically(line, pos instanceof Pos ? pos.ch : pos, dir); };
  6276. var prep;
  6277. var getWrappedLineExtent = function (ch) {
  6278. if (!cm.options.lineWrapping) { return {begin: 0, end: line.text.length} }
  6279. prep = prep || prepareMeasureForLine(cm, line);
  6280. return wrappedLineExtentChar(cm, line, prep, ch)
  6281. };
  6282. var wrappedLineExtent = getWrappedLineExtent(start.sticky == "before" ? mv(start, -1) : start.ch);
  6283. if (cm.doc.direction == "rtl" || part.level == 1) {
  6284. var moveInStorageOrder = (part.level == 1) == (dir < 0);
  6285. var ch = mv(start, moveInStorageOrder ? 1 : -1);
  6286. if (ch != null && (!moveInStorageOrder ? ch >= part.from && ch >= wrappedLineExtent.begin : ch <= part.to && ch <= wrappedLineExtent.end)) {
  6287. // Case 2: We move within an rtl part or in an rtl editor on the same visual line
  6288. var sticky = moveInStorageOrder ? "before" : "after";
  6289. return new Pos(start.line, ch, sticky)
  6290. }
  6291. }
  6292. // Case 3: Could not move within this bidi part in this visual line, so leave
  6293. // the current bidi part
  6294. var searchInVisualLine = function (partPos, dir, wrappedLineExtent) {
  6295. var getRes = function (ch, moveInStorageOrder) { return moveInStorageOrder
  6296. ? new Pos(start.line, mv(ch, 1), "before")
  6297. : new Pos(start.line, ch, "after"); };
  6298. for (; partPos >= 0 && partPos < bidi.length; partPos += dir) {
  6299. var part = bidi[partPos];
  6300. var moveInStorageOrder = (dir > 0) == (part.level != 1);
  6301. var ch = moveInStorageOrder ? wrappedLineExtent.begin : mv(wrappedLineExtent.end, -1);
  6302. if (part.from <= ch && ch < part.to) { return getRes(ch, moveInStorageOrder) }
  6303. ch = moveInStorageOrder ? part.from : mv(part.to, -1);
  6304. if (wrappedLineExtent.begin <= ch && ch < wrappedLineExtent.end) { return getRes(ch, moveInStorageOrder) }
  6305. }
  6306. };
  6307. // Case 3a: Look for other bidi parts on the same visual line
  6308. var res = searchInVisualLine(partPos + dir, dir, wrappedLineExtent);
  6309. if (res) { return res }
  6310. // Case 3b: Look for other bidi parts on the next visual line
  6311. var nextCh = dir > 0 ? wrappedLineExtent.end : mv(wrappedLineExtent.begin, -1);
  6312. if (nextCh != null && !(dir > 0 && nextCh == line.text.length)) {
  6313. res = searchInVisualLine(dir > 0 ? 0 : bidi.length - 1, dir, getWrappedLineExtent(nextCh));
  6314. if (res) { return res }
  6315. }
  6316. // Case 4: Nowhere to move
  6317. return null
  6318. }
  6319. // Commands are parameter-less actions that can be performed on an
  6320. // editor, mostly used for keybindings.
  6321. var commands = {
  6322. selectAll: selectAll,
  6323. singleSelection: function (cm) { return cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll); },
  6324. killLine: function (cm) { return deleteNearSelection(cm, function (range) {
  6325. if (range.empty()) {
  6326. var len = getLine(cm.doc, range.head.line).text.length;
  6327. if (range.head.ch == len && range.head.line < cm.lastLine())
  6328. { return {from: range.head, to: Pos(range.head.line + 1, 0)} }
  6329. else
  6330. { return {from: range.head, to: Pos(range.head.line, len)} }
  6331. } else {
  6332. return {from: range.from(), to: range.to()}
  6333. }
  6334. }); },
  6335. deleteLine: function (cm) { return deleteNearSelection(cm, function (range) { return ({
  6336. from: Pos(range.from().line, 0),
  6337. to: clipPos(cm.doc, Pos(range.to().line + 1, 0))
  6338. }); }); },
  6339. delLineLeft: function (cm) { return deleteNearSelection(cm, function (range) { return ({
  6340. from: Pos(range.from().line, 0), to: range.from()
  6341. }); }); },
  6342. delWrappedLineLeft: function (cm) { return deleteNearSelection(cm, function (range) {
  6343. var top = cm.charCoords(range.head, "div").top + 5;
  6344. var leftPos = cm.coordsChar({left: 0, top: top}, "div");
  6345. return {from: leftPos, to: range.from()}
  6346. }); },
  6347. delWrappedLineRight: function (cm) { return deleteNearSelection(cm, function (range) {
  6348. var top = cm.charCoords(range.head, "div").top + 5;
  6349. var rightPos = cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div");
  6350. return {from: range.from(), to: rightPos }
  6351. }); },
  6352. undo: function (cm) { return cm.undo(); },
  6353. redo: function (cm) { return cm.redo(); },
  6354. undoSelection: function (cm) { return cm.undoSelection(); },
  6355. redoSelection: function (cm) { return cm.redoSelection(); },
  6356. goDocStart: function (cm) { return cm.extendSelection(Pos(cm.firstLine(), 0)); },
  6357. goDocEnd: function (cm) { return cm.extendSelection(Pos(cm.lastLine())); },
  6358. goLineStart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStart(cm, range.head.line); },
  6359. {origin: "+move", bias: 1}
  6360. ); },
  6361. goLineStartSmart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStartSmart(cm, range.head); },
  6362. {origin: "+move", bias: 1}
  6363. ); },
  6364. goLineEnd: function (cm) { return cm.extendSelectionsBy(function (range) { return lineEnd(cm, range.head.line); },
  6365. {origin: "+move", bias: -1}
  6366. ); },
  6367. goLineRight: function (cm) { return cm.extendSelectionsBy(function (range) {
  6368. var top = cm.cursorCoords(range.head, "div").top + 5;
  6369. return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div")
  6370. }, sel_move); },
  6371. goLineLeft: function (cm) { return cm.extendSelectionsBy(function (range) {
  6372. var top = cm.cursorCoords(range.head, "div").top + 5;
  6373. return cm.coordsChar({left: 0, top: top}, "div")
  6374. }, sel_move); },
  6375. goLineLeftSmart: function (cm) { return cm.extendSelectionsBy(function (range) {
  6376. var top = cm.cursorCoords(range.head, "div").top + 5;
  6377. var pos = cm.coordsChar({left: 0, top: top}, "div");
  6378. if (pos.ch < cm.getLine(pos.line).search(/\S/)) { return lineStartSmart(cm, range.head) }
  6379. return pos
  6380. }, sel_move); },
  6381. goLineUp: function (cm) { return cm.moveV(-1, "line"); },
  6382. goLineDown: function (cm) { return cm.moveV(1, "line"); },
  6383. goPageUp: function (cm) { return cm.moveV(-1, "page"); },
  6384. goPageDown: function (cm) { return cm.moveV(1, "page"); },
  6385. goCharLeft: function (cm) { return cm.moveH(-1, "char"); },
  6386. goCharRight: function (cm) { return cm.moveH(1, "char"); },
  6387. goColumnLeft: function (cm) { return cm.moveH(-1, "column"); },
  6388. goColumnRight: function (cm) { return cm.moveH(1, "column"); },
  6389. goWordLeft: function (cm) { return cm.moveH(-1, "word"); },
  6390. goGroupRight: function (cm) { return cm.moveH(1, "group"); },
  6391. goGroupLeft: function (cm) { return cm.moveH(-1, "group"); },
  6392. goWordRight: function (cm) { return cm.moveH(1, "word"); },
  6393. delCharBefore: function (cm) { return cm.deleteH(-1, "codepoint"); },
  6394. delCharAfter: function (cm) { return cm.deleteH(1, "char"); },
  6395. delWordBefore: function (cm) { return cm.deleteH(-1, "word"); },
  6396. delWordAfter: function (cm) { return cm.deleteH(1, "word"); },
  6397. delGroupBefore: function (cm) { return cm.deleteH(-1, "group"); },
  6398. delGroupAfter: function (cm) { return cm.deleteH(1, "group"); },
  6399. indentAuto: function (cm) { return cm.indentSelection("smart"); },
  6400. indentMore: function (cm) { return cm.indentSelection("add"); },
  6401. indentLess: function (cm) { return cm.indentSelection("subtract"); },
  6402. insertTab: function (cm) { return cm.replaceSelection("\t"); },
  6403. insertSoftTab: function (cm) {
  6404. var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize;
  6405. for (var i = 0; i < ranges.length; i++) {
  6406. var pos = ranges[i].from();
  6407. var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize);
  6408. spaces.push(spaceStr(tabSize - col % tabSize));
  6409. }
  6410. cm.replaceSelections(spaces);
  6411. },
  6412. defaultTab: function (cm) {
  6413. if (cm.somethingSelected()) { cm.indentSelection("add"); }
  6414. else { cm.execCommand("insertTab"); }
  6415. },
  6416. // Swap the two chars left and right of each selection's head.
  6417. // Move cursor behind the two swapped characters afterwards.
  6418. //
  6419. // Doesn't consider line feeds a character.
  6420. // Doesn't scan more than one line above to find a character.
  6421. // Doesn't do anything on an empty line.
  6422. // Doesn't do anything with non-empty selections.
  6423. transposeChars: function (cm) { return runInOp(cm, function () {
  6424. var ranges = cm.listSelections(), newSel = [];
  6425. for (var i = 0; i < ranges.length; i++) {
  6426. if (!ranges[i].empty()) { continue }
  6427. var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text;
  6428. if (line) {
  6429. if (cur.ch == line.length) { cur = new Pos(cur.line, cur.ch - 1); }
  6430. if (cur.ch > 0) {
  6431. cur = new Pos(cur.line, cur.ch + 1);
  6432. cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2),
  6433. Pos(cur.line, cur.ch - 2), cur, "+transpose");
  6434. } else if (cur.line > cm.doc.first) {
  6435. var prev = getLine(cm.doc, cur.line - 1).text;
  6436. if (prev) {
  6437. cur = new Pos(cur.line, 1);
  6438. cm.replaceRange(line.charAt(0) + cm.doc.lineSeparator() +
  6439. prev.charAt(prev.length - 1),
  6440. Pos(cur.line - 1, prev.length - 1), cur, "+transpose");
  6441. }
  6442. }
  6443. }
  6444. newSel.push(new Range(cur, cur));
  6445. }
  6446. cm.setSelections(newSel);
  6447. }); },
  6448. newlineAndIndent: function (cm) { return runInOp(cm, function () {
  6449. var sels = cm.listSelections();
  6450. for (var i = sels.length - 1; i >= 0; i--)
  6451. { cm.replaceRange(cm.doc.lineSeparator(), sels[i].anchor, sels[i].head, "+input"); }
  6452. sels = cm.listSelections();
  6453. for (var i$1 = 0; i$1 < sels.length; i$1++)
  6454. { cm.indentLine(sels[i$1].from().line, null, true); }
  6455. ensureCursorVisible(cm);
  6456. }); },
  6457. openLine: function (cm) { return cm.replaceSelection("\n", "start"); },
  6458. toggleOverwrite: function (cm) { return cm.toggleOverwrite(); }
  6459. };
  6460. function lineStart(cm, lineN) {
  6461. var line = getLine(cm.doc, lineN);
  6462. var visual = visualLine(line);
  6463. if (visual != line) { lineN = lineNo(visual); }
  6464. return endOfLine(true, cm, visual, lineN, 1)
  6465. }
  6466. function lineEnd(cm, lineN) {
  6467. var line = getLine(cm.doc, lineN);
  6468. var visual = visualLineEnd(line);
  6469. if (visual != line) { lineN = lineNo(visual); }
  6470. return endOfLine(true, cm, line, lineN, -1)
  6471. }
  6472. function lineStartSmart(cm, pos) {
  6473. var start = lineStart(cm, pos.line);
  6474. var line = getLine(cm.doc, start.line);
  6475. var order = getOrder(line, cm.doc.direction);
  6476. if (!order || order[0].level == 0) {
  6477. var firstNonWS = Math.max(start.ch, line.text.search(/\S/));
  6478. var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch;
  6479. return Pos(start.line, inWS ? 0 : firstNonWS, start.sticky)
  6480. }
  6481. return start
  6482. }
  6483. // Run a handler that was bound to a key.
  6484. function doHandleBinding(cm, bound, dropShift) {
  6485. if (typeof bound == "string") {
  6486. bound = commands[bound];
  6487. if (!bound) { return false }
  6488. }
  6489. // Ensure previous input has been read, so that the handler sees a
  6490. // consistent view of the document
  6491. cm.display.input.ensurePolled();
  6492. var prevShift = cm.display.shift, done = false;
  6493. try {
  6494. if (cm.isReadOnly()) { cm.state.suppressEdits = true; }
  6495. if (dropShift) { cm.display.shift = false; }
  6496. done = bound(cm) != Pass;
  6497. } finally {
  6498. cm.display.shift = prevShift;
  6499. cm.state.suppressEdits = false;
  6500. }
  6501. return done
  6502. }
  6503. function lookupKeyForEditor(cm, name, handle) {
  6504. for (var i = 0; i < cm.state.keyMaps.length; i++) {
  6505. var result = lookupKey(name, cm.state.keyMaps[i], handle, cm);
  6506. if (result) { return result }
  6507. }
  6508. return (cm.options.extraKeys && lookupKey(name, cm.options.extraKeys, handle, cm))
  6509. || lookupKey(name, cm.options.keyMap, handle, cm)
  6510. }
  6511. // Note that, despite the name, this function is also used to check
  6512. // for bound mouse clicks.
  6513. var stopSeq = new Delayed;
  6514. function dispatchKey(cm, name, e, handle) {
  6515. var seq = cm.state.keySeq;
  6516. if (seq) {
  6517. if (isModifierKey(name)) { return "handled" }
  6518. if (/\'$/.test(name))
  6519. { cm.state.keySeq = null; }
  6520. else
  6521. { stopSeq.set(50, function () {
  6522. if (cm.state.keySeq == seq) {
  6523. cm.state.keySeq = null;
  6524. cm.display.input.reset();
  6525. }
  6526. }); }
  6527. if (dispatchKeyInner(cm, seq + " " + name, e, handle)) { return true }
  6528. }
  6529. return dispatchKeyInner(cm, name, e, handle)
  6530. }
  6531. function dispatchKeyInner(cm, name, e, handle) {
  6532. var result = lookupKeyForEditor(cm, name, handle);
  6533. if (result == "multi")
  6534. { cm.state.keySeq = name; }
  6535. if (result == "handled")
  6536. { signalLater(cm, "keyHandled", cm, name, e); }
  6537. if (result == "handled" || result == "multi") {
  6538. e_preventDefault(e);
  6539. restartBlink(cm);
  6540. }
  6541. return !!result
  6542. }
  6543. // Handle a key from the keydown event.
  6544. function handleKeyBinding(cm, e) {
  6545. var name = keyName(e, true);
  6546. if (!name) { return false }
  6547. if (e.shiftKey && !cm.state.keySeq) {
  6548. // First try to resolve full name (including 'Shift-'). Failing
  6549. // that, see if there is a cursor-motion command (starting with
  6550. // 'go') bound to the keyname without 'Shift-'.
  6551. return dispatchKey(cm, "Shift-" + name, e, function (b) { return doHandleBinding(cm, b, true); })
  6552. || dispatchKey(cm, name, e, function (b) {
  6553. if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion)
  6554. { return doHandleBinding(cm, b) }
  6555. })
  6556. } else {
  6557. return dispatchKey(cm, name, e, function (b) { return doHandleBinding(cm, b); })
  6558. }
  6559. }
  6560. // Handle a key from the keypress event
  6561. function handleCharBinding(cm, e, ch) {
  6562. return dispatchKey(cm, "'" + ch + "'", e, function (b) { return doHandleBinding(cm, b, true); })
  6563. }
  6564. var lastStoppedKey = null;
  6565. function onKeyDown(e) {
  6566. var cm = this;
  6567. if (e.target && e.target != cm.display.input.getField()) { return }
  6568. cm.curOp.focus = activeElt();
  6569. if (signalDOMEvent(cm, e)) { return }
  6570. // IE does strange things with escape.
  6571. if (ie && ie_version < 11 && e.keyCode == 27) { e.returnValue = false; }
  6572. var code = e.keyCode;
  6573. cm.display.shift = code == 16 || e.shiftKey;
  6574. var handled = handleKeyBinding(cm, e);
  6575. if (presto) {
  6576. lastStoppedKey = handled ? code : null;
  6577. // Opera has no cut event... we try to at least catch the key combo
  6578. if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey))
  6579. { cm.replaceSelection("", null, "cut"); }
  6580. }
  6581. if (gecko && !mac && !handled && code == 46 && e.shiftKey && !e.ctrlKey && document.execCommand)
  6582. { document.execCommand("cut"); }
  6583. // Turn mouse into crosshair when Alt is held on Mac.
  6584. if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className))
  6585. { showCrossHair(cm); }
  6586. }
  6587. function showCrossHair(cm) {
  6588. var lineDiv = cm.display.lineDiv;
  6589. addClass(lineDiv, "CodeMirror-crosshair");
  6590. function up(e) {
  6591. if (e.keyCode == 18 || !e.altKey) {
  6592. rmClass(lineDiv, "CodeMirror-crosshair");
  6593. off(document, "keyup", up);
  6594. off(document, "mouseover", up);
  6595. }
  6596. }
  6597. on(document, "keyup", up);
  6598. on(document, "mouseover", up);
  6599. }
  6600. function onKeyUp(e) {
  6601. if (e.keyCode == 16) { this.doc.sel.shift = false; }
  6602. signalDOMEvent(this, e);
  6603. }
  6604. function onKeyPress(e) {
  6605. var cm = this;
  6606. if (e.target && e.target != cm.display.input.getField()) { return }
  6607. if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) { return }
  6608. var keyCode = e.keyCode, charCode = e.charCode;
  6609. if (presto && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return}
  6610. if ((presto && (!e.which || e.which < 10)) && handleKeyBinding(cm, e)) { return }
  6611. var ch = String.fromCharCode(charCode == null ? keyCode : charCode);
  6612. // Some browsers fire keypress events for backspace
  6613. if (ch == "\x08") { return }
  6614. if (handleCharBinding(cm, e, ch)) { return }
  6615. cm.display.input.onKeyPress(e);
  6616. }
  6617. var DOUBLECLICK_DELAY = 400;
  6618. var PastClick = function(time, pos, button) {
  6619. this.time = time;
  6620. this.pos = pos;
  6621. this.button = button;
  6622. };
  6623. PastClick.prototype.compare = function (time, pos, button) {
  6624. return this.time + DOUBLECLICK_DELAY > time &&
  6625. cmp(pos, this.pos) == 0 && button == this.button
  6626. };
  6627. var lastClick, lastDoubleClick;
  6628. function clickRepeat(pos, button) {
  6629. var now = +new Date;
  6630. if (lastDoubleClick && lastDoubleClick.compare(now, pos, button)) {
  6631. lastClick = lastDoubleClick = null;
  6632. return "triple"
  6633. } else if (lastClick && lastClick.compare(now, pos, button)) {
  6634. lastDoubleClick = new PastClick(now, pos, button);
  6635. lastClick = null;
  6636. return "double"
  6637. } else {
  6638. lastClick = new PastClick(now, pos, button);
  6639. lastDoubleClick = null;
  6640. return "single"
  6641. }
  6642. }
  6643. // A mouse down can be a single click, double click, triple click,
  6644. // start of selection drag, start of text drag, new cursor
  6645. // (ctrl-click), rectangle drag (alt-drag), or xwin
  6646. // middle-click-paste. Or it might be a click on something we should
  6647. // not interfere with, such as a scrollbar or widget.
  6648. function onMouseDown(e) {
  6649. var cm = this, display = cm.display;
  6650. if (signalDOMEvent(cm, e) || display.activeTouch && display.input.supportsTouch()) { return }
  6651. display.input.ensurePolled();
  6652. display.shift = e.shiftKey;
  6653. if (eventInWidget(display, e)) {
  6654. if (!webkit) {
  6655. // Briefly turn off draggability, to allow widgets to do
  6656. // normal dragging things.
  6657. display.scroller.draggable = false;
  6658. setTimeout(function () { return display.scroller.draggable = true; }, 100);
  6659. }
  6660. return
  6661. }
  6662. if (clickInGutter(cm, e)) { return }
  6663. var pos = posFromMouse(cm, e), button = e_button(e), repeat = pos ? clickRepeat(pos, button) : "single";
  6664. window.focus();
  6665. // #3261: make sure, that we're not starting a second selection
  6666. if (button == 1 && cm.state.selectingText)
  6667. { cm.state.selectingText(e); }
  6668. if (pos && handleMappedButton(cm, button, pos, repeat, e)) { return }
  6669. if (button == 1) {
  6670. if (pos) { leftButtonDown(cm, pos, repeat, e); }
  6671. else if (e_target(e) == display.scroller) { e_preventDefault(e); }
  6672. } else if (button == 2) {
  6673. if (pos) { extendSelection(cm.doc, pos); }
  6674. setTimeout(function () { return display.input.focus(); }, 20);
  6675. } else if (button == 3) {
  6676. if (captureRightClick) { cm.display.input.onContextMenu(e); }
  6677. else { delayBlurEvent(cm); }
  6678. }
  6679. }
  6680. function handleMappedButton(cm, button, pos, repeat, event) {
  6681. var name = "Click";
  6682. if (repeat == "double") { name = "Double" + name; }
  6683. else if (repeat == "triple") { name = "Triple" + name; }
  6684. name = (button == 1 ? "Left" : button == 2 ? "Middle" : "Right") + name;
  6685. return dispatchKey(cm, addModifierNames(name, event), event, function (bound) {
  6686. if (typeof bound == "string") { bound = commands[bound]; }
  6687. if (!bound) { return false }
  6688. var done = false;
  6689. try {
  6690. if (cm.isReadOnly()) { cm.state.suppressEdits = true; }
  6691. done = bound(cm, pos) != Pass;
  6692. } finally {
  6693. cm.state.suppressEdits = false;
  6694. }
  6695. return done
  6696. })
  6697. }
  6698. function configureMouse(cm, repeat, event) {
  6699. var option = cm.getOption("configureMouse");
  6700. var value = option ? option(cm, repeat, event) : {};
  6701. if (value.unit == null) {
  6702. var rect = chromeOS ? event.shiftKey && event.metaKey : event.altKey;
  6703. value.unit = rect ? "rectangle" : repeat == "single" ? "char" : repeat == "double" ? "word" : "line";
  6704. }
  6705. if (value.extend == null || cm.doc.extend) { value.extend = cm.doc.extend || event.shiftKey; }
  6706. if (value.addNew == null) { value.addNew = mac ? event.metaKey : event.ctrlKey; }
  6707. if (value.moveOnDrag == null) { value.moveOnDrag = !(mac ? event.altKey : event.ctrlKey); }
  6708. return value
  6709. }
  6710. function leftButtonDown(cm, pos, repeat, event) {
  6711. if (ie) { setTimeout(bind(ensureFocus, cm), 0); }
  6712. else { cm.curOp.focus = activeElt(); }
  6713. var behavior = configureMouse(cm, repeat, event);
  6714. var sel = cm.doc.sel, contained;
  6715. if (cm.options.dragDrop && dragAndDrop && !cm.isReadOnly() &&
  6716. repeat == "single" && (contained = sel.contains(pos)) > -1 &&
  6717. (cmp((contained = sel.ranges[contained]).from(), pos) < 0 || pos.xRel > 0) &&
  6718. (cmp(contained.to(), pos) > 0 || pos.xRel < 0))
  6719. { leftButtonStartDrag(cm, event, pos, behavior); }
  6720. else
  6721. { leftButtonSelect(cm, event, pos, behavior); }
  6722. }
  6723. // Start a text drag. When it ends, see if any dragging actually
  6724. // happen, and treat as a click if it didn't.
  6725. function leftButtonStartDrag(cm, event, pos, behavior) {
  6726. var display = cm.display, moved = false;
  6727. var dragEnd = operation(cm, function (e) {
  6728. if (webkit) { display.scroller.draggable = false; }
  6729. cm.state.draggingText = false;
  6730. if (cm.state.delayingBlurEvent) {
  6731. if (cm.hasFocus()) { cm.state.delayingBlurEvent = false; }
  6732. else { delayBlurEvent(cm); }
  6733. }
  6734. off(display.wrapper.ownerDocument, "mouseup", dragEnd);
  6735. off(display.wrapper.ownerDocument, "mousemove", mouseMove);
  6736. off(display.scroller, "dragstart", dragStart);
  6737. off(display.scroller, "drop", dragEnd);
  6738. if (!moved) {
  6739. e_preventDefault(e);
  6740. if (!behavior.addNew)
  6741. { extendSelection(cm.doc, pos, null, null, behavior.extend); }
  6742. // Work around unexplainable focus problem in IE9 (#2127) and Chrome (#3081)
  6743. if ((webkit && !safari) || ie && ie_version == 9)
  6744. { setTimeout(function () {display.wrapper.ownerDocument.body.focus({preventScroll: true}); display.input.focus();}, 20); }
  6745. else
  6746. { display.input.focus(); }
  6747. }
  6748. });
  6749. var mouseMove = function(e2) {
  6750. moved = moved || Math.abs(event.clientX - e2.clientX) + Math.abs(event.clientY - e2.clientY) >= 10;
  6751. };
  6752. var dragStart = function () { return moved = true; };
  6753. // Let the drag handler handle this.
  6754. if (webkit) { display.scroller.draggable = true; }
  6755. cm.state.draggingText = dragEnd;
  6756. dragEnd.copy = !behavior.moveOnDrag;
  6757. on(display.wrapper.ownerDocument, "mouseup", dragEnd);
  6758. on(display.wrapper.ownerDocument, "mousemove", mouseMove);
  6759. on(display.scroller, "dragstart", dragStart);
  6760. on(display.scroller, "drop", dragEnd);
  6761. cm.state.delayingBlurEvent = true;
  6762. setTimeout(function () { return display.input.focus(); }, 20);
  6763. // IE's approach to draggable
  6764. if (display.scroller.dragDrop) { display.scroller.dragDrop(); }
  6765. }
  6766. function rangeForUnit(cm, pos, unit) {
  6767. if (unit == "char") { return new Range(pos, pos) }
  6768. if (unit == "word") { return cm.findWordAt(pos) }
  6769. if (unit == "line") { return new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))) }
  6770. var result = unit(cm, pos);
  6771. return new Range(result.from, result.to)
  6772. }
  6773. // Normal selection, as opposed to text dragging.
  6774. function leftButtonSelect(cm, event, start, behavior) {
  6775. if (ie) { delayBlurEvent(cm); }
  6776. var display = cm.display, doc = cm.doc;
  6777. e_preventDefault(event);
  6778. var ourRange, ourIndex, startSel = doc.sel, ranges = startSel.ranges;
  6779. if (behavior.addNew && !behavior.extend) {
  6780. ourIndex = doc.sel.contains(start);
  6781. if (ourIndex > -1)
  6782. { ourRange = ranges[ourIndex]; }
  6783. else
  6784. { ourRange = new Range(start, start); }
  6785. } else {
  6786. ourRange = doc.sel.primary();
  6787. ourIndex = doc.sel.primIndex;
  6788. }
  6789. if (behavior.unit == "rectangle") {
  6790. if (!behavior.addNew) { ourRange = new Range(start, start); }
  6791. start = posFromMouse(cm, event, true, true);
  6792. ourIndex = -1;
  6793. } else {
  6794. var range = rangeForUnit(cm, start, behavior.unit);
  6795. if (behavior.extend)
  6796. { ourRange = extendRange(ourRange, range.anchor, range.head, behavior.extend); }
  6797. else
  6798. { ourRange = range; }
  6799. }
  6800. if (!behavior.addNew) {
  6801. ourIndex = 0;
  6802. setSelection(doc, new Selection([ourRange], 0), sel_mouse);
  6803. startSel = doc.sel;
  6804. } else if (ourIndex == -1) {
  6805. ourIndex = ranges.length;
  6806. setSelection(doc, normalizeSelection(cm, ranges.concat([ourRange]), ourIndex),
  6807. {scroll: false, origin: "*mouse"});
  6808. } else if (ranges.length > 1 && ranges[ourIndex].empty() && behavior.unit == "char" && !behavior.extend) {
  6809. setSelection(doc, normalizeSelection(cm, ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0),
  6810. {scroll: false, origin: "*mouse"});
  6811. startSel = doc.sel;
  6812. } else {
  6813. replaceOneSelection(doc, ourIndex, ourRange, sel_mouse);
  6814. }
  6815. var lastPos = start;
  6816. function extendTo(pos) {
  6817. if (cmp(lastPos, pos) == 0) { return }
  6818. lastPos = pos;
  6819. if (behavior.unit == "rectangle") {
  6820. var ranges = [], tabSize = cm.options.tabSize;
  6821. var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize);
  6822. var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize);
  6823. var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol);
  6824. for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line));
  6825. line <= end; line++) {
  6826. var text = getLine(doc, line).text, leftPos = findColumn(text, left, tabSize);
  6827. if (left == right)
  6828. { ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos))); }
  6829. else if (text.length > leftPos)
  6830. { ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize)))); }
  6831. }
  6832. if (!ranges.length) { ranges.push(new Range(start, start)); }
  6833. setSelection(doc, normalizeSelection(cm, startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex),
  6834. {origin: "*mouse", scroll: false});
  6835. cm.scrollIntoView(pos);
  6836. } else {
  6837. var oldRange = ourRange;
  6838. var range = rangeForUnit(cm, pos, behavior.unit);
  6839. var anchor = oldRange.anchor, head;
  6840. if (cmp(range.anchor, anchor) > 0) {
  6841. head = range.head;
  6842. anchor = minPos(oldRange.from(), range.anchor);
  6843. } else {
  6844. head = range.anchor;
  6845. anchor = maxPos(oldRange.to(), range.head);
  6846. }
  6847. var ranges$1 = startSel.ranges.slice(0);
  6848. ranges$1[ourIndex] = bidiSimplify(cm, new Range(clipPos(doc, anchor), head));
  6849. setSelection(doc, normalizeSelection(cm, ranges$1, ourIndex), sel_mouse);
  6850. }
  6851. }
  6852. var editorSize = display.wrapper.getBoundingClientRect();
  6853. // Used to ensure timeout re-tries don't fire when another extend
  6854. // happened in the meantime (clearTimeout isn't reliable -- at
  6855. // least on Chrome, the timeouts still happen even when cleared,
  6856. // if the clear happens after their scheduled firing time).
  6857. var counter = 0;
  6858. function extend(e) {
  6859. var curCount = ++counter;
  6860. var cur = posFromMouse(cm, e, true, behavior.unit == "rectangle");
  6861. if (!cur) { return }
  6862. if (cmp(cur, lastPos) != 0) {
  6863. cm.curOp.focus = activeElt();
  6864. extendTo(cur);
  6865. var visible = visibleLines(display, doc);
  6866. if (cur.line >= visible.to || cur.line < visible.from)
  6867. { setTimeout(operation(cm, function () {if (counter == curCount) { extend(e); }}), 150); }
  6868. } else {
  6869. var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0;
  6870. if (outside) { setTimeout(operation(cm, function () {
  6871. if (counter != curCount) { return }
  6872. display.scroller.scrollTop += outside;
  6873. extend(e);
  6874. }), 50); }
  6875. }
  6876. }
  6877. function done(e) {
  6878. cm.state.selectingText = false;
  6879. counter = Infinity;
  6880. // If e is null or undefined we interpret this as someone trying
  6881. // to explicitly cancel the selection rather than the user
  6882. // letting go of the mouse button.
  6883. if (e) {
  6884. e_preventDefault(e);
  6885. display.input.focus();
  6886. }
  6887. off(display.wrapper.ownerDocument, "mousemove", move);
  6888. off(display.wrapper.ownerDocument, "mouseup", up);
  6889. doc.history.lastSelOrigin = null;
  6890. }
  6891. var move = operation(cm, function (e) {
  6892. if (e.buttons === 0 || !e_button(e)) { done(e); }
  6893. else { extend(e); }
  6894. });
  6895. var up = operation(cm, done);
  6896. cm.state.selectingText = up;
  6897. on(display.wrapper.ownerDocument, "mousemove", move);
  6898. on(display.wrapper.ownerDocument, "mouseup", up);
  6899. }
  6900. // Used when mouse-selecting to adjust the anchor to the proper side
  6901. // of a bidi jump depending on the visual position of the head.
  6902. function bidiSimplify(cm, range) {
  6903. var anchor = range.anchor;
  6904. var head = range.head;
  6905. var anchorLine = getLine(cm.doc, anchor.line);
  6906. if (cmp(anchor, head) == 0 && anchor.sticky == head.sticky) { return range }
  6907. var order = getOrder(anchorLine);
  6908. if (!order) { return range }
  6909. var index = getBidiPartAt(order, anchor.ch, anchor.sticky), part = order[index];
  6910. if (part.from != anchor.ch && part.to != anchor.ch) { return range }
  6911. var boundary = index + ((part.from == anchor.ch) == (part.level != 1) ? 0 : 1);
  6912. if (boundary == 0 || boundary == order.length) { return range }
  6913. // Compute the relative visual position of the head compared to the
  6914. // anchor (<0 is to the left, >0 to the right)
  6915. var leftSide;
  6916. if (head.line != anchor.line) {
  6917. leftSide = (head.line - anchor.line) * (cm.doc.direction == "ltr" ? 1 : -1) > 0;
  6918. } else {
  6919. var headIndex = getBidiPartAt(order, head.ch, head.sticky);
  6920. var dir = headIndex - index || (head.ch - anchor.ch) * (part.level == 1 ? -1 : 1);
  6921. if (headIndex == boundary - 1 || headIndex == boundary)
  6922. { leftSide = dir < 0; }
  6923. else
  6924. { leftSide = dir > 0; }
  6925. }
  6926. var usePart = order[boundary + (leftSide ? -1 : 0)];
  6927. var from = leftSide == (usePart.level == 1);
  6928. var ch = from ? usePart.from : usePart.to, sticky = from ? "after" : "before";
  6929. return anchor.ch == ch && anchor.sticky == sticky ? range : new Range(new Pos(anchor.line, ch, sticky), head)
  6930. }
  6931. // Determines whether an event happened in the gutter, and fires the
  6932. // handlers for the corresponding event.
  6933. function gutterEvent(cm, e, type, prevent) {
  6934. var mX, mY;
  6935. if (e.touches) {
  6936. mX = e.touches[0].clientX;
  6937. mY = e.touches[0].clientY;
  6938. } else {
  6939. try { mX = e.clientX; mY = e.clientY; }
  6940. catch(e$1) { return false }
  6941. }
  6942. if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) { return false }
  6943. if (prevent) { e_preventDefault(e); }
  6944. var display = cm.display;
  6945. var lineBox = display.lineDiv.getBoundingClientRect();
  6946. if (mY > lineBox.bottom || !hasHandler(cm, type)) { return e_defaultPrevented(e) }
  6947. mY -= lineBox.top - display.viewOffset;
  6948. for (var i = 0; i < cm.display.gutterSpecs.length; ++i) {
  6949. var g = display.gutters.childNodes[i];
  6950. if (g && g.getBoundingClientRect().right >= mX) {
  6951. var line = lineAtHeight(cm.doc, mY);
  6952. var gutter = cm.display.gutterSpecs[i];
  6953. signal(cm, type, cm, line, gutter.className, e);
  6954. return e_defaultPrevented(e)
  6955. }
  6956. }
  6957. }
  6958. function clickInGutter(cm, e) {
  6959. return gutterEvent(cm, e, "gutterClick", true)
  6960. }
  6961. // CONTEXT MENU HANDLING
  6962. // To make the context menu work, we need to briefly unhide the
  6963. // textarea (making it as unobtrusive as possible) to let the
  6964. // right-click take effect on it.
  6965. function onContextMenu(cm, e) {
  6966. if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) { return }
  6967. if (signalDOMEvent(cm, e, "contextmenu")) { return }
  6968. if (!captureRightClick) { cm.display.input.onContextMenu(e); }
  6969. }
  6970. function contextMenuInGutter(cm, e) {
  6971. if (!hasHandler(cm, "gutterContextMenu")) { return false }
  6972. return gutterEvent(cm, e, "gutterContextMenu", false)
  6973. }
  6974. function themeChanged(cm) {
  6975. cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") +
  6976. cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-");
  6977. clearCaches(cm);
  6978. }
  6979. var Init = {toString: function(){return "CodeMirror.Init"}};
  6980. var defaults = {};
  6981. var optionHandlers = {};
  6982. function defineOptions(CodeMirror) {
  6983. var optionHandlers = CodeMirror.optionHandlers;
  6984. function option(name, deflt, handle, notOnInit) {
  6985. CodeMirror.defaults[name] = deflt;
  6986. if (handle) { optionHandlers[name] =
  6987. notOnInit ? function (cm, val, old) {if (old != Init) { handle(cm, val, old); }} : handle; }
  6988. }
  6989. CodeMirror.defineOption = option;
  6990. // Passed to option handlers when there is no old value.
  6991. CodeMirror.Init = Init;
  6992. // These two are, on init, called from the constructor because they
  6993. // have to be initialized before the editor can start at all.
  6994. option("value", "", function (cm, val) { return cm.setValue(val); }, true);
  6995. option("mode", null, function (cm, val) {
  6996. cm.doc.modeOption = val;
  6997. loadMode(cm);
  6998. }, true);
  6999. option("indentUnit", 2, loadMode, true);
  7000. option("indentWithTabs", false);
  7001. option("smartIndent", true);
  7002. option("tabSize", 4, function (cm) {
  7003. resetModeState(cm);
  7004. clearCaches(cm);
  7005. regChange(cm);
  7006. }, true);
  7007. option("lineSeparator", null, function (cm, val) {
  7008. cm.doc.lineSep = val;
  7009. if (!val) { return }
  7010. var newBreaks = [], lineNo = cm.doc.first;
  7011. cm.doc.iter(function (line) {
  7012. for (var pos = 0;;) {
  7013. var found = line.text.indexOf(val, pos);
  7014. if (found == -1) { break }
  7015. pos = found + val.length;
  7016. newBreaks.push(Pos(lineNo, found));
  7017. }
  7018. lineNo++;
  7019. });
  7020. for (var i = newBreaks.length - 1; i >= 0; i--)
  7021. { replaceRange(cm.doc, val, newBreaks[i], Pos(newBreaks[i].line, newBreaks[i].ch + val.length)); }
  7022. });
  7023. option("specialChars", /[\u0000-\u001f\u007f-\u009f\u00ad\u061c\u200b\u200e\u200f\u2028\u2029\ufeff\ufff9-\ufffc]/g, function (cm, val, old) {
  7024. cm.state.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g");
  7025. if (old != Init) { cm.refresh(); }
  7026. });
  7027. option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function (cm) { return cm.refresh(); }, true);
  7028. option("electricChars", true);
  7029. option("inputStyle", mobile ? "contenteditable" : "textarea", function () {
  7030. throw new Error("inputStyle can not (yet) be changed in a running editor") // FIXME
  7031. }, true);
  7032. option("spellcheck", false, function (cm, val) { return cm.getInputField().spellcheck = val; }, true);
  7033. option("autocorrect", false, function (cm, val) { return cm.getInputField().autocorrect = val; }, true);
  7034. option("autocapitalize", false, function (cm, val) { return cm.getInputField().autocapitalize = val; }, true);
  7035. option("rtlMoveVisually", !windows);
  7036. option("wholeLineUpdateBefore", true);
  7037. option("theme", "default", function (cm) {
  7038. themeChanged(cm);
  7039. updateGutters(cm);
  7040. }, true);
  7041. option("keyMap", "default", function (cm, val, old) {
  7042. var next = getKeyMap(val);
  7043. var prev = old != Init && getKeyMap(old);
  7044. if (prev && prev.detach) { prev.detach(cm, next); }
  7045. if (next.attach) { next.attach(cm, prev || null); }
  7046. });
  7047. option("extraKeys", null);
  7048. option("configureMouse", null);
  7049. option("lineWrapping", false, wrappingChanged, true);
  7050. option("gutters", [], function (cm, val) {
  7051. cm.display.gutterSpecs = getGutters(val, cm.options.lineNumbers);
  7052. updateGutters(cm);
  7053. }, true);
  7054. option("fixedGutter", true, function (cm, val) {
  7055. cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0";
  7056. cm.refresh();
  7057. }, true);
  7058. option("coverGutterNextToScrollbar", false, function (cm) { return updateScrollbars(cm); }, true);
  7059. option("scrollbarStyle", "native", function (cm) {
  7060. initScrollbars(cm);
  7061. updateScrollbars(cm);
  7062. cm.display.scrollbars.setScrollTop(cm.doc.scrollTop);
  7063. cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft);
  7064. }, true);
  7065. option("lineNumbers", false, function (cm, val) {
  7066. cm.display.gutterSpecs = getGutters(cm.options.gutters, val);
  7067. updateGutters(cm);
  7068. }, true);
  7069. option("firstLineNumber", 1, updateGutters, true);
  7070. option("lineNumberFormatter", function (integer) { return integer; }, updateGutters, true);
  7071. option("showCursorWhenSelecting", false, updateSelection, true);
  7072. option("resetSelectionOnContextMenu", true);
  7073. option("lineWiseCopyCut", true);
  7074. option("pasteLinesPerSelection", true);
  7075. option("selectionsMayTouch", false);
  7076. option("readOnly", false, function (cm, val) {
  7077. if (val == "nocursor") {
  7078. onBlur(cm);
  7079. cm.display.input.blur();
  7080. }
  7081. cm.display.input.readOnlyChanged(val);
  7082. });
  7083. option("screenReaderLabel", null, function (cm, val) {
  7084. val = (val === '') ? null : val;
  7085. cm.display.input.screenReaderLabelChanged(val);
  7086. });
  7087. option("disableInput", false, function (cm, val) {if (!val) { cm.display.input.reset(); }}, true);
  7088. option("dragDrop", true, dragDropChanged);
  7089. option("allowDropFileTypes", null);
  7090. option("cursorBlinkRate", 530);
  7091. option("cursorScrollMargin", 0);
  7092. option("cursorHeight", 1, updateSelection, true);
  7093. option("singleCursorHeightPerLine", true, updateSelection, true);
  7094. option("workTime", 100);
  7095. option("workDelay", 100);
  7096. option("flattenSpans", true, resetModeState, true);
  7097. option("addModeClass", false, resetModeState, true);
  7098. option("pollInterval", 100);
  7099. option("undoDepth", 200, function (cm, val) { return cm.doc.history.undoDepth = val; });
  7100. option("historyEventDelay", 1250);
  7101. option("viewportMargin", 10, function (cm) { return cm.refresh(); }, true);
  7102. option("maxHighlightLength", 10000, resetModeState, true);
  7103. option("moveInputWithCursor", true, function (cm, val) {
  7104. if (!val) { cm.display.input.resetPosition(); }
  7105. });
  7106. option("tabindex", null, function (cm, val) { return cm.display.input.getField().tabIndex = val || ""; });
  7107. option("autofocus", null);
  7108. option("direction", "ltr", function (cm, val) { return cm.doc.setDirection(val); }, true);
  7109. option("phrases", null);
  7110. }
  7111. function dragDropChanged(cm, value, old) {
  7112. var wasOn = old && old != Init;
  7113. if (!value != !wasOn) {
  7114. var funcs = cm.display.dragFunctions;
  7115. var toggle = value ? on : off;
  7116. toggle(cm.display.scroller, "dragstart", funcs.start);
  7117. toggle(cm.display.scroller, "dragenter", funcs.enter);
  7118. toggle(cm.display.scroller, "dragover", funcs.over);
  7119. toggle(cm.display.scroller, "dragleave", funcs.leave);
  7120. toggle(cm.display.scroller, "drop", funcs.drop);
  7121. }
  7122. }
  7123. function wrappingChanged(cm) {
  7124. if (cm.options.lineWrapping) {
  7125. addClass(cm.display.wrapper, "CodeMirror-wrap");
  7126. cm.display.sizer.style.minWidth = "";
  7127. cm.display.sizerWidth = null;
  7128. } else {
  7129. rmClass(cm.display.wrapper, "CodeMirror-wrap");
  7130. findMaxLine(cm);
  7131. }
  7132. estimateLineHeights(cm);
  7133. regChange(cm);
  7134. clearCaches(cm);
  7135. setTimeout(function () { return updateScrollbars(cm); }, 100);
  7136. }
  7137. // A CodeMirror instance represents an editor. This is the object
  7138. // that user code is usually dealing with.
  7139. function CodeMirror(place, options) {
  7140. var this$1 = this;
  7141. if (!(this instanceof CodeMirror)) { return new CodeMirror(place, options) }
  7142. this.options = options = options ? copyObj(options) : {};
  7143. // Determine effective options based on given values and defaults.
  7144. copyObj(defaults, options, false);
  7145. var doc = options.value;
  7146. if (typeof doc == "string") { doc = new Doc(doc, options.mode, null, options.lineSeparator, options.direction); }
  7147. else if (options.mode) { doc.modeOption = options.mode; }
  7148. this.doc = doc;
  7149. var input = new CodeMirror.inputStyles[options.inputStyle](this);
  7150. var display = this.display = new Display(place, doc, input, options);
  7151. display.wrapper.CodeMirror = this;
  7152. themeChanged(this);
  7153. if (options.lineWrapping)
  7154. { this.display.wrapper.className += " CodeMirror-wrap"; }
  7155. initScrollbars(this);
  7156. this.state = {
  7157. keyMaps: [], // stores maps added by addKeyMap
  7158. overlays: [], // highlighting overlays, as added by addOverlay
  7159. modeGen: 0, // bumped when mode/overlay changes, used to invalidate highlighting info
  7160. overwrite: false,
  7161. delayingBlurEvent: false,
  7162. focused: false,
  7163. suppressEdits: false, // used to disable editing during key handlers when in readOnly mode
  7164. pasteIncoming: -1, cutIncoming: -1, // help recognize paste/cut edits in input.poll
  7165. selectingText: false,
  7166. draggingText: false,
  7167. highlight: new Delayed(), // stores highlight worker timeout
  7168. keySeq: null, // Unfinished key sequence
  7169. specialChars: null
  7170. };
  7171. if (options.autofocus && !mobile) { display.input.focus(); }
  7172. // Override magic textarea content restore that IE sometimes does
  7173. // on our hidden textarea on reload
  7174. if (ie && ie_version < 11) { setTimeout(function () { return this$1.display.input.reset(true); }, 20); }
  7175. registerEventHandlers(this);
  7176. ensureGlobalHandlers();
  7177. startOperation(this);
  7178. this.curOp.forceUpdate = true;
  7179. attachDoc(this, doc);
  7180. if ((options.autofocus && !mobile) || this.hasFocus())
  7181. { setTimeout(function () {
  7182. if (this$1.hasFocus() && !this$1.state.focused) { onFocus(this$1); }
  7183. }, 20); }
  7184. else
  7185. { onBlur(this); }
  7186. for (var opt in optionHandlers) { if (optionHandlers.hasOwnProperty(opt))
  7187. { optionHandlers[opt](this, options[opt], Init); } }
  7188. maybeUpdateLineNumberWidth(this);
  7189. if (options.finishInit) { options.finishInit(this); }
  7190. for (var i = 0; i < initHooks.length; ++i) { initHooks[i](this); }
  7191. endOperation(this);
  7192. // Suppress optimizelegibility in Webkit, since it breaks text
  7193. // measuring on line wrapping boundaries.
  7194. if (webkit && options.lineWrapping &&
  7195. getComputedStyle(display.lineDiv).textRendering == "optimizelegibility")
  7196. { display.lineDiv.style.textRendering = "auto"; }
  7197. }
  7198. // The default configuration options.
  7199. CodeMirror.defaults = defaults;
  7200. // Functions to run when options are changed.
  7201. CodeMirror.optionHandlers = optionHandlers;
  7202. // Attach the necessary event handlers when initializing the editor
  7203. function registerEventHandlers(cm) {
  7204. var d = cm.display;
  7205. on(d.scroller, "mousedown", operation(cm, onMouseDown));
  7206. // Older IE's will not fire a second mousedown for a double click
  7207. if (ie && ie_version < 11)
  7208. { on(d.scroller, "dblclick", operation(cm, function (e) {
  7209. if (signalDOMEvent(cm, e)) { return }
  7210. var pos = posFromMouse(cm, e);
  7211. if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) { return }
  7212. e_preventDefault(e);
  7213. var word = cm.findWordAt(pos);
  7214. extendSelection(cm.doc, word.anchor, word.head);
  7215. })); }
  7216. else
  7217. { on(d.scroller, "dblclick", function (e) { return signalDOMEvent(cm, e) || e_preventDefault(e); }); }
  7218. // Some browsers fire contextmenu *after* opening the menu, at
  7219. // which point we can't mess with it anymore. Context menu is
  7220. // handled in onMouseDown for these browsers.
  7221. on(d.scroller, "contextmenu", function (e) { return onContextMenu(cm, e); });
  7222. on(d.input.getField(), "contextmenu", function (e) {
  7223. if (!d.scroller.contains(e.target)) { onContextMenu(cm, e); }
  7224. });
  7225. // Used to suppress mouse event handling when a touch happens
  7226. var touchFinished, prevTouch = {end: 0};
  7227. function finishTouch() {
  7228. if (d.activeTouch) {
  7229. touchFinished = setTimeout(function () { return d.activeTouch = null; }, 1000);
  7230. prevTouch = d.activeTouch;
  7231. prevTouch.end = +new Date;
  7232. }
  7233. }
  7234. function isMouseLikeTouchEvent(e) {
  7235. if (e.touches.length != 1) { return false }
  7236. var touch = e.touches[0];
  7237. return touch.radiusX <= 1 && touch.radiusY <= 1
  7238. }
  7239. function farAway(touch, other) {
  7240. if (other.left == null) { return true }
  7241. var dx = other.left - touch.left, dy = other.top - touch.top;
  7242. return dx * dx + dy * dy > 20 * 20
  7243. }
  7244. on(d.scroller, "touchstart", function (e) {
  7245. if (!signalDOMEvent(cm, e) && !isMouseLikeTouchEvent(e) && !clickInGutter(cm, e)) {
  7246. d.input.ensurePolled();
  7247. clearTimeout(touchFinished);
  7248. var now = +new Date;
  7249. d.activeTouch = {start: now, moved: false,
  7250. prev: now - prevTouch.end <= 300 ? prevTouch : null};
  7251. if (e.touches.length == 1) {
  7252. d.activeTouch.left = e.touches[0].pageX;
  7253. d.activeTouch.top = e.touches[0].pageY;
  7254. }
  7255. }
  7256. });
  7257. on(d.scroller, "touchmove", function () {
  7258. if (d.activeTouch) { d.activeTouch.moved = true; }
  7259. });
  7260. on(d.scroller, "touchend", function (e) {
  7261. var touch = d.activeTouch;
  7262. if (touch && !eventInWidget(d, e) && touch.left != null &&
  7263. !touch.moved && new Date - touch.start < 300) {
  7264. var pos = cm.coordsChar(d.activeTouch, "page"), range;
  7265. if (!touch.prev || farAway(touch, touch.prev)) // Single tap
  7266. { range = new Range(pos, pos); }
  7267. else if (!touch.prev.prev || farAway(touch, touch.prev.prev)) // Double tap
  7268. { range = cm.findWordAt(pos); }
  7269. else // Triple tap
  7270. { range = new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))); }
  7271. cm.setSelection(range.anchor, range.head);
  7272. cm.focus();
  7273. e_preventDefault(e);
  7274. }
  7275. finishTouch();
  7276. });
  7277. on(d.scroller, "touchcancel", finishTouch);
  7278. // Sync scrolling between fake scrollbars and real scrollable
  7279. // area, ensure viewport is updated when scrolling.
  7280. on(d.scroller, "scroll", function () {
  7281. if (d.scroller.clientHeight) {
  7282. updateScrollTop(cm, d.scroller.scrollTop);
  7283. setScrollLeft(cm, d.scroller.scrollLeft, true);
  7284. signal(cm, "scroll", cm);
  7285. }
  7286. });
  7287. // Listen to wheel events in order to try and update the viewport on time.
  7288. on(d.scroller, "mousewheel", function (e) { return onScrollWheel(cm, e); });
  7289. on(d.scroller, "DOMMouseScroll", function (e) { return onScrollWheel(cm, e); });
  7290. // Prevent wrapper from ever scrolling
  7291. on(d.wrapper, "scroll", function () { return d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; });
  7292. d.dragFunctions = {
  7293. enter: function (e) {if (!signalDOMEvent(cm, e)) { e_stop(e); }},
  7294. over: function (e) {if (!signalDOMEvent(cm, e)) { onDragOver(cm, e); e_stop(e); }},
  7295. start: function (e) { return onDragStart(cm, e); },
  7296. drop: operation(cm, onDrop),
  7297. leave: function (e) {if (!signalDOMEvent(cm, e)) { clearDragCursor(cm); }}
  7298. };
  7299. var inp = d.input.getField();
  7300. on(inp, "keyup", function (e) { return onKeyUp.call(cm, e); });
  7301. on(inp, "keydown", operation(cm, onKeyDown));
  7302. on(inp, "keypress", operation(cm, onKeyPress));
  7303. on(inp, "focus", function (e) { return onFocus(cm, e); });
  7304. on(inp, "blur", function (e) { return onBlur(cm, e); });
  7305. }
  7306. var initHooks = [];
  7307. CodeMirror.defineInitHook = function (f) { return initHooks.push(f); };
  7308. // Indent the given line. The how parameter can be "smart",
  7309. // "add"/null, "subtract", or "prev". When aggressive is false
  7310. // (typically set to true for forced single-line indents), empty
  7311. // lines are not indented, and places where the mode returns Pass
  7312. // are left alone.
  7313. function indentLine(cm, n, how, aggressive) {
  7314. var doc = cm.doc, state;
  7315. if (how == null) { how = "add"; }
  7316. if (how == "smart") {
  7317. // Fall back to "prev" when the mode doesn't have an indentation
  7318. // method.
  7319. if (!doc.mode.indent) { how = "prev"; }
  7320. else { state = getContextBefore(cm, n).state; }
  7321. }
  7322. var tabSize = cm.options.tabSize;
  7323. var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize);
  7324. if (line.stateAfter) { line.stateAfter = null; }
  7325. var curSpaceString = line.text.match(/^\s*/)[0], indentation;
  7326. if (!aggressive && !/\S/.test(line.text)) {
  7327. indentation = 0;
  7328. how = "not";
  7329. } else if (how == "smart") {
  7330. indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text);
  7331. if (indentation == Pass || indentation > 150) {
  7332. if (!aggressive) { return }
  7333. how = "prev";
  7334. }
  7335. }
  7336. if (how == "prev") {
  7337. if (n > doc.first) { indentation = countColumn(getLine(doc, n-1).text, null, tabSize); }
  7338. else { indentation = 0; }
  7339. } else if (how == "add") {
  7340. indentation = curSpace + cm.options.indentUnit;
  7341. } else if (how == "subtract") {
  7342. indentation = curSpace - cm.options.indentUnit;
  7343. } else if (typeof how == "number") {
  7344. indentation = curSpace + how;
  7345. }
  7346. indentation = Math.max(0, indentation);
  7347. var indentString = "", pos = 0;
  7348. if (cm.options.indentWithTabs)
  7349. { for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";} }
  7350. if (pos < indentation) { indentString += spaceStr(indentation - pos); }
  7351. if (indentString != curSpaceString) {
  7352. replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input");
  7353. line.stateAfter = null;
  7354. return true
  7355. } else {
  7356. // Ensure that, if the cursor was in the whitespace at the start
  7357. // of the line, it is moved to the end of that space.
  7358. for (var i$1 = 0; i$1 < doc.sel.ranges.length; i$1++) {
  7359. var range = doc.sel.ranges[i$1];
  7360. if (range.head.line == n && range.head.ch < curSpaceString.length) {
  7361. var pos$1 = Pos(n, curSpaceString.length);
  7362. replaceOneSelection(doc, i$1, new Range(pos$1, pos$1));
  7363. break
  7364. }
  7365. }
  7366. }
  7367. }
  7368. // This will be set to a {lineWise: bool, text: [string]} object, so
  7369. // that, when pasting, we know what kind of selections the copied
  7370. // text was made out of.
  7371. var lastCopied = null;
  7372. function setLastCopied(newLastCopied) {
  7373. lastCopied = newLastCopied;
  7374. }
  7375. function applyTextInput(cm, inserted, deleted, sel, origin) {
  7376. var doc = cm.doc;
  7377. cm.display.shift = false;
  7378. if (!sel) { sel = doc.sel; }
  7379. var recent = +new Date - 200;
  7380. var paste = origin == "paste" || cm.state.pasteIncoming > recent;
  7381. var textLines = splitLinesAuto(inserted), multiPaste = null;
  7382. // When pasting N lines into N selections, insert one line per selection
  7383. if (paste && sel.ranges.length > 1) {
  7384. if (lastCopied && lastCopied.text.join("\n") == inserted) {
  7385. if (sel.ranges.length % lastCopied.text.length == 0) {
  7386. multiPaste = [];
  7387. for (var i = 0; i < lastCopied.text.length; i++)
  7388. { multiPaste.push(doc.splitLines(lastCopied.text[i])); }
  7389. }
  7390. } else if (textLines.length == sel.ranges.length && cm.options.pasteLinesPerSelection) {
  7391. multiPaste = map(textLines, function (l) { return [l]; });
  7392. }
  7393. }
  7394. var updateInput = cm.curOp.updateInput;
  7395. // Normal behavior is to insert the new text into every selection
  7396. for (var i$1 = sel.ranges.length - 1; i$1 >= 0; i$1--) {
  7397. var range = sel.ranges[i$1];
  7398. var from = range.from(), to = range.to();
  7399. if (range.empty()) {
  7400. if (deleted && deleted > 0) // Handle deletion
  7401. { from = Pos(from.line, from.ch - deleted); }
  7402. else if (cm.state.overwrite && !paste) // Handle overwrite
  7403. { to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length)); }
  7404. else if (paste && lastCopied && lastCopied.lineWise && lastCopied.text.join("\n") == textLines.join("\n"))
  7405. { from = to = Pos(from.line, 0); }
  7406. }
  7407. var changeEvent = {from: from, to: to, text: multiPaste ? multiPaste[i$1 % multiPaste.length] : textLines,
  7408. origin: origin || (paste ? "paste" : cm.state.cutIncoming > recent ? "cut" : "+input")};
  7409. makeChange(cm.doc, changeEvent);
  7410. signalLater(cm, "inputRead", cm, changeEvent);
  7411. }
  7412. if (inserted && !paste)
  7413. { triggerElectric(cm, inserted); }
  7414. ensureCursorVisible(cm);
  7415. if (cm.curOp.updateInput < 2) { cm.curOp.updateInput = updateInput; }
  7416. cm.curOp.typing = true;
  7417. cm.state.pasteIncoming = cm.state.cutIncoming = -1;
  7418. }
  7419. function handlePaste(e, cm) {
  7420. var pasted = e.clipboardData && e.clipboardData.getData("Text");
  7421. if (pasted) {
  7422. e.preventDefault();
  7423. if (!cm.isReadOnly() && !cm.options.disableInput)
  7424. { runInOp(cm, function () { return applyTextInput(cm, pasted, 0, null, "paste"); }); }
  7425. return true
  7426. }
  7427. }
  7428. function triggerElectric(cm, inserted) {
  7429. // When an 'electric' character is inserted, immediately trigger a reindent
  7430. if (!cm.options.electricChars || !cm.options.smartIndent) { return }
  7431. var sel = cm.doc.sel;
  7432. for (var i = sel.ranges.length - 1; i >= 0; i--) {
  7433. var range = sel.ranges[i];
  7434. if (range.head.ch > 100 || (i && sel.ranges[i - 1].head.line == range.head.line)) { continue }
  7435. var mode = cm.getModeAt(range.head);
  7436. var indented = false;
  7437. if (mode.electricChars) {
  7438. for (var j = 0; j < mode.electricChars.length; j++)
  7439. { if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) {
  7440. indented = indentLine(cm, range.head.line, "smart");
  7441. break
  7442. } }
  7443. } else if (mode.electricInput) {
  7444. if (mode.electricInput.test(getLine(cm.doc, range.head.line).text.slice(0, range.head.ch)))
  7445. { indented = indentLine(cm, range.head.line, "smart"); }
  7446. }
  7447. if (indented) { signalLater(cm, "electricInput", cm, range.head.line); }
  7448. }
  7449. }
  7450. function copyableRanges(cm) {
  7451. var text = [], ranges = [];
  7452. for (var i = 0; i < cm.doc.sel.ranges.length; i++) {
  7453. var line = cm.doc.sel.ranges[i].head.line;
  7454. var lineRange = {anchor: Pos(line, 0), head: Pos(line + 1, 0)};
  7455. ranges.push(lineRange);
  7456. text.push(cm.getRange(lineRange.anchor, lineRange.head));
  7457. }
  7458. return {text: text, ranges: ranges}
  7459. }
  7460. function disableBrowserMagic(field, spellcheck, autocorrect, autocapitalize) {
  7461. field.setAttribute("autocorrect", autocorrect ? "" : "off");
  7462. field.setAttribute("autocapitalize", autocapitalize ? "" : "off");
  7463. field.setAttribute("spellcheck", !!spellcheck);
  7464. }
  7465. function hiddenTextarea() {
  7466. var te = elt("textarea", null, null, "position: absolute; bottom: -1em; padding: 0; width: 1px; height: 1em; min-height: 1em; outline: none");
  7467. var div = elt("div", [te], null, "overflow: hidden; position: relative; width: 3px; height: 0px;");
  7468. // The textarea is kept positioned near the cursor to prevent the
  7469. // fact that it'll be scrolled into view on input from scrolling
  7470. // our fake cursor out of view. On webkit, when wrap=off, paste is
  7471. // very slow. So make the area wide instead.
  7472. if (webkit) { te.style.width = "1000px"; }
  7473. else { te.setAttribute("wrap", "off"); }
  7474. // If border: 0; -- iOS fails to open keyboard (issue #1287)
  7475. if (ios) { te.style.border = "1px solid black"; }
  7476. disableBrowserMagic(te);
  7477. return div
  7478. }
  7479. // The publicly visible API. Note that methodOp(f) means
  7480. // 'wrap f in an operation, performed on its `this` parameter'.
  7481. // This is not the complete set of editor methods. Most of the
  7482. // methods defined on the Doc type are also injected into
  7483. // CodeMirror.prototype, for backwards compatibility and
  7484. // convenience.
  7485. function addEditorMethods(CodeMirror) {
  7486. var optionHandlers = CodeMirror.optionHandlers;
  7487. var helpers = CodeMirror.helpers = {};
  7488. CodeMirror.prototype = {
  7489. constructor: CodeMirror,
  7490. focus: function(){window.focus(); this.display.input.focus();},
  7491. setOption: function(option, value) {
  7492. var options = this.options, old = options[option];
  7493. if (options[option] == value && option != "mode") { return }
  7494. options[option] = value;
  7495. if (optionHandlers.hasOwnProperty(option))
  7496. { operation(this, optionHandlers[option])(this, value, old); }
  7497. signal(this, "optionChange", this, option);
  7498. },
  7499. getOption: function(option) {return this.options[option]},
  7500. getDoc: function() {return this.doc},
  7501. addKeyMap: function(map, bottom) {
  7502. this.state.keyMaps[bottom ? "push" : "unshift"](getKeyMap(map));
  7503. },
  7504. removeKeyMap: function(map) {
  7505. var maps = this.state.keyMaps;
  7506. for (var i = 0; i < maps.length; ++i)
  7507. { if (maps[i] == map || maps[i].name == map) {
  7508. maps.splice(i, 1);
  7509. return true
  7510. } }
  7511. },
  7512. addOverlay: methodOp(function(spec, options) {
  7513. var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec);
  7514. if (mode.startState) { throw new Error("Overlays may not be stateful.") }
  7515. insertSorted(this.state.overlays,
  7516. {mode: mode, modeSpec: spec, opaque: options && options.opaque,
  7517. priority: (options && options.priority) || 0},
  7518. function (overlay) { return overlay.priority; });
  7519. this.state.modeGen++;
  7520. regChange(this);
  7521. }),
  7522. removeOverlay: methodOp(function(spec) {
  7523. var overlays = this.state.overlays;
  7524. for (var i = 0; i < overlays.length; ++i) {
  7525. var cur = overlays[i].modeSpec;
  7526. if (cur == spec || typeof spec == "string" && cur.name == spec) {
  7527. overlays.splice(i, 1);
  7528. this.state.modeGen++;
  7529. regChange(this);
  7530. return
  7531. }
  7532. }
  7533. }),
  7534. indentLine: methodOp(function(n, dir, aggressive) {
  7535. if (typeof dir != "string" && typeof dir != "number") {
  7536. if (dir == null) { dir = this.options.smartIndent ? "smart" : "prev"; }
  7537. else { dir = dir ? "add" : "subtract"; }
  7538. }
  7539. if (isLine(this.doc, n)) { indentLine(this, n, dir, aggressive); }
  7540. }),
  7541. indentSelection: methodOp(function(how) {
  7542. var ranges = this.doc.sel.ranges, end = -1;
  7543. for (var i = 0; i < ranges.length; i++) {
  7544. var range = ranges[i];
  7545. if (!range.empty()) {
  7546. var from = range.from(), to = range.to();
  7547. var start = Math.max(end, from.line);
  7548. end = Math.min(this.lastLine(), to.line - (to.ch ? 0 : 1)) + 1;
  7549. for (var j = start; j < end; ++j)
  7550. { indentLine(this, j, how); }
  7551. var newRanges = this.doc.sel.ranges;
  7552. if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i].from().ch > 0)
  7553. { replaceOneSelection(this.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll); }
  7554. } else if (range.head.line > end) {
  7555. indentLine(this, range.head.line, how, true);
  7556. end = range.head.line;
  7557. if (i == this.doc.sel.primIndex) { ensureCursorVisible(this); }
  7558. }
  7559. }
  7560. }),
  7561. // Fetch the parser token for a given character. Useful for hacks
  7562. // that want to inspect the mode state (say, for completion).
  7563. getTokenAt: function(pos, precise) {
  7564. return takeToken(this, pos, precise)
  7565. },
  7566. getLineTokens: function(line, precise) {
  7567. return takeToken(this, Pos(line), precise, true)
  7568. },
  7569. getTokenTypeAt: function(pos) {
  7570. pos = clipPos(this.doc, pos);
  7571. var styles = getLineStyles(this, getLine(this.doc, pos.line));
  7572. var before = 0, after = (styles.length - 1) / 2, ch = pos.ch;
  7573. var type;
  7574. if (ch == 0) { type = styles[2]; }
  7575. else { for (;;) {
  7576. var mid = (before + after) >> 1;
  7577. if ((mid ? styles[mid * 2 - 1] : 0) >= ch) { after = mid; }
  7578. else if (styles[mid * 2 + 1] < ch) { before = mid + 1; }
  7579. else { type = styles[mid * 2 + 2]; break }
  7580. } }
  7581. var cut = type ? type.indexOf("overlay ") : -1;
  7582. return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1)
  7583. },
  7584. getModeAt: function(pos) {
  7585. var mode = this.doc.mode;
  7586. if (!mode.innerMode) { return mode }
  7587. return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode
  7588. },
  7589. getHelper: function(pos, type) {
  7590. return this.getHelpers(pos, type)[0]
  7591. },
  7592. getHelpers: function(pos, type) {
  7593. var found = [];
  7594. if (!helpers.hasOwnProperty(type)) { return found }
  7595. var help = helpers[type], mode = this.getModeAt(pos);
  7596. if (typeof mode[type] == "string") {
  7597. if (help[mode[type]]) { found.push(help[mode[type]]); }
  7598. } else if (mode[type]) {
  7599. for (var i = 0; i < mode[type].length; i++) {
  7600. var val = help[mode[type][i]];
  7601. if (val) { found.push(val); }
  7602. }
  7603. } else if (mode.helperType && help[mode.helperType]) {
  7604. found.push(help[mode.helperType]);
  7605. } else if (help[mode.name]) {
  7606. found.push(help[mode.name]);
  7607. }
  7608. for (var i$1 = 0; i$1 < help._global.length; i$1++) {
  7609. var cur = help._global[i$1];
  7610. if (cur.pred(mode, this) && indexOf(found, cur.val) == -1)
  7611. { found.push(cur.val); }
  7612. }
  7613. return found
  7614. },
  7615. getStateAfter: function(line, precise) {
  7616. var doc = this.doc;
  7617. line = clipLine(doc, line == null ? doc.first + doc.size - 1: line);
  7618. return getContextBefore(this, line + 1, precise).state
  7619. },
  7620. cursorCoords: function(start, mode) {
  7621. var pos, range = this.doc.sel.primary();
  7622. if (start == null) { pos = range.head; }
  7623. else if (typeof start == "object") { pos = clipPos(this.doc, start); }
  7624. else { pos = start ? range.from() : range.to(); }
  7625. return cursorCoords(this, pos, mode || "page")
  7626. },
  7627. charCoords: function(pos, mode) {
  7628. return charCoords(this, clipPos(this.doc, pos), mode || "page")
  7629. },
  7630. coordsChar: function(coords, mode) {
  7631. coords = fromCoordSystem(this, coords, mode || "page");
  7632. return coordsChar(this, coords.left, coords.top)
  7633. },
  7634. lineAtHeight: function(height, mode) {
  7635. height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top;
  7636. return lineAtHeight(this.doc, height + this.display.viewOffset)
  7637. },
  7638. heightAtLine: function(line, mode, includeWidgets) {
  7639. var end = false, lineObj;
  7640. if (typeof line == "number") {
  7641. var last = this.doc.first + this.doc.size - 1;
  7642. if (line < this.doc.first) { line = this.doc.first; }
  7643. else if (line > last) { line = last; end = true; }
  7644. lineObj = getLine(this.doc, line);
  7645. } else {
  7646. lineObj = line;
  7647. }
  7648. return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || "page", includeWidgets || end).top +
  7649. (end ? this.doc.height - heightAtLine(lineObj) : 0)
  7650. },
  7651. defaultTextHeight: function() { return textHeight(this.display) },
  7652. defaultCharWidth: function() { return charWidth(this.display) },
  7653. getViewport: function() { return {from: this.display.viewFrom, to: this.display.viewTo}},
  7654. addWidget: function(pos, node, scroll, vert, horiz) {
  7655. var display = this.display;
  7656. pos = cursorCoords(this, clipPos(this.doc, pos));
  7657. var top = pos.bottom, left = pos.left;
  7658. node.style.position = "absolute";
  7659. node.setAttribute("cm-ignore-events", "true");
  7660. this.display.input.setUneditable(node);
  7661. display.sizer.appendChild(node);
  7662. if (vert == "over") {
  7663. top = pos.top;
  7664. } else if (vert == "above" || vert == "near") {
  7665. var vspace = Math.max(display.wrapper.clientHeight, this.doc.height),
  7666. hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth);
  7667. // Default to positioning above (if specified and possible); otherwise default to positioning below
  7668. if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight)
  7669. { top = pos.top - node.offsetHeight; }
  7670. else if (pos.bottom + node.offsetHeight <= vspace)
  7671. { top = pos.bottom; }
  7672. if (left + node.offsetWidth > hspace)
  7673. { left = hspace - node.offsetWidth; }
  7674. }
  7675. node.style.top = top + "px";
  7676. node.style.left = node.style.right = "";
  7677. if (horiz == "right") {
  7678. left = display.sizer.clientWidth - node.offsetWidth;
  7679. node.style.right = "0px";
  7680. } else {
  7681. if (horiz == "left") { left = 0; }
  7682. else if (horiz == "middle") { left = (display.sizer.clientWidth - node.offsetWidth) / 2; }
  7683. node.style.left = left + "px";
  7684. }
  7685. if (scroll)
  7686. { scrollIntoView(this, {left: left, top: top, right: left + node.offsetWidth, bottom: top + node.offsetHeight}); }
  7687. },
  7688. triggerOnKeyDown: methodOp(onKeyDown),
  7689. triggerOnKeyPress: methodOp(onKeyPress),
  7690. triggerOnKeyUp: onKeyUp,
  7691. triggerOnMouseDown: methodOp(onMouseDown),
  7692. execCommand: function(cmd) {
  7693. if (commands.hasOwnProperty(cmd))
  7694. { return commands[cmd].call(null, this) }
  7695. },
  7696. triggerElectric: methodOp(function(text) { triggerElectric(this, text); }),
  7697. findPosH: function(from, amount, unit, visually) {
  7698. var dir = 1;
  7699. if (amount < 0) { dir = -1; amount = -amount; }
  7700. var cur = clipPos(this.doc, from);
  7701. for (var i = 0; i < amount; ++i) {
  7702. cur = findPosH(this.doc, cur, dir, unit, visually);
  7703. if (cur.hitSide) { break }
  7704. }
  7705. return cur
  7706. },
  7707. moveH: methodOp(function(dir, unit) {
  7708. var this$1 = this;
  7709. this.extendSelectionsBy(function (range) {
  7710. if (this$1.display.shift || this$1.doc.extend || range.empty())
  7711. { return findPosH(this$1.doc, range.head, dir, unit, this$1.options.rtlMoveVisually) }
  7712. else
  7713. { return dir < 0 ? range.from() : range.to() }
  7714. }, sel_move);
  7715. }),
  7716. deleteH: methodOp(function(dir, unit) {
  7717. var sel = this.doc.sel, doc = this.doc;
  7718. if (sel.somethingSelected())
  7719. { doc.replaceSelection("", null, "+delete"); }
  7720. else
  7721. { deleteNearSelection(this, function (range) {
  7722. var other = findPosH(doc, range.head, dir, unit, false);
  7723. return dir < 0 ? {from: other, to: range.head} : {from: range.head, to: other}
  7724. }); }
  7725. }),
  7726. findPosV: function(from, amount, unit, goalColumn) {
  7727. var dir = 1, x = goalColumn;
  7728. if (amount < 0) { dir = -1; amount = -amount; }
  7729. var cur = clipPos(this.doc, from);
  7730. for (var i = 0; i < amount; ++i) {
  7731. var coords = cursorCoords(this, cur, "div");
  7732. if (x == null) { x = coords.left; }
  7733. else { coords.left = x; }
  7734. cur = findPosV(this, coords, dir, unit);
  7735. if (cur.hitSide) { break }
  7736. }
  7737. return cur
  7738. },
  7739. moveV: methodOp(function(dir, unit) {
  7740. var this$1 = this;
  7741. var doc = this.doc, goals = [];
  7742. var collapse = !this.display.shift && !doc.extend && doc.sel.somethingSelected();
  7743. doc.extendSelectionsBy(function (range) {
  7744. if (collapse)
  7745. { return dir < 0 ? range.from() : range.to() }
  7746. var headPos = cursorCoords(this$1, range.head, "div");
  7747. if (range.goalColumn != null) { headPos.left = range.goalColumn; }
  7748. goals.push(headPos.left);
  7749. var pos = findPosV(this$1, headPos, dir, unit);
  7750. if (unit == "page" && range == doc.sel.primary())
  7751. { addToScrollTop(this$1, charCoords(this$1, pos, "div").top - headPos.top); }
  7752. return pos
  7753. }, sel_move);
  7754. if (goals.length) { for (var i = 0; i < doc.sel.ranges.length; i++)
  7755. { doc.sel.ranges[i].goalColumn = goals[i]; } }
  7756. }),
  7757. // Find the word at the given position (as returned by coordsChar).
  7758. findWordAt: function(pos) {
  7759. var doc = this.doc, line = getLine(doc, pos.line).text;
  7760. var start = pos.ch, end = pos.ch;
  7761. if (line) {
  7762. var helper = this.getHelper(pos, "wordChars");
  7763. if ((pos.sticky == "before" || end == line.length) && start) { --start; } else { ++end; }
  7764. var startChar = line.charAt(start);
  7765. var check = isWordChar(startChar, helper)
  7766. ? function (ch) { return isWordChar(ch, helper); }
  7767. : /\s/.test(startChar) ? function (ch) { return /\s/.test(ch); }
  7768. : function (ch) { return (!/\s/.test(ch) && !isWordChar(ch)); };
  7769. while (start > 0 && check(line.charAt(start - 1))) { --start; }
  7770. while (end < line.length && check(line.charAt(end))) { ++end; }
  7771. }
  7772. return new Range(Pos(pos.line, start), Pos(pos.line, end))
  7773. },
  7774. toggleOverwrite: function(value) {
  7775. if (value != null && value == this.state.overwrite) { return }
  7776. if (this.state.overwrite = !this.state.overwrite)
  7777. { addClass(this.display.cursorDiv, "CodeMirror-overwrite"); }
  7778. else
  7779. { rmClass(this.display.cursorDiv, "CodeMirror-overwrite"); }
  7780. signal(this, "overwriteToggle", this, this.state.overwrite);
  7781. },
  7782. hasFocus: function() { return this.display.input.getField() == activeElt() },
  7783. isReadOnly: function() { return !!(this.options.readOnly || this.doc.cantEdit) },
  7784. scrollTo: methodOp(function (x, y) { scrollToCoords(this, x, y); }),
  7785. getScrollInfo: function() {
  7786. var scroller = this.display.scroller;
  7787. return {left: scroller.scrollLeft, top: scroller.scrollTop,
  7788. height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight,
  7789. width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth,
  7790. clientHeight: displayHeight(this), clientWidth: displayWidth(this)}
  7791. },
  7792. scrollIntoView: methodOp(function(range, margin) {
  7793. if (range == null) {
  7794. range = {from: this.doc.sel.primary().head, to: null};
  7795. if (margin == null) { margin = this.options.cursorScrollMargin; }
  7796. } else if (typeof range == "number") {
  7797. range = {from: Pos(range, 0), to: null};
  7798. } else if (range.from == null) {
  7799. range = {from: range, to: null};
  7800. }
  7801. if (!range.to) { range.to = range.from; }
  7802. range.margin = margin || 0;
  7803. if (range.from.line != null) {
  7804. scrollToRange(this, range);
  7805. } else {
  7806. scrollToCoordsRange(this, range.from, range.to, range.margin);
  7807. }
  7808. }),
  7809. setSize: methodOp(function(width, height) {
  7810. var this$1 = this;
  7811. var interpret = function (val) { return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val; };
  7812. if (width != null) { this.display.wrapper.style.width = interpret(width); }
  7813. if (height != null) { this.display.wrapper.style.height = interpret(height); }
  7814. if (this.options.lineWrapping) { clearLineMeasurementCache(this); }
  7815. var lineNo = this.display.viewFrom;
  7816. this.doc.iter(lineNo, this.display.viewTo, function (line) {
  7817. if (line.widgets) { for (var i = 0; i < line.widgets.length; i++)
  7818. { if (line.widgets[i].noHScroll) { regLineChange(this$1, lineNo, "widget"); break } } }
  7819. ++lineNo;
  7820. });
  7821. this.curOp.forceUpdate = true;
  7822. signal(this, "refresh", this);
  7823. }),
  7824. operation: function(f){return runInOp(this, f)},
  7825. startOperation: function(){return startOperation(this)},
  7826. endOperation: function(){return endOperation(this)},
  7827. refresh: methodOp(function() {
  7828. var oldHeight = this.display.cachedTextHeight;
  7829. regChange(this);
  7830. this.curOp.forceUpdate = true;
  7831. clearCaches(this);
  7832. scrollToCoords(this, this.doc.scrollLeft, this.doc.scrollTop);
  7833. updateGutterSpace(this.display);
  7834. if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5 || this.options.lineWrapping)
  7835. { estimateLineHeights(this); }
  7836. signal(this, "refresh", this);
  7837. }),
  7838. swapDoc: methodOp(function(doc) {
  7839. var old = this.doc;
  7840. old.cm = null;
  7841. // Cancel the current text selection if any (#5821)
  7842. if (this.state.selectingText) { this.state.selectingText(); }
  7843. attachDoc(this, doc);
  7844. clearCaches(this);
  7845. this.display.input.reset();
  7846. scrollToCoords(this, doc.scrollLeft, doc.scrollTop);
  7847. this.curOp.forceScroll = true;
  7848. signalLater(this, "swapDoc", this, old);
  7849. return old
  7850. }),
  7851. phrase: function(phraseText) {
  7852. var phrases = this.options.phrases;
  7853. return phrases && Object.prototype.hasOwnProperty.call(phrases, phraseText) ? phrases[phraseText] : phraseText
  7854. },
  7855. getInputField: function(){return this.display.input.getField()},
  7856. getWrapperElement: function(){return this.display.wrapper},
  7857. getScrollerElement: function(){return this.display.scroller},
  7858. getGutterElement: function(){return this.display.gutters}
  7859. };
  7860. eventMixin(CodeMirror);
  7861. CodeMirror.registerHelper = function(type, name, value) {
  7862. if (!helpers.hasOwnProperty(type)) { helpers[type] = CodeMirror[type] = {_global: []}; }
  7863. helpers[type][name] = value;
  7864. };
  7865. CodeMirror.registerGlobalHelper = function(type, name, predicate, value) {
  7866. CodeMirror.registerHelper(type, name, value);
  7867. helpers[type]._global.push({pred: predicate, val: value});
  7868. };
  7869. }
  7870. // Used for horizontal relative motion. Dir is -1 or 1 (left or
  7871. // right), unit can be "codepoint", "char", "column" (like char, but
  7872. // doesn't cross line boundaries), "word" (across next word), or
  7873. // "group" (to the start of next group of word or
  7874. // non-word-non-whitespace chars). The visually param controls
  7875. // whether, in right-to-left text, direction 1 means to move towards
  7876. // the next index in the string, or towards the character to the right
  7877. // of the current position. The resulting position will have a
  7878. // hitSide=true property if it reached the end of the document.
  7879. function findPosH(doc, pos, dir, unit, visually) {
  7880. var oldPos = pos;
  7881. var origDir = dir;
  7882. var lineObj = getLine(doc, pos.line);
  7883. var lineDir = visually && doc.direction == "rtl" ? -dir : dir;
  7884. function findNextLine() {
  7885. var l = pos.line + lineDir;
  7886. if (l < doc.first || l >= doc.first + doc.size) { return false }
  7887. pos = new Pos(l, pos.ch, pos.sticky);
  7888. return lineObj = getLine(doc, l)
  7889. }
  7890. function moveOnce(boundToLine) {
  7891. var next;
  7892. if (unit == "codepoint") {
  7893. var ch = lineObj.text.charCodeAt(pos.ch + (dir > 0 ? 0 : -1));
  7894. if (isNaN(ch)) {
  7895. next = null;
  7896. } else {
  7897. var astral = dir > 0 ? ch >= 0xD800 && ch < 0xDC00 : ch >= 0xDC00 && ch < 0xDFFF;
  7898. next = new Pos(pos.line, Math.max(0, Math.min(lineObj.text.length, pos.ch + dir * (astral ? 2 : 1))), -dir);
  7899. }
  7900. } else if (visually) {
  7901. next = moveVisually(doc.cm, lineObj, pos, dir);
  7902. } else {
  7903. next = moveLogically(lineObj, pos, dir);
  7904. }
  7905. if (next == null) {
  7906. if (!boundToLine && findNextLine())
  7907. { pos = endOfLine(visually, doc.cm, lineObj, pos.line, lineDir); }
  7908. else
  7909. { return false }
  7910. } else {
  7911. pos = next;
  7912. }
  7913. return true
  7914. }
  7915. if (unit == "char" || unit == "codepoint") {
  7916. moveOnce();
  7917. } else if (unit == "column") {
  7918. moveOnce(true);
  7919. } else if (unit == "word" || unit == "group") {
  7920. var sawType = null, group = unit == "group";
  7921. var helper = doc.cm && doc.cm.getHelper(pos, "wordChars");
  7922. for (var first = true;; first = false) {
  7923. if (dir < 0 && !moveOnce(!first)) { break }
  7924. var cur = lineObj.text.charAt(pos.ch) || "\n";
  7925. var type = isWordChar(cur, helper) ? "w"
  7926. : group && cur == "\n" ? "n"
  7927. : !group || /\s/.test(cur) ? null
  7928. : "p";
  7929. if (group && !first && !type) { type = "s"; }
  7930. if (sawType && sawType != type) {
  7931. if (dir < 0) {dir = 1; moveOnce(); pos.sticky = "after";}
  7932. break
  7933. }
  7934. if (type) { sawType = type; }
  7935. if (dir > 0 && !moveOnce(!first)) { break }
  7936. }
  7937. }
  7938. var result = skipAtomic(doc, pos, oldPos, origDir, true);
  7939. if (equalCursorPos(oldPos, result)) { result.hitSide = true; }
  7940. return result
  7941. }
  7942. // For relative vertical movement. Dir may be -1 or 1. Unit can be
  7943. // "page" or "line". The resulting position will have a hitSide=true
  7944. // property if it reached the end of the document.
  7945. function findPosV(cm, pos, dir, unit) {
  7946. var doc = cm.doc, x = pos.left, y;
  7947. if (unit == "page") {
  7948. var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight);
  7949. var moveAmount = Math.max(pageSize - .5 * textHeight(cm.display), 3);
  7950. y = (dir > 0 ? pos.bottom : pos.top) + dir * moveAmount;
  7951. } else if (unit == "line") {
  7952. y = dir > 0 ? pos.bottom + 3 : pos.top - 3;
  7953. }
  7954. var target;
  7955. for (;;) {
  7956. target = coordsChar(cm, x, y);
  7957. if (!target.outside) { break }
  7958. if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break }
  7959. y += dir * 5;
  7960. }
  7961. return target
  7962. }
  7963. // CONTENTEDITABLE INPUT STYLE
  7964. var ContentEditableInput = function(cm) {
  7965. this.cm = cm;
  7966. this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null;
  7967. this.polling = new Delayed();
  7968. this.composing = null;
  7969. this.gracePeriod = false;
  7970. this.readDOMTimeout = null;
  7971. };
  7972. ContentEditableInput.prototype.init = function (display) {
  7973. var this$1 = this;
  7974. var input = this, cm = input.cm;
  7975. var div = input.div = display.lineDiv;
  7976. div.contentEditable = true;
  7977. disableBrowserMagic(div, cm.options.spellcheck, cm.options.autocorrect, cm.options.autocapitalize);
  7978. function belongsToInput(e) {
  7979. for (var t = e.target; t; t = t.parentNode) {
  7980. if (t == div) { return true }
  7981. if (/\bCodeMirror-(?:line)?widget\b/.test(t.className)) { break }
  7982. }
  7983. return false
  7984. }
  7985. on(div, "paste", function (e) {
  7986. if (!belongsToInput(e) || signalDOMEvent(cm, e) || handlePaste(e, cm)) { return }
  7987. // IE doesn't fire input events, so we schedule a read for the pasted content in this way
  7988. if (ie_version <= 11) { setTimeout(operation(cm, function () { return this$1.updateFromDOM(); }), 20); }
  7989. });
  7990. on(div, "compositionstart", function (e) {
  7991. this$1.composing = {data: e.data, done: false};
  7992. });
  7993. on(div, "compositionupdate", function (e) {
  7994. if (!this$1.composing) { this$1.composing = {data: e.data, done: false}; }
  7995. });
  7996. on(div, "compositionend", function (e) {
  7997. if (this$1.composing) {
  7998. if (e.data != this$1.composing.data) { this$1.readFromDOMSoon(); }
  7999. this$1.composing.done = true;
  8000. }
  8001. });
  8002. on(div, "touchstart", function () { return input.forceCompositionEnd(); });
  8003. on(div, "input", function () {
  8004. if (!this$1.composing) { this$1.readFromDOMSoon(); }
  8005. });
  8006. function onCopyCut(e) {
  8007. if (!belongsToInput(e) || signalDOMEvent(cm, e)) { return }
  8008. if (cm.somethingSelected()) {
  8009. setLastCopied({lineWise: false, text: cm.getSelections()});
  8010. if (e.type == "cut") { cm.replaceSelection("", null, "cut"); }
  8011. } else if (!cm.options.lineWiseCopyCut) {
  8012. return
  8013. } else {
  8014. var ranges = copyableRanges(cm);
  8015. setLastCopied({lineWise: true, text: ranges.text});
  8016. if (e.type == "cut") {
  8017. cm.operation(function () {
  8018. cm.setSelections(ranges.ranges, 0, sel_dontScroll);
  8019. cm.replaceSelection("", null, "cut");
  8020. });
  8021. }
  8022. }
  8023. if (e.clipboardData) {
  8024. e.clipboardData.clearData();
  8025. var content = lastCopied.text.join("\n");
  8026. // iOS exposes the clipboard API, but seems to discard content inserted into it
  8027. e.clipboardData.setData("Text", content);
  8028. if (e.clipboardData.getData("Text") == content) {
  8029. e.preventDefault();
  8030. return
  8031. }
  8032. }
  8033. // Old-fashioned briefly-focus-a-textarea hack
  8034. var kludge = hiddenTextarea(), te = kludge.firstChild;
  8035. cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild);
  8036. te.value = lastCopied.text.join("\n");
  8037. var hadFocus = activeElt();
  8038. selectInput(te);
  8039. setTimeout(function () {
  8040. cm.display.lineSpace.removeChild(kludge);
  8041. hadFocus.focus();
  8042. if (hadFocus == div) { input.showPrimarySelection(); }
  8043. }, 50);
  8044. }
  8045. on(div, "copy", onCopyCut);
  8046. on(div, "cut", onCopyCut);
  8047. };
  8048. ContentEditableInput.prototype.screenReaderLabelChanged = function (label) {
  8049. // Label for screenreaders, accessibility
  8050. if(label) {
  8051. this.div.setAttribute('aria-label', label);
  8052. } else {
  8053. this.div.removeAttribute('aria-label');
  8054. }
  8055. };
  8056. ContentEditableInput.prototype.prepareSelection = function () {
  8057. var result = prepareSelection(this.cm, false);
  8058. result.focus = activeElt() == this.div;
  8059. return result
  8060. };
  8061. ContentEditableInput.prototype.showSelection = function (info, takeFocus) {
  8062. if (!info || !this.cm.display.view.length) { return }
  8063. if (info.focus || takeFocus) { this.showPrimarySelection(); }
  8064. this.showMultipleSelections(info);
  8065. };
  8066. ContentEditableInput.prototype.getSelection = function () {
  8067. return this.cm.display.wrapper.ownerDocument.getSelection()
  8068. };
  8069. ContentEditableInput.prototype.showPrimarySelection = function () {
  8070. var sel = this.getSelection(), cm = this.cm, prim = cm.doc.sel.primary();
  8071. var from = prim.from(), to = prim.to();
  8072. if (cm.display.viewTo == cm.display.viewFrom || from.line >= cm.display.viewTo || to.line < cm.display.viewFrom) {
  8073. sel.removeAllRanges();
  8074. return
  8075. }
  8076. var curAnchor = domToPos(cm, sel.anchorNode, sel.anchorOffset);
  8077. var curFocus = domToPos(cm, sel.focusNode, sel.focusOffset);
  8078. if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad &&
  8079. cmp(minPos(curAnchor, curFocus), from) == 0 &&
  8080. cmp(maxPos(curAnchor, curFocus), to) == 0)
  8081. { return }
  8082. var view = cm.display.view;
  8083. var start = (from.line >= cm.display.viewFrom && posToDOM(cm, from)) ||
  8084. {node: view[0].measure.map[2], offset: 0};
  8085. var end = to.line < cm.display.viewTo && posToDOM(cm, to);
  8086. if (!end) {
  8087. var measure = view[view.length - 1].measure;
  8088. var map = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map;
  8089. end = {node: map[map.length - 1], offset: map[map.length - 2] - map[map.length - 3]};
  8090. }
  8091. if (!start || !end) {
  8092. sel.removeAllRanges();
  8093. return
  8094. }
  8095. var old = sel.rangeCount && sel.getRangeAt(0), rng;
  8096. try { rng = range(start.node, start.offset, end.offset, end.node); }
  8097. catch(e) {} // Our model of the DOM might be outdated, in which case the range we try to set can be impossible
  8098. if (rng) {
  8099. if (!gecko && cm.state.focused) {
  8100. sel.collapse(start.node, start.offset);
  8101. if (!rng.collapsed) {
  8102. sel.removeAllRanges();
  8103. sel.addRange(rng);
  8104. }
  8105. } else {
  8106. sel.removeAllRanges();
  8107. sel.addRange(rng);
  8108. }
  8109. if (old && sel.anchorNode == null) { sel.addRange(old); }
  8110. else if (gecko) { this.startGracePeriod(); }
  8111. }
  8112. this.rememberSelection();
  8113. };
  8114. ContentEditableInput.prototype.startGracePeriod = function () {
  8115. var this$1 = this;
  8116. clearTimeout(this.gracePeriod);
  8117. this.gracePeriod = setTimeout(function () {
  8118. this$1.gracePeriod = false;
  8119. if (this$1.selectionChanged())
  8120. { this$1.cm.operation(function () { return this$1.cm.curOp.selectionChanged = true; }); }
  8121. }, 20);
  8122. };
  8123. ContentEditableInput.prototype.showMultipleSelections = function (info) {
  8124. removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors);
  8125. removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection);
  8126. };
  8127. ContentEditableInput.prototype.rememberSelection = function () {
  8128. var sel = this.getSelection();
  8129. this.lastAnchorNode = sel.anchorNode; this.lastAnchorOffset = sel.anchorOffset;
  8130. this.lastFocusNode = sel.focusNode; this.lastFocusOffset = sel.focusOffset;
  8131. };
  8132. ContentEditableInput.prototype.selectionInEditor = function () {
  8133. var sel = this.getSelection();
  8134. if (!sel.rangeCount) { return false }
  8135. var node = sel.getRangeAt(0).commonAncestorContainer;
  8136. return contains(this.div, node)
  8137. };
  8138. ContentEditableInput.prototype.focus = function () {
  8139. if (this.cm.options.readOnly != "nocursor") {
  8140. if (!this.selectionInEditor() || activeElt() != this.div)
  8141. { this.showSelection(this.prepareSelection(), true); }
  8142. this.div.focus();
  8143. }
  8144. };
  8145. ContentEditableInput.prototype.blur = function () { this.div.blur(); };
  8146. ContentEditableInput.prototype.getField = function () { return this.div };
  8147. ContentEditableInput.prototype.supportsTouch = function () { return true };
  8148. ContentEditableInput.prototype.receivedFocus = function () {
  8149. var this$1 = this;
  8150. var input = this;
  8151. if (this.selectionInEditor())
  8152. { setTimeout(function () { return this$1.pollSelection(); }, 20); }
  8153. else
  8154. { runInOp(this.cm, function () { return input.cm.curOp.selectionChanged = true; }); }
  8155. function poll() {
  8156. if (input.cm.state.focused) {
  8157. input.pollSelection();
  8158. input.polling.set(input.cm.options.pollInterval, poll);
  8159. }
  8160. }
  8161. this.polling.set(this.cm.options.pollInterval, poll);
  8162. };
  8163. ContentEditableInput.prototype.selectionChanged = function () {
  8164. var sel = this.getSelection();
  8165. return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset ||
  8166. sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset
  8167. };
  8168. ContentEditableInput.prototype.pollSelection = function () {
  8169. if (this.readDOMTimeout != null || this.gracePeriod || !this.selectionChanged()) { return }
  8170. var sel = this.getSelection(), cm = this.cm;
  8171. // On Android Chrome (version 56, at least), backspacing into an
  8172. // uneditable block element will put the cursor in that element,
  8173. // and then, because it's not editable, hide the virtual keyboard.
  8174. // Because Android doesn't allow us to actually detect backspace
  8175. // presses in a sane way, this code checks for when that happens
  8176. // and simulates a backspace press in this case.
  8177. if (android && chrome && this.cm.display.gutterSpecs.length && isInGutter(sel.anchorNode)) {
  8178. this.cm.triggerOnKeyDown({type: "keydown", keyCode: 8, preventDefault: Math.abs});
  8179. this.blur();
  8180. this.focus();
  8181. return
  8182. }
  8183. if (this.composing) { return }
  8184. this.rememberSelection();
  8185. var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset);
  8186. var head = domToPos(cm, sel.focusNode, sel.focusOffset);
  8187. if (anchor && head) { runInOp(cm, function () {
  8188. setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll);
  8189. if (anchor.bad || head.bad) { cm.curOp.selectionChanged = true; }
  8190. }); }
  8191. };
  8192. ContentEditableInput.prototype.pollContent = function () {
  8193. if (this.readDOMTimeout != null) {
  8194. clearTimeout(this.readDOMTimeout);
  8195. this.readDOMTimeout = null;
  8196. }
  8197. var cm = this.cm, display = cm.display, sel = cm.doc.sel.primary();
  8198. var from = sel.from(), to = sel.to();
  8199. if (from.ch == 0 && from.line > cm.firstLine())
  8200. { from = Pos(from.line - 1, getLine(cm.doc, from.line - 1).length); }
  8201. if (to.ch == getLine(cm.doc, to.line).text.length && to.line < cm.lastLine())
  8202. { to = Pos(to.line + 1, 0); }
  8203. if (from.line < display.viewFrom || to.line > display.viewTo - 1) { return false }
  8204. var fromIndex, fromLine, fromNode;
  8205. if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) {
  8206. fromLine = lineNo(display.view[0].line);
  8207. fromNode = display.view[0].node;
  8208. } else {
  8209. fromLine = lineNo(display.view[fromIndex].line);
  8210. fromNode = display.view[fromIndex - 1].node.nextSibling;
  8211. }
  8212. var toIndex = findViewIndex(cm, to.line);
  8213. var toLine, toNode;
  8214. if (toIndex == display.view.length - 1) {
  8215. toLine = display.viewTo - 1;
  8216. toNode = display.lineDiv.lastChild;
  8217. } else {
  8218. toLine = lineNo(display.view[toIndex + 1].line) - 1;
  8219. toNode = display.view[toIndex + 1].node.previousSibling;
  8220. }
  8221. if (!fromNode) { return false }
  8222. var newText = cm.doc.splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine));
  8223. var oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length));
  8224. while (newText.length > 1 && oldText.length > 1) {
  8225. if (lst(newText) == lst(oldText)) { newText.pop(); oldText.pop(); toLine--; }
  8226. else if (newText[0] == oldText[0]) { newText.shift(); oldText.shift(); fromLine++; }
  8227. else { break }
  8228. }
  8229. var cutFront = 0, cutEnd = 0;
  8230. var newTop = newText[0], oldTop = oldText[0], maxCutFront = Math.min(newTop.length, oldTop.length);
  8231. while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront))
  8232. { ++cutFront; }
  8233. var newBot = lst(newText), oldBot = lst(oldText);
  8234. var maxCutEnd = Math.min(newBot.length - (newText.length == 1 ? cutFront : 0),
  8235. oldBot.length - (oldText.length == 1 ? cutFront : 0));
  8236. while (cutEnd < maxCutEnd &&
  8237. newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1))
  8238. { ++cutEnd; }
  8239. // Try to move start of change to start of selection if ambiguous
  8240. if (newText.length == 1 && oldText.length == 1 && fromLine == from.line) {
  8241. while (cutFront && cutFront > from.ch &&
  8242. newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) {
  8243. cutFront--;
  8244. cutEnd++;
  8245. }
  8246. }
  8247. newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd).replace(/^\u200b+/, "");
  8248. newText[0] = newText[0].slice(cutFront).replace(/\u200b+$/, "");
  8249. var chFrom = Pos(fromLine, cutFront);
  8250. var chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0);
  8251. if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) {
  8252. replaceRange(cm.doc, newText, chFrom, chTo, "+input");
  8253. return true
  8254. }
  8255. };
  8256. ContentEditableInput.prototype.ensurePolled = function () {
  8257. this.forceCompositionEnd();
  8258. };
  8259. ContentEditableInput.prototype.reset = function () {
  8260. this.forceCompositionEnd();
  8261. };
  8262. ContentEditableInput.prototype.forceCompositionEnd = function () {
  8263. if (!this.composing) { return }
  8264. clearTimeout(this.readDOMTimeout);
  8265. this.composing = null;
  8266. this.updateFromDOM();
  8267. this.div.blur();
  8268. this.div.focus();
  8269. };
  8270. ContentEditableInput.prototype.readFromDOMSoon = function () {
  8271. var this$1 = this;
  8272. if (this.readDOMTimeout != null) { return }
  8273. this.readDOMTimeout = setTimeout(function () {
  8274. this$1.readDOMTimeout = null;
  8275. if (this$1.composing) {
  8276. if (this$1.composing.done) { this$1.composing = null; }
  8277. else { return }
  8278. }
  8279. this$1.updateFromDOM();
  8280. }, 80);
  8281. };
  8282. ContentEditableInput.prototype.updateFromDOM = function () {
  8283. var this$1 = this;
  8284. if (this.cm.isReadOnly() || !this.pollContent())
  8285. { runInOp(this.cm, function () { return regChange(this$1.cm); }); }
  8286. };
  8287. ContentEditableInput.prototype.setUneditable = function (node) {
  8288. node.contentEditable = "false";
  8289. };
  8290. ContentEditableInput.prototype.onKeyPress = function (e) {
  8291. if (e.charCode == 0 || this.composing) { return }
  8292. e.preventDefault();
  8293. if (!this.cm.isReadOnly())
  8294. { operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0); }
  8295. };
  8296. ContentEditableInput.prototype.readOnlyChanged = function (val) {
  8297. this.div.contentEditable = String(val != "nocursor");
  8298. };
  8299. ContentEditableInput.prototype.onContextMenu = function () {};
  8300. ContentEditableInput.prototype.resetPosition = function () {};
  8301. ContentEditableInput.prototype.needsContentAttribute = true;
  8302. function posToDOM(cm, pos) {
  8303. var view = findViewForLine(cm, pos.line);
  8304. if (!view || view.hidden) { return null }
  8305. var line = getLine(cm.doc, pos.line);
  8306. var info = mapFromLineView(view, line, pos.line);
  8307. var order = getOrder(line, cm.doc.direction), side = "left";
  8308. if (order) {
  8309. var partPos = getBidiPartAt(order, pos.ch);
  8310. side = partPos % 2 ? "right" : "left";
  8311. }
  8312. var result = nodeAndOffsetInLineMap(info.map, pos.ch, side);
  8313. result.offset = result.collapse == "right" ? result.end : result.start;
  8314. return result
  8315. }
  8316. function isInGutter(node) {
  8317. for (var scan = node; scan; scan = scan.parentNode)
  8318. { if (/CodeMirror-gutter-wrapper/.test(scan.className)) { return true } }
  8319. return false
  8320. }
  8321. function badPos(pos, bad) { if (bad) { pos.bad = true; } return pos }
  8322. function domTextBetween(cm, from, to, fromLine, toLine) {
  8323. var text = "", closing = false, lineSep = cm.doc.lineSeparator(), extraLinebreak = false;
  8324. function recognizeMarker(id) { return function (marker) { return marker.id == id; } }
  8325. function close() {
  8326. if (closing) {
  8327. text += lineSep;
  8328. if (extraLinebreak) { text += lineSep; }
  8329. closing = extraLinebreak = false;
  8330. }
  8331. }
  8332. function addText(str) {
  8333. if (str) {
  8334. close();
  8335. text += str;
  8336. }
  8337. }
  8338. function walk(node) {
  8339. if (node.nodeType == 1) {
  8340. var cmText = node.getAttribute("cm-text");
  8341. if (cmText) {
  8342. addText(cmText);
  8343. return
  8344. }
  8345. var markerID = node.getAttribute("cm-marker"), range;
  8346. if (markerID) {
  8347. var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID));
  8348. if (found.length && (range = found[0].find(0)))
  8349. { addText(getBetween(cm.doc, range.from, range.to).join(lineSep)); }
  8350. return
  8351. }
  8352. if (node.getAttribute("contenteditable") == "false") { return }
  8353. var isBlock = /^(pre|div|p|li|table|br)$/i.test(node.nodeName);
  8354. if (!/^br$/i.test(node.nodeName) && node.textContent.length == 0) { return }
  8355. if (isBlock) { close(); }
  8356. for (var i = 0; i < node.childNodes.length; i++)
  8357. { walk(node.childNodes[i]); }
  8358. if (/^(pre|p)$/i.test(node.nodeName)) { extraLinebreak = true; }
  8359. if (isBlock) { closing = true; }
  8360. } else if (node.nodeType == 3) {
  8361. addText(node.nodeValue.replace(/\u200b/g, "").replace(/\u00a0/g, " "));
  8362. }
  8363. }
  8364. for (;;) {
  8365. walk(from);
  8366. if (from == to) { break }
  8367. from = from.nextSibling;
  8368. extraLinebreak = false;
  8369. }
  8370. return text
  8371. }
  8372. function domToPos(cm, node, offset) {
  8373. var lineNode;
  8374. if (node == cm.display.lineDiv) {
  8375. lineNode = cm.display.lineDiv.childNodes[offset];
  8376. if (!lineNode) { return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true) }
  8377. node = null; offset = 0;
  8378. } else {
  8379. for (lineNode = node;; lineNode = lineNode.parentNode) {
  8380. if (!lineNode || lineNode == cm.display.lineDiv) { return null }
  8381. if (lineNode.parentNode && lineNode.parentNode == cm.display.lineDiv) { break }
  8382. }
  8383. }
  8384. for (var i = 0; i < cm.display.view.length; i++) {
  8385. var lineView = cm.display.view[i];
  8386. if (lineView.node == lineNode)
  8387. { return locateNodeInLineView(lineView, node, offset) }
  8388. }
  8389. }
  8390. function locateNodeInLineView(lineView, node, offset) {
  8391. var wrapper = lineView.text.firstChild, bad = false;
  8392. if (!node || !contains(wrapper, node)) { return badPos(Pos(lineNo(lineView.line), 0), true) }
  8393. if (node == wrapper) {
  8394. bad = true;
  8395. node = wrapper.childNodes[offset];
  8396. offset = 0;
  8397. if (!node) {
  8398. var line = lineView.rest ? lst(lineView.rest) : lineView.line;
  8399. return badPos(Pos(lineNo(line), line.text.length), bad)
  8400. }
  8401. }
  8402. var textNode = node.nodeType == 3 ? node : null, topNode = node;
  8403. if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) {
  8404. textNode = node.firstChild;
  8405. if (offset) { offset = textNode.nodeValue.length; }
  8406. }
  8407. while (topNode.parentNode != wrapper) { topNode = topNode.parentNode; }
  8408. var measure = lineView.measure, maps = measure.maps;
  8409. function find(textNode, topNode, offset) {
  8410. for (var i = -1; i < (maps ? maps.length : 0); i++) {
  8411. var map = i < 0 ? measure.map : maps[i];
  8412. for (var j = 0; j < map.length; j += 3) {
  8413. var curNode = map[j + 2];
  8414. if (curNode == textNode || curNode == topNode) {
  8415. var line = lineNo(i < 0 ? lineView.line : lineView.rest[i]);
  8416. var ch = map[j] + offset;
  8417. if (offset < 0 || curNode != textNode) { ch = map[j + (offset ? 1 : 0)]; }
  8418. return Pos(line, ch)
  8419. }
  8420. }
  8421. }
  8422. }
  8423. var found = find(textNode, topNode, offset);
  8424. if (found) { return badPos(found, bad) }
  8425. // FIXME this is all really shaky. might handle the few cases it needs to handle, but likely to cause problems
  8426. for (var after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) {
  8427. found = find(after, after.firstChild, 0);
  8428. if (found)
  8429. { return badPos(Pos(found.line, found.ch - dist), bad) }
  8430. else
  8431. { dist += after.textContent.length; }
  8432. }
  8433. for (var before = topNode.previousSibling, dist$1 = offset; before; before = before.previousSibling) {
  8434. found = find(before, before.firstChild, -1);
  8435. if (found)
  8436. { return badPos(Pos(found.line, found.ch + dist$1), bad) }
  8437. else
  8438. { dist$1 += before.textContent.length; }
  8439. }
  8440. }
  8441. // TEXTAREA INPUT STYLE
  8442. var TextareaInput = function(cm) {
  8443. this.cm = cm;
  8444. // See input.poll and input.reset
  8445. this.prevInput = "";
  8446. // Flag that indicates whether we expect input to appear real soon
  8447. // now (after some event like 'keypress' or 'input') and are
  8448. // polling intensively.
  8449. this.pollingFast = false;
  8450. // Self-resetting timeout for the poller
  8451. this.polling = new Delayed();
  8452. // Used to work around IE issue with selection being forgotten when focus moves away from textarea
  8453. this.hasSelection = false;
  8454. this.composing = null;
  8455. };
  8456. TextareaInput.prototype.init = function (display) {
  8457. var this$1 = this;
  8458. var input = this, cm = this.cm;
  8459. this.createField(display);
  8460. var te = this.textarea;
  8461. display.wrapper.insertBefore(this.wrapper, display.wrapper.firstChild);
  8462. // Needed to hide big blue blinking cursor on Mobile Safari (doesn't seem to work in iOS 8 anymore)
  8463. if (ios) { te.style.width = "0px"; }
  8464. on(te, "input", function () {
  8465. if (ie && ie_version >= 9 && this$1.hasSelection) { this$1.hasSelection = null; }
  8466. input.poll();
  8467. });
  8468. on(te, "paste", function (e) {
  8469. if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { return }
  8470. cm.state.pasteIncoming = +new Date;
  8471. input.fastPoll();
  8472. });
  8473. function prepareCopyCut(e) {
  8474. if (signalDOMEvent(cm, e)) { return }
  8475. if (cm.somethingSelected()) {
  8476. setLastCopied({lineWise: false, text: cm.getSelections()});
  8477. } else if (!cm.options.lineWiseCopyCut) {
  8478. return
  8479. } else {
  8480. var ranges = copyableRanges(cm);
  8481. setLastCopied({lineWise: true, text: ranges.text});
  8482. if (e.type == "cut") {
  8483. cm.setSelections(ranges.ranges, null, sel_dontScroll);
  8484. } else {
  8485. input.prevInput = "";
  8486. te.value = ranges.text.join("\n");
  8487. selectInput(te);
  8488. }
  8489. }
  8490. if (e.type == "cut") { cm.state.cutIncoming = +new Date; }
  8491. }
  8492. on(te, "cut", prepareCopyCut);
  8493. on(te, "copy", prepareCopyCut);
  8494. on(display.scroller, "paste", function (e) {
  8495. if (eventInWidget(display, e) || signalDOMEvent(cm, e)) { return }
  8496. if (!te.dispatchEvent) {
  8497. cm.state.pasteIncoming = +new Date;
  8498. input.focus();
  8499. return
  8500. }
  8501. // Pass the `paste` event to the textarea so it's handled by its event listener.
  8502. var event = new Event("paste");
  8503. event.clipboardData = e.clipboardData;
  8504. te.dispatchEvent(event);
  8505. });
  8506. // Prevent normal selection in the editor (we handle our own)
  8507. on(display.lineSpace, "selectstart", function (e) {
  8508. if (!eventInWidget(display, e)) { e_preventDefault(e); }
  8509. });
  8510. on(te, "compositionstart", function () {
  8511. var start = cm.getCursor("from");
  8512. if (input.composing) { input.composing.range.clear(); }
  8513. input.composing = {
  8514. start: start,
  8515. range: cm.markText(start, cm.getCursor("to"), {className: "CodeMirror-composing"})
  8516. };
  8517. });
  8518. on(te, "compositionend", function () {
  8519. if (input.composing) {
  8520. input.poll();
  8521. input.composing.range.clear();
  8522. input.composing = null;
  8523. }
  8524. });
  8525. };
  8526. TextareaInput.prototype.createField = function (_display) {
  8527. // Wraps and hides input textarea
  8528. this.wrapper = hiddenTextarea();
  8529. // The semihidden textarea that is focused when the editor is
  8530. // focused, and receives input.
  8531. this.textarea = this.wrapper.firstChild;
  8532. };
  8533. TextareaInput.prototype.screenReaderLabelChanged = function (label) {
  8534. // Label for screenreaders, accessibility
  8535. if(label) {
  8536. this.textarea.setAttribute('aria-label', label);
  8537. } else {
  8538. this.textarea.removeAttribute('aria-label');
  8539. }
  8540. };
  8541. TextareaInput.prototype.prepareSelection = function () {
  8542. // Redraw the selection and/or cursor
  8543. var cm = this.cm, display = cm.display, doc = cm.doc;
  8544. var result = prepareSelection(cm);
  8545. // Move the hidden textarea near the cursor to prevent scrolling artifacts
  8546. if (cm.options.moveInputWithCursor) {
  8547. var headPos = cursorCoords(cm, doc.sel.primary().head, "div");
  8548. var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect();
  8549. result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10,
  8550. headPos.top + lineOff.top - wrapOff.top));
  8551. result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10,
  8552. headPos.left + lineOff.left - wrapOff.left));
  8553. }
  8554. return result
  8555. };
  8556. TextareaInput.prototype.showSelection = function (drawn) {
  8557. var cm = this.cm, display = cm.display;
  8558. removeChildrenAndAdd(display.cursorDiv, drawn.cursors);
  8559. removeChildrenAndAdd(display.selectionDiv, drawn.selection);
  8560. if (drawn.teTop != null) {
  8561. this.wrapper.style.top = drawn.teTop + "px";
  8562. this.wrapper.style.left = drawn.teLeft + "px";
  8563. }
  8564. };
  8565. // Reset the input to correspond to the selection (or to be empty,
  8566. // when not typing and nothing is selected)
  8567. TextareaInput.prototype.reset = function (typing) {
  8568. if (this.contextMenuPending || this.composing) { return }
  8569. var cm = this.cm;
  8570. if (cm.somethingSelected()) {
  8571. this.prevInput = "";
  8572. var content = cm.getSelection();
  8573. this.textarea.value = content;
  8574. if (cm.state.focused) { selectInput(this.textarea); }
  8575. if (ie && ie_version >= 9) { this.hasSelection = content; }
  8576. } else if (!typing) {
  8577. this.prevInput = this.textarea.value = "";
  8578. if (ie && ie_version >= 9) { this.hasSelection = null; }
  8579. }
  8580. };
  8581. TextareaInput.prototype.getField = function () { return this.textarea };
  8582. TextareaInput.prototype.supportsTouch = function () { return false };
  8583. TextareaInput.prototype.focus = function () {
  8584. if (this.cm.options.readOnly != "nocursor" && (!mobile || activeElt() != this.textarea)) {
  8585. try { this.textarea.focus(); }
  8586. catch (e) {} // IE8 will throw if the textarea is display: none or not in DOM
  8587. }
  8588. };
  8589. TextareaInput.prototype.blur = function () { this.textarea.blur(); };
  8590. TextareaInput.prototype.resetPosition = function () {
  8591. this.wrapper.style.top = this.wrapper.style.left = 0;
  8592. };
  8593. TextareaInput.prototype.receivedFocus = function () { this.slowPoll(); };
  8594. // Poll for input changes, using the normal rate of polling. This
  8595. // runs as long as the editor is focused.
  8596. TextareaInput.prototype.slowPoll = function () {
  8597. var this$1 = this;
  8598. if (this.pollingFast) { return }
  8599. this.polling.set(this.cm.options.pollInterval, function () {
  8600. this$1.poll();
  8601. if (this$1.cm.state.focused) { this$1.slowPoll(); }
  8602. });
  8603. };
  8604. // When an event has just come in that is likely to add or change
  8605. // something in the input textarea, we poll faster, to ensure that
  8606. // the change appears on the screen quickly.
  8607. TextareaInput.prototype.fastPoll = function () {
  8608. var missed = false, input = this;
  8609. input.pollingFast = true;
  8610. function p() {
  8611. var changed = input.poll();
  8612. if (!changed && !missed) {missed = true; input.polling.set(60, p);}
  8613. else {input.pollingFast = false; input.slowPoll();}
  8614. }
  8615. input.polling.set(20, p);
  8616. };
  8617. // Read input from the textarea, and update the document to match.
  8618. // When something is selected, it is present in the textarea, and
  8619. // selected (unless it is huge, in which case a placeholder is
  8620. // used). When nothing is selected, the cursor sits after previously
  8621. // seen text (can be empty), which is stored in prevInput (we must
  8622. // not reset the textarea when typing, because that breaks IME).
  8623. TextareaInput.prototype.poll = function () {
  8624. var this$1 = this;
  8625. var cm = this.cm, input = this.textarea, prevInput = this.prevInput;
  8626. // Since this is called a *lot*, try to bail out as cheaply as
  8627. // possible when it is clear that nothing happened. hasSelection
  8628. // will be the case when there is a lot of text in the textarea,
  8629. // in which case reading its value would be expensive.
  8630. if (this.contextMenuPending || !cm.state.focused ||
  8631. (hasSelection(input) && !prevInput && !this.composing) ||
  8632. cm.isReadOnly() || cm.options.disableInput || cm.state.keySeq)
  8633. { return false }
  8634. var text = input.value;
  8635. // If nothing changed, bail.
  8636. if (text == prevInput && !cm.somethingSelected()) { return false }
  8637. // Work around nonsensical selection resetting in IE9/10, and
  8638. // inexplicable appearance of private area unicode characters on
  8639. // some key combos in Mac (#2689).
  8640. if (ie && ie_version >= 9 && this.hasSelection === text ||
  8641. mac && /[\uf700-\uf7ff]/.test(text)) {
  8642. cm.display.input.reset();
  8643. return false
  8644. }
  8645. if (cm.doc.sel == cm.display.selForContextMenu) {
  8646. var first = text.charCodeAt(0);
  8647. if (first == 0x200b && !prevInput) { prevInput = "\u200b"; }
  8648. if (first == 0x21da) { this.reset(); return this.cm.execCommand("undo") }
  8649. }
  8650. // Find the part of the input that is actually new
  8651. var same = 0, l = Math.min(prevInput.length, text.length);
  8652. while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) { ++same; }
  8653. runInOp(cm, function () {
  8654. applyTextInput(cm, text.slice(same), prevInput.length - same,
  8655. null, this$1.composing ? "*compose" : null);
  8656. // Don't leave long text in the textarea, since it makes further polling slow
  8657. if (text.length > 1000 || text.indexOf("\n") > -1) { input.value = this$1.prevInput = ""; }
  8658. else { this$1.prevInput = text; }
  8659. if (this$1.composing) {
  8660. this$1.composing.range.clear();
  8661. this$1.composing.range = cm.markText(this$1.composing.start, cm.getCursor("to"),
  8662. {className: "CodeMirror-composing"});
  8663. }
  8664. });
  8665. return true
  8666. };
  8667. TextareaInput.prototype.ensurePolled = function () {
  8668. if (this.pollingFast && this.poll()) { this.pollingFast = false; }
  8669. };
  8670. TextareaInput.prototype.onKeyPress = function () {
  8671. if (ie && ie_version >= 9) { this.hasSelection = null; }
  8672. this.fastPoll();
  8673. };
  8674. TextareaInput.prototype.onContextMenu = function (e) {
  8675. var input = this, cm = input.cm, display = cm.display, te = input.textarea;
  8676. if (input.contextMenuPending) { input.contextMenuPending(); }
  8677. var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop;
  8678. if (!pos || presto) { return } // Opera is difficult.
  8679. // Reset the current text selection only if the click is done outside of the selection
  8680. // and 'resetSelectionOnContextMenu' option is true.
  8681. var reset = cm.options.resetSelectionOnContextMenu;
  8682. if (reset && cm.doc.sel.contains(pos) == -1)
  8683. { operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll); }
  8684. var oldCSS = te.style.cssText, oldWrapperCSS = input.wrapper.style.cssText;
  8685. var wrapperBox = input.wrapper.offsetParent.getBoundingClientRect();
  8686. input.wrapper.style.cssText = "position: static";
  8687. 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);";
  8688. var oldScrollY;
  8689. if (webkit) { oldScrollY = window.scrollY; } // Work around Chrome issue (#2712)
  8690. display.input.focus();
  8691. if (webkit) { window.scrollTo(null, oldScrollY); }
  8692. display.input.reset();
  8693. // Adds "Select all" to context menu in FF
  8694. if (!cm.somethingSelected()) { te.value = input.prevInput = " "; }
  8695. input.contextMenuPending = rehide;
  8696. display.selForContextMenu = cm.doc.sel;
  8697. clearTimeout(display.detectingSelectAll);
  8698. // Select-all will be greyed out if there's nothing to select, so
  8699. // this adds a zero-width space so that we can later check whether
  8700. // it got selected.
  8701. function prepareSelectAllHack() {
  8702. if (te.selectionStart != null) {
  8703. var selected = cm.somethingSelected();
  8704. var extval = "\u200b" + (selected ? te.value : "");
  8705. te.value = "\u21da"; // Used to catch context-menu undo
  8706. te.value = extval;
  8707. input.prevInput = selected ? "" : "\u200b";
  8708. te.selectionStart = 1; te.selectionEnd = extval.length;
  8709. // Re-set this, in case some other handler touched the
  8710. // selection in the meantime.
  8711. display.selForContextMenu = cm.doc.sel;
  8712. }
  8713. }
  8714. function rehide() {
  8715. if (input.contextMenuPending != rehide) { return }
  8716. input.contextMenuPending = false;
  8717. input.wrapper.style.cssText = oldWrapperCSS;
  8718. te.style.cssText = oldCSS;
  8719. if (ie && ie_version < 9) { display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos); }
  8720. // Try to detect the user choosing select-all
  8721. if (te.selectionStart != null) {
  8722. if (!ie || (ie && ie_version < 9)) { prepareSelectAllHack(); }
  8723. var i = 0, poll = function () {
  8724. if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0 &&
  8725. te.selectionEnd > 0 && input.prevInput == "\u200b") {
  8726. operation(cm, selectAll)(cm);
  8727. } else if (i++ < 10) {
  8728. display.detectingSelectAll = setTimeout(poll, 500);
  8729. } else {
  8730. display.selForContextMenu = null;
  8731. display.input.reset();
  8732. }
  8733. };
  8734. display.detectingSelectAll = setTimeout(poll, 200);
  8735. }
  8736. }
  8737. if (ie && ie_version >= 9) { prepareSelectAllHack(); }
  8738. if (captureRightClick) {
  8739. e_stop(e);
  8740. var mouseup = function () {
  8741. off(window, "mouseup", mouseup);
  8742. setTimeout(rehide, 20);
  8743. };
  8744. on(window, "mouseup", mouseup);
  8745. } else {
  8746. setTimeout(rehide, 50);
  8747. }
  8748. };
  8749. TextareaInput.prototype.readOnlyChanged = function (val) {
  8750. if (!val) { this.reset(); }
  8751. this.textarea.disabled = val == "nocursor";
  8752. this.textarea.readOnly = !!val;
  8753. };
  8754. TextareaInput.prototype.setUneditable = function () {};
  8755. TextareaInput.prototype.needsContentAttribute = false;
  8756. function fromTextArea(textarea, options) {
  8757. options = options ? copyObj(options) : {};
  8758. options.value = textarea.value;
  8759. if (!options.tabindex && textarea.tabIndex)
  8760. { options.tabindex = textarea.tabIndex; }
  8761. if (!options.placeholder && textarea.placeholder)
  8762. { options.placeholder = textarea.placeholder; }
  8763. // Set autofocus to true if this textarea is focused, or if it has
  8764. // autofocus and no other element is focused.
  8765. if (options.autofocus == null) {
  8766. var hasFocus = activeElt();
  8767. options.autofocus = hasFocus == textarea ||
  8768. textarea.getAttribute("autofocus") != null && hasFocus == document.body;
  8769. }
  8770. function save() {textarea.value = cm.getValue();}
  8771. var realSubmit;
  8772. if (textarea.form) {
  8773. on(textarea.form, "submit", save);
  8774. // Deplorable hack to make the submit method do the right thing.
  8775. if (!options.leaveSubmitMethodAlone) {
  8776. var form = textarea.form;
  8777. realSubmit = form.submit;
  8778. try {
  8779. var wrappedSubmit = form.submit = function () {
  8780. save();
  8781. form.submit = realSubmit;
  8782. form.submit();
  8783. form.submit = wrappedSubmit;
  8784. };
  8785. } catch(e) {}
  8786. }
  8787. }
  8788. options.finishInit = function (cm) {
  8789. cm.save = save;
  8790. cm.getTextArea = function () { return textarea; };
  8791. cm.toTextArea = function () {
  8792. cm.toTextArea = isNaN; // Prevent this from being ran twice
  8793. save();
  8794. textarea.parentNode.removeChild(cm.getWrapperElement());
  8795. textarea.style.display = "";
  8796. if (textarea.form) {
  8797. off(textarea.form, "submit", save);
  8798. if (!options.leaveSubmitMethodAlone && typeof textarea.form.submit == "function")
  8799. { textarea.form.submit = realSubmit; }
  8800. }
  8801. };
  8802. };
  8803. textarea.style.display = "none";
  8804. var cm = CodeMirror(function (node) { return textarea.parentNode.insertBefore(node, textarea.nextSibling); },
  8805. options);
  8806. return cm
  8807. }
  8808. function addLegacyProps(CodeMirror) {
  8809. CodeMirror.off = off;
  8810. CodeMirror.on = on;
  8811. CodeMirror.wheelEventPixels = wheelEventPixels;
  8812. CodeMirror.Doc = Doc;
  8813. CodeMirror.splitLines = splitLinesAuto;
  8814. CodeMirror.countColumn = countColumn;
  8815. CodeMirror.findColumn = findColumn;
  8816. CodeMirror.isWordChar = isWordCharBasic;
  8817. CodeMirror.Pass = Pass;
  8818. CodeMirror.signal = signal;
  8819. CodeMirror.Line = Line;
  8820. CodeMirror.changeEnd = changeEnd;
  8821. CodeMirror.scrollbarModel = scrollbarModel;
  8822. CodeMirror.Pos = Pos;
  8823. CodeMirror.cmpPos = cmp;
  8824. CodeMirror.modes = modes;
  8825. CodeMirror.mimeModes = mimeModes;
  8826. CodeMirror.resolveMode = resolveMode;
  8827. CodeMirror.getMode = getMode;
  8828. CodeMirror.modeExtensions = modeExtensions;
  8829. CodeMirror.extendMode = extendMode;
  8830. CodeMirror.copyState = copyState;
  8831. CodeMirror.startState = startState;
  8832. CodeMirror.innerMode = innerMode;
  8833. CodeMirror.commands = commands;
  8834. CodeMirror.keyMap = keyMap;
  8835. CodeMirror.keyName = keyName;
  8836. CodeMirror.isModifierKey = isModifierKey;
  8837. CodeMirror.lookupKey = lookupKey;
  8838. CodeMirror.normalizeKeyMap = normalizeKeyMap;
  8839. CodeMirror.StringStream = StringStream;
  8840. CodeMirror.SharedTextMarker = SharedTextMarker;
  8841. CodeMirror.TextMarker = TextMarker;
  8842. CodeMirror.LineWidget = LineWidget;
  8843. CodeMirror.e_preventDefault = e_preventDefault;
  8844. CodeMirror.e_stopPropagation = e_stopPropagation;
  8845. CodeMirror.e_stop = e_stop;
  8846. CodeMirror.addClass = addClass;
  8847. CodeMirror.contains = contains;
  8848. CodeMirror.rmClass = rmClass;
  8849. CodeMirror.keyNames = keyNames;
  8850. }
  8851. // EDITOR CONSTRUCTOR
  8852. defineOptions(CodeMirror);
  8853. addEditorMethods(CodeMirror);
  8854. // Set up methods on CodeMirror's prototype to redirect to the editor's document.
  8855. var dontDelegate = "iter insert remove copy getEditor constructor".split(" ");
  8856. for (var prop in Doc.prototype) { if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0)
  8857. { CodeMirror.prototype[prop] = (function(method) {
  8858. return function() {return method.apply(this.doc, arguments)}
  8859. })(Doc.prototype[prop]); } }
  8860. eventMixin(Doc);
  8861. CodeMirror.inputStyles = {"textarea": TextareaInput, "contenteditable": ContentEditableInput};
  8862. // Extra arguments are stored as the mode's dependencies, which is
  8863. // used by (legacy) mechanisms like loadmode.js to automatically
  8864. // load a mode. (Preferred mechanism is the require/define calls.)
  8865. CodeMirror.defineMode = function(name/*, mode, …*/) {
  8866. if (!CodeMirror.defaults.mode && name != "null") { CodeMirror.defaults.mode = name; }
  8867. defineMode.apply(this, arguments);
  8868. };
  8869. CodeMirror.defineMIME = defineMIME;
  8870. // Minimal default mode.
  8871. CodeMirror.defineMode("null", function () { return ({token: function (stream) { return stream.skipToEnd(); }}); });
  8872. CodeMirror.defineMIME("text/plain", "null");
  8873. // EXTENSIONS
  8874. CodeMirror.defineExtension = function (name, func) {
  8875. CodeMirror.prototype[name] = func;
  8876. };
  8877. CodeMirror.defineDocExtension = function (name, func) {
  8878. Doc.prototype[name] = func;
  8879. };
  8880. CodeMirror.fromTextArea = fromTextArea;
  8881. addLegacyProps(CodeMirror);
  8882. CodeMirror.version = "5.65.1";
  8883. return CodeMirror;
  8884. })));