codemirror.js 361 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693
  1. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  2. // Distributed under an MIT license: https://codemirror.net/LICENSE
  3. // This is CodeMirror (https://codemirror.net), a code editor
  4. // implemented in JavaScript on top of the browser's DOM.
  5. //
  6. // You can find some technical background for some of the code below
  7. // at http://marijnhaverbeke.nl/blog/#cm-internals .
  8. (function (global, factory) {
  9. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  10. typeof define === 'function' && define.amd ? define(factory) :
  11. (global.CodeMirror = factory());
  12. }(this, (function () { 'use strict';
  13. // Kludges for bugs and behavior differences that can't be feature
  14. // detected are enabled based on userAgent etc sniffing.
  15. var userAgent = navigator.userAgent
  16. var platform = navigator.platform
  17. var gecko = /gecko\/\d/i.test(userAgent)
  18. var ie_upto10 = /MSIE \d/.test(userAgent)
  19. var ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(userAgent)
  20. var edge = /Edge\/(\d+)/.exec(userAgent)
  21. var ie = ie_upto10 || ie_11up || edge
  22. var ie_version = ie && (ie_upto10 ? document.documentMode || 6 : +(edge || ie_11up)[1])
  23. var webkit = !edge && /WebKit\//.test(userAgent)
  24. var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(userAgent)
  25. var chrome = !edge && /Chrome\//.test(userAgent)
  26. var presto = /Opera\//.test(userAgent)
  27. var safari = /Apple Computer/.test(navigator.vendor)
  28. var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(userAgent)
  29. var phantom = /PhantomJS/.test(userAgent)
  30. var ios = !edge && /AppleWebKit/.test(userAgent) && /Mobile\/\w+/.test(userAgent)
  31. var android = /Android/.test(userAgent)
  32. // This is woefully incomplete. Suggestions for alternative methods welcome.
  33. var mobile = ios || android || /webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(userAgent)
  34. var mac = ios || /Mac/.test(platform)
  35. var chromeOS = /\bCrOS\b/.test(userAgent)
  36. var windows = /win/i.test(platform)
  37. var presto_version = presto && userAgent.match(/Version\/(\d*\.\d*)/)
  38. if (presto_version) { presto_version = Number(presto_version[1]) }
  39. if (presto_version && presto_version >= 15) { presto = false; webkit = true }
  40. // Some browsers use the wrong event properties to signal cmd/ctrl on OS X
  41. var flipCtrlCmd = mac && (qtwebkit || presto && (presto_version == null || presto_version < 12.11))
  42. var captureRightClick = gecko || (ie && ie_version >= 9)
  43. function classTest(cls) { return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*") }
  44. var rmClass = function(node, cls) {
  45. var current = node.className
  46. var match = classTest(cls).exec(current)
  47. if (match) {
  48. var after = current.slice(match.index + match[0].length)
  49. node.className = current.slice(0, match.index) + (after ? match[1] + after : "")
  50. }
  51. }
  52. function removeChildren(e) {
  53. for (var count = e.childNodes.length; count > 0; --count)
  54. { e.removeChild(e.firstChild) }
  55. return e
  56. }
  57. function removeChildrenAndAdd(parent, e) {
  58. return removeChildren(parent).appendChild(e)
  59. }
  60. function elt(tag, content, className, style) {
  61. var e = document.createElement(tag)
  62. if (className) { e.className = className }
  63. if (style) { e.style.cssText = style }
  64. if (typeof content == "string") { e.appendChild(document.createTextNode(content)) }
  65. else if (content) { for (var i = 0; i < content.length; ++i) { e.appendChild(content[i]) } }
  66. return e
  67. }
  68. // wrapper for elt, which removes the elt from the accessibility tree
  69. function eltP(tag, content, className, style) {
  70. var e = elt(tag, content, className, style)
  71. e.setAttribute("role", "presentation")
  72. return e
  73. }
  74. var range
  75. if (document.createRange) { range = function(node, start, end, endNode) {
  76. var r = document.createRange()
  77. r.setEnd(endNode || node, end)
  78. r.setStart(node, start)
  79. return r
  80. } }
  81. else { range = function(node, start, end) {
  82. var r = document.body.createTextRange()
  83. try { r.moveToElementText(node.parentNode) }
  84. catch(e) { return r }
  85. r.collapse(true)
  86. r.moveEnd("character", end)
  87. r.moveStart("character", start)
  88. return r
  89. } }
  90. function contains(parent, child) {
  91. if (child.nodeType == 3) // Android browser always returns false when child is a textnode
  92. { child = child.parentNode }
  93. if (parent.contains)
  94. { return parent.contains(child) }
  95. do {
  96. if (child.nodeType == 11) { child = child.host }
  97. if (child == parent) { return true }
  98. } while (child = child.parentNode)
  99. }
  100. function activeElt() {
  101. // IE and Edge may throw an "Unspecified Error" when accessing document.activeElement.
  102. // IE < 10 will throw when accessed while the page is loading or in an iframe.
  103. // IE > 9 and Edge will throw when accessed in an iframe if document.body is unavailable.
  104. var activeElement
  105. try {
  106. activeElement = document.activeElement
  107. } catch(e) {
  108. activeElement = document.body || null
  109. }
  110. while (activeElement && activeElement.shadowRoot && activeElement.shadowRoot.activeElement)
  111. { activeElement = activeElement.shadowRoot.activeElement }
  112. return activeElement
  113. }
  114. function addClass(node, cls) {
  115. var current = node.className
  116. if (!classTest(cls).test(current)) { node.className += (current ? " " : "") + cls }
  117. }
  118. function joinClasses(a, b) {
  119. var as = a.split(" ")
  120. for (var i = 0; i < as.length; i++)
  121. { if (as[i] && !classTest(as[i]).test(b)) { b += " " + as[i] } }
  122. return b
  123. }
  124. var selectInput = function(node) { node.select() }
  125. if (ios) // Mobile Safari apparently has a bug where select() is broken.
  126. { selectInput = function(node) { node.selectionStart = 0; node.selectionEnd = node.value.length } }
  127. else if (ie) // Suppress mysterious IE10 errors
  128. { selectInput = function(node) { try { node.select() } catch(_e) {} } }
  129. function bind(f) {
  130. var args = Array.prototype.slice.call(arguments, 1)
  131. return function(){return f.apply(null, args)}
  132. }
  133. function copyObj(obj, target, overwrite) {
  134. if (!target) { target = {} }
  135. for (var prop in obj)
  136. { if (obj.hasOwnProperty(prop) && (overwrite !== false || !target.hasOwnProperty(prop)))
  137. { target[prop] = obj[prop] } }
  138. return target
  139. }
  140. // Counts the column offset in a string, taking tabs into account.
  141. // Used mostly to find indentation.
  142. function countColumn(string, end, tabSize, startIndex, startValue) {
  143. if (end == null) {
  144. end = string.search(/[^\s\u00a0]/)
  145. if (end == -1) { end = string.length }
  146. }
  147. for (var i = startIndex || 0, n = startValue || 0;;) {
  148. var nextTab = string.indexOf("\t", i)
  149. if (nextTab < 0 || nextTab >= end)
  150. { return n + (end - i) }
  151. n += nextTab - i
  152. n += tabSize - (n % tabSize)
  153. i = nextTab + 1
  154. }
  155. }
  156. var Delayed = function() {this.id = null};
  157. Delayed.prototype.set = function (ms, f) {
  158. clearTimeout(this.id)
  159. this.id = setTimeout(f, ms)
  160. };
  161. function indexOf(array, elt) {
  162. for (var i = 0; i < array.length; ++i)
  163. { if (array[i] == elt) { return i } }
  164. return -1
  165. }
  166. // Number of pixels added to scroller and sizer to hide scrollbar
  167. var scrollerGap = 30
  168. // Returned or thrown by various protocols to signal 'I'm not
  169. // handling this'.
  170. var Pass = {toString: function(){return "CodeMirror.Pass"}}
  171. // Reused option objects for setSelection & friends
  172. var sel_dontScroll = {scroll: false};
  173. var sel_mouse = {origin: "*mouse"};
  174. var sel_move = {origin: "+move"};
  175. // The inverse of countColumn -- find the offset that corresponds to
  176. // a particular column.
  177. function findColumn(string, goal, tabSize) {
  178. for (var pos = 0, col = 0;;) {
  179. var nextTab = string.indexOf("\t", pos)
  180. if (nextTab == -1) { nextTab = string.length }
  181. var skipped = nextTab - pos
  182. if (nextTab == string.length || col + skipped >= goal)
  183. { return pos + Math.min(skipped, goal - col) }
  184. col += nextTab - pos
  185. col += tabSize - (col % tabSize)
  186. pos = nextTab + 1
  187. if (col >= goal) { return pos }
  188. }
  189. }
  190. var spaceStrs = [""]
  191. function spaceStr(n) {
  192. while (spaceStrs.length <= n)
  193. { spaceStrs.push(lst(spaceStrs) + " ") }
  194. return spaceStrs[n]
  195. }
  196. function lst(arr) { return arr[arr.length-1] }
  197. function map(array, f) {
  198. var out = []
  199. for (var i = 0; i < array.length; i++) { out[i] = f(array[i], i) }
  200. return out
  201. }
  202. function insertSorted(array, value, score) {
  203. var pos = 0, priority = score(value)
  204. while (pos < array.length && score(array[pos]) <= priority) { pos++ }
  205. array.splice(pos, 0, value)
  206. }
  207. function nothing() {}
  208. function createObj(base, props) {
  209. var inst
  210. if (Object.create) {
  211. inst = Object.create(base)
  212. } else {
  213. nothing.prototype = base
  214. inst = new nothing()
  215. }
  216. if (props) { copyObj(props, inst) }
  217. return inst
  218. }
  219. var nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/
  220. function isWordCharBasic(ch) {
  221. return /\w/.test(ch) || ch > "\x80" &&
  222. (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch))
  223. }
  224. function isWordChar(ch, helper) {
  225. if (!helper) { return isWordCharBasic(ch) }
  226. if (helper.source.indexOf("\\w") > -1 && isWordCharBasic(ch)) { return true }
  227. return helper.test(ch)
  228. }
  229. function isEmpty(obj) {
  230. for (var n in obj) { if (obj.hasOwnProperty(n) && obj[n]) { return false } }
  231. return true
  232. }
  233. // Extending unicode characters. A series of a non-extending char +
  234. // any number of extending chars is treated as a single unit as far
  235. // as editing and measuring is concerned. This is not fully correct,
  236. // since some scripts/fonts/browsers also treat other configurations
  237. // of code points as a group.
  238. var extendingChars = /[\u0300-\u036f\u0483-\u0489\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u065e\u0670\u06d6-\u06dc\u06de-\u06e4\u06e7\u06e8\u06ea-\u06ed\u0711\u0730-\u074a\u07a6-\u07b0\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0900-\u0902\u093c\u0941-\u0948\u094d\u0951-\u0955\u0962\u0963\u0981\u09bc\u09be\u09c1-\u09c4\u09cd\u09d7\u09e2\u09e3\u0a01\u0a02\u0a3c\u0a41\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a70\u0a71\u0a75\u0a81\u0a82\u0abc\u0ac1-\u0ac5\u0ac7\u0ac8\u0acd\u0ae2\u0ae3\u0b01\u0b3c\u0b3e\u0b3f\u0b41-\u0b44\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b82\u0bbe\u0bc0\u0bcd\u0bd7\u0c3e-\u0c40\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0cbc\u0cbf\u0cc2\u0cc6\u0ccc\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0d3e\u0d41-\u0d44\u0d4d\u0d57\u0d62\u0d63\u0dca\u0dcf\u0dd2-\u0dd4\u0dd6\u0ddf\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0f18\u0f19\u0f35\u0f37\u0f39\u0f71-\u0f7e\u0f80-\u0f84\u0f86\u0f87\u0f90-\u0f97\u0f99-\u0fbc\u0fc6\u102d-\u1030\u1032-\u1037\u1039\u103a\u103d\u103e\u1058\u1059\u105e-\u1060\u1071-\u1074\u1082\u1085\u1086\u108d\u109d\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b7-\u17bd\u17c6\u17c9-\u17d3\u17dd\u180b-\u180d\u18a9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193b\u1a17\u1a18\u1a56\u1a58-\u1a5e\u1a60\u1a62\u1a65-\u1a6c\u1a73-\u1a7c\u1a7f\u1b00-\u1b03\u1b34\u1b36-\u1b3a\u1b3c\u1b42\u1b6b-\u1b73\u1b80\u1b81\u1ba2-\u1ba5\u1ba8\u1ba9\u1c2c-\u1c33\u1c36\u1c37\u1cd0-\u1cd2\u1cd4-\u1ce0\u1ce2-\u1ce8\u1ced\u1dc0-\u1de6\u1dfd-\u1dff\u200c\u200d\u20d0-\u20f0\u2cef-\u2cf1\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua66f-\ua672\ua67c\ua67d\ua6f0\ua6f1\ua802\ua806\ua80b\ua825\ua826\ua8c4\ua8e0-\ua8f1\ua926-\ua92d\ua947-\ua951\ua980-\ua982\ua9b3\ua9b6-\ua9b9\ua9bc\uaa29-\uaa2e\uaa31\uaa32\uaa35\uaa36\uaa43\uaa4c\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uabe5\uabe8\uabed\udc00-\udfff\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\uff9e\uff9f]/
  239. function isExtendingChar(ch) { return ch.charCodeAt(0) >= 768 && extendingChars.test(ch) }
  240. // Returns a number from the range [`0`; `str.length`] unless `pos` is outside that range.
  241. function skipExtendingChars(str, pos, dir) {
  242. while ((dir < 0 ? pos > 0 : pos < str.length) && isExtendingChar(str.charAt(pos))) { pos += dir }
  243. return pos
  244. }
  245. // Returns the value from the range [`from`; `to`] that satisfies
  246. // `pred` and is closest to `from`. Assumes that at least `to`
  247. // satisfies `pred`. Supports `from` being greater than `to`.
  248. function findFirst(pred, from, to) {
  249. // At any point we are certain `to` satisfies `pred`, don't know
  250. // whether `from` does.
  251. var dir = from > to ? -1 : 1
  252. for (;;) {
  253. if (from == to) { return from }
  254. var midF = (from + to) / 2, mid = dir < 0 ? Math.ceil(midF) : Math.floor(midF)
  255. if (mid == from) { return pred(mid) ? from : to }
  256. if (pred(mid)) { to = mid }
  257. else { from = mid + dir }
  258. }
  259. }
  260. // The display handles the DOM integration, both for input reading
  261. // and content drawing. It holds references to DOM nodes and
  262. // display-related state.
  263. function Display(place, doc, input) {
  264. var d = this
  265. this.input = input
  266. // Covers bottom-right square when both scrollbars are present.
  267. d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler")
  268. d.scrollbarFiller.setAttribute("cm-not-content", "true")
  269. // Covers bottom of gutter when coverGutterNextToScrollbar is on
  270. // and h scrollbar is present.
  271. d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler")
  272. d.gutterFiller.setAttribute("cm-not-content", "true")
  273. // Will contain the actual code, positioned to cover the viewport.
  274. d.lineDiv = eltP("div", null, "CodeMirror-code")
  275. // Elements are added to these to represent selection and cursors.
  276. d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1")
  277. d.cursorDiv = elt("div", null, "CodeMirror-cursors")
  278. // A visibility: hidden element used to find the size of things.
  279. d.measure = elt("div", null, "CodeMirror-measure")
  280. // When lines outside of the viewport are measured, they are drawn in this.
  281. d.lineMeasure = elt("div", null, "CodeMirror-measure")
  282. // Wraps everything that needs to exist inside the vertically-padded coordinate system
  283. d.lineSpace = eltP("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv],
  284. null, "position: relative; outline: none")
  285. var lines = eltP("div", [d.lineSpace], "CodeMirror-lines")
  286. // Moved around its parent to cover visible view.
  287. d.mover = elt("div", [lines], null, "position: relative")
  288. // Set to the height of the document, allowing scrolling.
  289. d.sizer = elt("div", [d.mover], "CodeMirror-sizer")
  290. d.sizerWidth = null
  291. // Behavior of elts with overflow: auto and padding is
  292. // inconsistent across browsers. This is used to ensure the
  293. // scrollable area is big enough.
  294. d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerGap + "px; width: 1px;")
  295. // Will contain the gutters, if any.
  296. d.gutters = elt("div", null, "CodeMirror-gutters")
  297. d.lineGutter = null
  298. // Actual scrollable element.
  299. d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll")
  300. d.scroller.setAttribute("tabIndex", "-1")
  301. // The element in which the editor lives.
  302. d.wrapper = elt("div", [d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror")
  303. // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported)
  304. if (ie && ie_version < 8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0 }
  305. if (!webkit && !(gecko && mobile)) { d.scroller.draggable = true }
  306. if (place) {
  307. if (place.appendChild) { place.appendChild(d.wrapper) }
  308. else { place(d.wrapper) }
  309. }
  310. // Current rendered range (may be bigger than the view window).
  311. d.viewFrom = d.viewTo = doc.first
  312. d.reportedViewFrom = d.reportedViewTo = doc.first
  313. // Information about the rendered lines.
  314. d.view = []
  315. d.renderedView = null
  316. // Holds info about a single rendered line when it was rendered
  317. // for measurement, while not in view.
  318. d.externalMeasured = null
  319. // Empty space (in pixels) above the view
  320. d.viewOffset = 0
  321. d.lastWrapHeight = d.lastWrapWidth = 0
  322. d.updateLineNumbers = null
  323. d.nativeBarWidth = d.barHeight = d.barWidth = 0
  324. d.scrollbarsClipped = false
  325. // Used to only resize the line number gutter when necessary (when
  326. // the amount of lines crosses a boundary that makes its width change)
  327. d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null
  328. // Set to true when a non-horizontal-scrolling line widget is
  329. // added. As an optimization, line widget aligning is skipped when
  330. // this is false.
  331. d.alignWidgets = false
  332. d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null
  333. // Tracks the maximum line length so that the horizontal scrollbar
  334. // can be kept static when scrolling.
  335. d.maxLine = null
  336. d.maxLineLength = 0
  337. d.maxLineChanged = false
  338. // Used for measuring wheel scrolling granularity
  339. d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null
  340. // True when shift is held down.
  341. d.shift = false
  342. // Used to track whether anything happened since the context menu
  343. // was opened.
  344. d.selForContextMenu = null
  345. d.activeTouch = null
  346. input.init(d)
  347. }
  348. // Find the line object corresponding to the given line number.
  349. function getLine(doc, n) {
  350. n -= doc.first
  351. if (n < 0 || n >= doc.size) { throw new Error("There is no line " + (n + doc.first) + " in the document.") }
  352. var chunk = doc
  353. while (!chunk.lines) {
  354. for (var i = 0;; ++i) {
  355. var child = chunk.children[i], sz = child.chunkSize()
  356. if (n < sz) { chunk = child; break }
  357. n -= sz
  358. }
  359. }
  360. return chunk.lines[n]
  361. }
  362. // Get the part of a document between two positions, as an array of
  363. // strings.
  364. function getBetween(doc, start, end) {
  365. var out = [], n = start.line
  366. doc.iter(start.line, end.line + 1, function (line) {
  367. var text = line.text
  368. if (n == end.line) { text = text.slice(0, end.ch) }
  369. if (n == start.line) { text = text.slice(start.ch) }
  370. out.push(text)
  371. ++n
  372. })
  373. return out
  374. }
  375. // Get the lines between from and to, as array of strings.
  376. function getLines(doc, from, to) {
  377. var out = []
  378. doc.iter(from, to, function (line) { out.push(line.text) }) // iter aborts when callback returns truthy value
  379. return out
  380. }
  381. // Update the height of a line, propagating the height change
  382. // upwards to parent nodes.
  383. function updateLineHeight(line, height) {
  384. var diff = height - line.height
  385. if (diff) { for (var n = line; n; n = n.parent) { n.height += diff } }
  386. }
  387. // Given a line object, find its line number by walking up through
  388. // its parent links.
  389. function lineNo(line) {
  390. if (line.parent == null) { return null }
  391. var cur = line.parent, no = indexOf(cur.lines, line)
  392. for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) {
  393. for (var i = 0;; ++i) {
  394. if (chunk.children[i] == cur) { break }
  395. no += chunk.children[i].chunkSize()
  396. }
  397. }
  398. return no + cur.first
  399. }
  400. // Find the line at the given vertical position, using the height
  401. // information in the document tree.
  402. function lineAtHeight(chunk, h) {
  403. var n = chunk.first
  404. outer: do {
  405. for (var i$1 = 0; i$1 < chunk.children.length; ++i$1) {
  406. var child = chunk.children[i$1], ch = child.height
  407. if (h < ch) { chunk = child; continue outer }
  408. h -= ch
  409. n += child.chunkSize()
  410. }
  411. return n
  412. } while (!chunk.lines)
  413. var i = 0
  414. for (; i < chunk.lines.length; ++i) {
  415. var line = chunk.lines[i], lh = line.height
  416. if (h < lh) { break }
  417. h -= lh
  418. }
  419. return n + i
  420. }
  421. function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size}
  422. function lineNumberFor(options, i) {
  423. return String(options.lineNumberFormatter(i + options.firstLineNumber))
  424. }
  425. // A Pos instance represents a position within the text.
  426. function Pos(line, ch, sticky) {
  427. if ( sticky === void 0 ) sticky = null;
  428. if (!(this instanceof Pos)) { return new Pos(line, ch, sticky) }
  429. this.line = line
  430. this.ch = ch
  431. this.sticky = sticky
  432. }
  433. // Compare two positions, return 0 if they are the same, a negative
  434. // number when a is less, and a positive number otherwise.
  435. function cmp(a, b) { return a.line - b.line || a.ch - b.ch }
  436. function equalCursorPos(a, b) { return a.sticky == b.sticky && cmp(a, b) == 0 }
  437. function copyPos(x) {return Pos(x.line, x.ch)}
  438. function maxPos(a, b) { return cmp(a, b) < 0 ? b : a }
  439. function minPos(a, b) { return cmp(a, b) < 0 ? a : b }
  440. // Most of the external API clips given positions to make sure they
  441. // actually exist within the document.
  442. function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1))}
  443. function clipPos(doc, pos) {
  444. if (pos.line < doc.first) { return Pos(doc.first, 0) }
  445. var last = doc.first + doc.size - 1
  446. if (pos.line > last) { return Pos(last, getLine(doc, last).text.length) }
  447. return clipToLen(pos, getLine(doc, pos.line).text.length)
  448. }
  449. function clipToLen(pos, linelen) {
  450. var ch = pos.ch
  451. if (ch == null || ch > linelen) { return Pos(pos.line, linelen) }
  452. else if (ch < 0) { return Pos(pos.line, 0) }
  453. else { return pos }
  454. }
  455. function clipPosArray(doc, array) {
  456. var out = []
  457. for (var i = 0; i < array.length; i++) { out[i] = clipPos(doc, array[i]) }
  458. return out
  459. }
  460. // Optimize some code when these features are not used.
  461. var sawReadOnlySpans = false;
  462. var sawCollapsedSpans = false;
  463. function seeReadOnlySpans() {
  464. sawReadOnlySpans = true
  465. }
  466. function seeCollapsedSpans() {
  467. sawCollapsedSpans = true
  468. }
  469. // TEXTMARKER SPANS
  470. function MarkedSpan(marker, from, to) {
  471. this.marker = marker
  472. this.from = from; this.to = to
  473. }
  474. // Search an array of spans for a span matching the given marker.
  475. function getMarkedSpanFor(spans, marker) {
  476. if (spans) { for (var i = 0; i < spans.length; ++i) {
  477. var span = spans[i]
  478. if (span.marker == marker) { return span }
  479. } }
  480. }
  481. // Remove a span from an array, returning undefined if no spans are
  482. // left (we don't store arrays for lines without spans).
  483. function removeMarkedSpan(spans, span) {
  484. var r
  485. for (var i = 0; i < spans.length; ++i)
  486. { if (spans[i] != span) { (r || (r = [])).push(spans[i]) } }
  487. return r
  488. }
  489. // Add a span to a line.
  490. function addMarkedSpan(line, span) {
  491. line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span]
  492. span.marker.attachLine(line)
  493. }
  494. // Used for the algorithm that adjusts markers for a change in the
  495. // document. These functions cut an array of spans at a given
  496. // character position, returning an array of remaining chunks (or
  497. // undefined if nothing remains).
  498. function markedSpansBefore(old, startCh, isInsert) {
  499. var nw
  500. if (old) { for (var i = 0; i < old.length; ++i) {
  501. var span = old[i], marker = span.marker
  502. var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh)
  503. if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) {
  504. var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh)
  505. ;(nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to))
  506. }
  507. } }
  508. return nw
  509. }
  510. function markedSpansAfter(old, endCh, isInsert) {
  511. var nw
  512. if (old) { for (var i = 0; i < old.length; ++i) {
  513. var span = old[i], marker = span.marker
  514. var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh)
  515. if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) {
  516. var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh)
  517. ;(nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh,
  518. span.to == null ? null : span.to - endCh))
  519. }
  520. } }
  521. return nw
  522. }
  523. // Given a change object, compute the new set of marker spans that
  524. // cover the line in which the change took place. Removes spans
  525. // entirely within the change, reconnects spans belonging to the
  526. // same marker that appear on both sides of the change, and cuts off
  527. // spans partially within the change. Returns an array of span
  528. // arrays with one element for each line in (after) the change.
  529. function stretchSpansOverChange(doc, change) {
  530. if (change.full) { return null }
  531. var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans
  532. var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans
  533. if (!oldFirst && !oldLast) { return null }
  534. var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0
  535. // Get the spans that 'stick out' on both sides
  536. var first = markedSpansBefore(oldFirst, startCh, isInsert)
  537. var last = markedSpansAfter(oldLast, endCh, isInsert)
  538. // Next, merge those two ends
  539. var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0)
  540. if (first) {
  541. // Fix up .to properties of first
  542. for (var i = 0; i < first.length; ++i) {
  543. var span = first[i]
  544. if (span.to == null) {
  545. var found = getMarkedSpanFor(last, span.marker)
  546. if (!found) { span.to = startCh }
  547. else if (sameLine) { span.to = found.to == null ? null : found.to + offset }
  548. }
  549. }
  550. }
  551. if (last) {
  552. // Fix up .from in last (or move them into first in case of sameLine)
  553. for (var i$1 = 0; i$1 < last.length; ++i$1) {
  554. var span$1 = last[i$1]
  555. if (span$1.to != null) { span$1.to += offset }
  556. if (span$1.from == null) {
  557. var found$1 = getMarkedSpanFor(first, span$1.marker)
  558. if (!found$1) {
  559. span$1.from = offset
  560. if (sameLine) { (first || (first = [])).push(span$1) }
  561. }
  562. } else {
  563. span$1.from += offset
  564. if (sameLine) { (first || (first = [])).push(span$1) }
  565. }
  566. }
  567. }
  568. // Make sure we didn't create any zero-length spans
  569. if (first) { first = clearEmptySpans(first) }
  570. if (last && last != first) { last = clearEmptySpans(last) }
  571. var newMarkers = [first]
  572. if (!sameLine) {
  573. // Fill gap with whole-line-spans
  574. var gap = change.text.length - 2, gapMarkers
  575. if (gap > 0 && first)
  576. { for (var i$2 = 0; i$2 < first.length; ++i$2)
  577. { if (first[i$2].to == null)
  578. { (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i$2].marker, null, null)) } } }
  579. for (var i$3 = 0; i$3 < gap; ++i$3)
  580. { newMarkers.push(gapMarkers) }
  581. newMarkers.push(last)
  582. }
  583. return newMarkers
  584. }
  585. // Remove spans that are empty and don't have a clearWhenEmpty
  586. // option of false.
  587. function clearEmptySpans(spans) {
  588. for (var i = 0; i < spans.length; ++i) {
  589. var span = spans[i]
  590. if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false)
  591. { spans.splice(i--, 1) }
  592. }
  593. if (!spans.length) { return null }
  594. return spans
  595. }
  596. // Used to 'clip' out readOnly ranges when making a change.
  597. function removeReadOnlyRanges(doc, from, to) {
  598. var markers = null
  599. doc.iter(from.line, to.line + 1, function (line) {
  600. if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) {
  601. var mark = line.markedSpans[i].marker
  602. if (mark.readOnly && (!markers || indexOf(markers, mark) == -1))
  603. { (markers || (markers = [])).push(mark) }
  604. } }
  605. })
  606. if (!markers) { return null }
  607. var parts = [{from: from, to: to}]
  608. for (var i = 0; i < markers.length; ++i) {
  609. var mk = markers[i], m = mk.find(0)
  610. for (var j = 0; j < parts.length; ++j) {
  611. var p = parts[j]
  612. if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) { continue }
  613. var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to)
  614. if (dfrom < 0 || !mk.inclusiveLeft && !dfrom)
  615. { newParts.push({from: p.from, to: m.from}) }
  616. if (dto > 0 || !mk.inclusiveRight && !dto)
  617. { newParts.push({from: m.to, to: p.to}) }
  618. parts.splice.apply(parts, newParts)
  619. j += newParts.length - 3
  620. }
  621. }
  622. return parts
  623. }
  624. // Connect or disconnect spans from a line.
  625. function detachMarkedSpans(line) {
  626. var spans = line.markedSpans
  627. if (!spans) { return }
  628. for (var i = 0; i < spans.length; ++i)
  629. { spans[i].marker.detachLine(line) }
  630. line.markedSpans = null
  631. }
  632. function attachMarkedSpans(line, spans) {
  633. if (!spans) { return }
  634. for (var i = 0; i < spans.length; ++i)
  635. { spans[i].marker.attachLine(line) }
  636. line.markedSpans = spans
  637. }
  638. // Helpers used when computing which overlapping collapsed span
  639. // counts as the larger one.
  640. function extraLeft(marker) { return marker.inclusiveLeft ? -1 : 0 }
  641. function extraRight(marker) { return marker.inclusiveRight ? 1 : 0 }
  642. // Returns a number indicating which of two overlapping collapsed
  643. // spans is larger (and thus includes the other). Falls back to
  644. // comparing ids when the spans cover exactly the same range.
  645. function compareCollapsedMarkers(a, b) {
  646. var lenDiff = a.lines.length - b.lines.length
  647. if (lenDiff != 0) { return lenDiff }
  648. var aPos = a.find(), bPos = b.find()
  649. var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b)
  650. if (fromCmp) { return -fromCmp }
  651. var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b)
  652. if (toCmp) { return toCmp }
  653. return b.id - a.id
  654. }
  655. // Find out whether a line ends or starts in a collapsed span. If
  656. // so, return the marker for that span.
  657. function collapsedSpanAtSide(line, start) {
  658. var sps = sawCollapsedSpans && line.markedSpans, found
  659. if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) {
  660. sp = sps[i]
  661. if (sp.marker.collapsed && (start ? sp.from : sp.to) == null &&
  662. (!found || compareCollapsedMarkers(found, sp.marker) < 0))
  663. { found = sp.marker }
  664. } }
  665. return found
  666. }
  667. function collapsedSpanAtStart(line) { return collapsedSpanAtSide(line, true) }
  668. function collapsedSpanAtEnd(line) { return collapsedSpanAtSide(line, false) }
  669. function collapsedSpanAround(line, ch) {
  670. var sps = sawCollapsedSpans && line.markedSpans, found
  671. if (sps) { for (var i = 0; i < sps.length; ++i) {
  672. var sp = sps[i]
  673. if (sp.marker.collapsed && (sp.from == null || sp.from < ch) && (sp.to == null || sp.to > ch) &&
  674. (!found || compareCollapsedMarkers(found, sp.marker) < 0)) { found = sp.marker }
  675. } }
  676. return found
  677. }
  678. // Test whether there exists a collapsed span that partially
  679. // overlaps (covers the start or end, but not both) of a new span.
  680. // Such overlap is not allowed.
  681. function conflictingCollapsedRange(doc, lineNo, from, to, marker) {
  682. var line = getLine(doc, lineNo)
  683. var sps = sawCollapsedSpans && line.markedSpans
  684. if (sps) { for (var i = 0; i < sps.length; ++i) {
  685. var sp = sps[i]
  686. if (!sp.marker.collapsed) { continue }
  687. var found = sp.marker.find(0)
  688. var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker)
  689. var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker)
  690. if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) { continue }
  691. if (fromCmp <= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.to, from) >= 0 : cmp(found.to, from) > 0) ||
  692. fromCmp >= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.from, to) <= 0 : cmp(found.from, to) < 0))
  693. { return true }
  694. } }
  695. }
  696. // A visual line is a line as drawn on the screen. Folding, for
  697. // example, can cause multiple logical lines to appear on the same
  698. // visual line. This finds the start of the visual line that the
  699. // given line is part of (usually that is the line itself).
  700. function visualLine(line) {
  701. var merged
  702. while (merged = collapsedSpanAtStart(line))
  703. { line = merged.find(-1, true).line }
  704. return line
  705. }
  706. function visualLineEnd(line) {
  707. var merged
  708. while (merged = collapsedSpanAtEnd(line))
  709. { line = merged.find(1, true).line }
  710. return line
  711. }
  712. // Returns an array of logical lines that continue the visual line
  713. // started by the argument, or undefined if there are no such lines.
  714. function visualLineContinued(line) {
  715. var merged, lines
  716. while (merged = collapsedSpanAtEnd(line)) {
  717. line = merged.find(1, true).line
  718. ;(lines || (lines = [])).push(line)
  719. }
  720. return lines
  721. }
  722. // Get the line number of the start of the visual line that the
  723. // given line number is part of.
  724. function visualLineNo(doc, lineN) {
  725. var line = getLine(doc, lineN), vis = visualLine(line)
  726. if (line == vis) { return lineN }
  727. return lineNo(vis)
  728. }
  729. // Get the line number of the start of the next visual line after
  730. // the given line.
  731. function visualLineEndNo(doc, lineN) {
  732. if (lineN > doc.lastLine()) { return lineN }
  733. var line = getLine(doc, lineN), merged
  734. if (!lineIsHidden(doc, line)) { return lineN }
  735. while (merged = collapsedSpanAtEnd(line))
  736. { line = merged.find(1, true).line }
  737. return lineNo(line) + 1
  738. }
  739. // Compute whether a line is hidden. Lines count as hidden when they
  740. // are part of a visual line that starts with another line, or when
  741. // they are entirely covered by collapsed, non-widget span.
  742. function lineIsHidden(doc, line) {
  743. var sps = sawCollapsedSpans && line.markedSpans
  744. if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) {
  745. sp = sps[i]
  746. if (!sp.marker.collapsed) { continue }
  747. if (sp.from == null) { return true }
  748. if (sp.marker.widgetNode) { continue }
  749. if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp))
  750. { return true }
  751. } }
  752. }
  753. function lineIsHiddenInner(doc, line, span) {
  754. if (span.to == null) {
  755. var end = span.marker.find(1, true)
  756. return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker))
  757. }
  758. if (span.marker.inclusiveRight && span.to == line.text.length)
  759. { return true }
  760. for (var sp = (void 0), i = 0; i < line.markedSpans.length; ++i) {
  761. sp = line.markedSpans[i]
  762. if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to &&
  763. (sp.to == null || sp.to != span.from) &&
  764. (sp.marker.inclusiveLeft || span.marker.inclusiveRight) &&
  765. lineIsHiddenInner(doc, line, sp)) { return true }
  766. }
  767. }
  768. // Find the height above the given line.
  769. function heightAtLine(lineObj) {
  770. lineObj = visualLine(lineObj)
  771. var h = 0, chunk = lineObj.parent
  772. for (var i = 0; i < chunk.lines.length; ++i) {
  773. var line = chunk.lines[i]
  774. if (line == lineObj) { break }
  775. else { h += line.height }
  776. }
  777. for (var p = chunk.parent; p; chunk = p, p = chunk.parent) {
  778. for (var i$1 = 0; i$1 < p.children.length; ++i$1) {
  779. var cur = p.children[i$1]
  780. if (cur == chunk) { break }
  781. else { h += cur.height }
  782. }
  783. }
  784. return h
  785. }
  786. // Compute the character length of a line, taking into account
  787. // collapsed ranges (see markText) that might hide parts, and join
  788. // other lines onto it.
  789. function lineLength(line) {
  790. if (line.height == 0) { return 0 }
  791. var len = line.text.length, merged, cur = line
  792. while (merged = collapsedSpanAtStart(cur)) {
  793. var found = merged.find(0, true)
  794. cur = found.from.line
  795. len += found.from.ch - found.to.ch
  796. }
  797. cur = line
  798. while (merged = collapsedSpanAtEnd(cur)) {
  799. var found$1 = merged.find(0, true)
  800. len -= cur.text.length - found$1.from.ch
  801. cur = found$1.to.line
  802. len += cur.text.length - found$1.to.ch
  803. }
  804. return len
  805. }
  806. // Find the longest line in the document.
  807. function findMaxLine(cm) {
  808. var d = cm.display, doc = cm.doc
  809. d.maxLine = getLine(doc, doc.first)
  810. d.maxLineLength = lineLength(d.maxLine)
  811. d.maxLineChanged = true
  812. doc.iter(function (line) {
  813. var len = lineLength(line)
  814. if (len > d.maxLineLength) {
  815. d.maxLineLength = len
  816. d.maxLine = line
  817. }
  818. })
  819. }
  820. // BIDI HELPERS
  821. function iterateBidiSections(order, from, to, f) {
  822. if (!order) { return f(from, to, "ltr", 0) }
  823. var found = false
  824. for (var i = 0; i < order.length; ++i) {
  825. var part = order[i]
  826. if (part.from < to && part.to > from || from == to && part.to == from) {
  827. f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr", i)
  828. found = true
  829. }
  830. }
  831. if (!found) { f(from, to, "ltr") }
  832. }
  833. var bidiOther = null
  834. function getBidiPartAt(order, ch, sticky) {
  835. var found
  836. bidiOther = null
  837. for (var i = 0; i < order.length; ++i) {
  838. var cur = order[i]
  839. if (cur.from < ch && cur.to > ch) { return i }
  840. if (cur.to == ch) {
  841. if (cur.from != cur.to && sticky == "before") { found = i }
  842. else { bidiOther = i }
  843. }
  844. if (cur.from == ch) {
  845. if (cur.from != cur.to && sticky != "before") { found = i }
  846. else { bidiOther = i }
  847. }
  848. }
  849. return found != null ? found : bidiOther
  850. }
  851. // Bidirectional ordering algorithm
  852. // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm
  853. // that this (partially) implements.
  854. // One-char codes used for character types:
  855. // L (L): Left-to-Right
  856. // R (R): Right-to-Left
  857. // r (AL): Right-to-Left Arabic
  858. // 1 (EN): European Number
  859. // + (ES): European Number Separator
  860. // % (ET): European Number Terminator
  861. // n (AN): Arabic Number
  862. // , (CS): Common Number Separator
  863. // m (NSM): Non-Spacing Mark
  864. // b (BN): Boundary Neutral
  865. // s (B): Paragraph Separator
  866. // t (S): Segment Separator
  867. // w (WS): Whitespace
  868. // N (ON): Other Neutrals
  869. // Returns null if characters are ordered as they appear
  870. // (left-to-right), or an array of sections ({from, to, level}
  871. // objects) in the order in which they occur visually.
  872. var bidiOrdering = (function() {
  873. // Character types for codepoints 0 to 0xff
  874. var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN"
  875. // Character types for codepoints 0x600 to 0x6f9
  876. var arabicTypes = "nnnnnnNNr%%r,rNNmmmmmmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmmmnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmnNmmmmmmrrmmNmmmmrr1111111111"
  877. function charType(code) {
  878. if (code <= 0xf7) { return lowTypes.charAt(code) }
  879. else if (0x590 <= code && code <= 0x5f4) { return "R" }
  880. else if (0x600 <= code && code <= 0x6f9) { return arabicTypes.charAt(code - 0x600) }
  881. else if (0x6ee <= code && code <= 0x8ac) { return "r" }
  882. else if (0x2000 <= code && code <= 0x200b) { return "w" }
  883. else if (code == 0x200c) { return "b" }
  884. else { return "L" }
  885. }
  886. var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/
  887. var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/
  888. function BidiSpan(level, from, to) {
  889. this.level = level
  890. this.from = from; this.to = to
  891. }
  892. return function(str, direction) {
  893. var outerType = direction == "ltr" ? "L" : "R"
  894. if (str.length == 0 || direction == "ltr" && !bidiRE.test(str)) { return false }
  895. var len = str.length, types = []
  896. for (var i = 0; i < len; ++i)
  897. { types.push(charType(str.charCodeAt(i))) }
  898. // W1. Examine each non-spacing mark (NSM) in the level run, and
  899. // change the type of the NSM to the type of the previous
  900. // character. If the NSM is at the start of the level run, it will
  901. // get the type of sor.
  902. for (var i$1 = 0, prev = outerType; i$1 < len; ++i$1) {
  903. var type = types[i$1]
  904. if (type == "m") { types[i$1] = prev }
  905. else { prev = type }
  906. }
  907. // W2. Search backwards from each instance of a European number
  908. // until the first strong type (R, L, AL, or sor) is found. If an
  909. // AL is found, change the type of the European number to Arabic
  910. // number.
  911. // W3. Change all ALs to R.
  912. for (var i$2 = 0, cur = outerType; i$2 < len; ++i$2) {
  913. var type$1 = types[i$2]
  914. if (type$1 == "1" && cur == "r") { types[i$2] = "n" }
  915. else if (isStrong.test(type$1)) { cur = type$1; if (type$1 == "r") { types[i$2] = "R" } }
  916. }
  917. // W4. A single European separator between two European numbers
  918. // changes to a European number. A single common separator between
  919. // two numbers of the same type changes to that type.
  920. for (var i$3 = 1, prev$1 = types[0]; i$3 < len - 1; ++i$3) {
  921. var type$2 = types[i$3]
  922. if (type$2 == "+" && prev$1 == "1" && types[i$3+1] == "1") { types[i$3] = "1" }
  923. else if (type$2 == "," && prev$1 == types[i$3+1] &&
  924. (prev$1 == "1" || prev$1 == "n")) { types[i$3] = prev$1 }
  925. prev$1 = type$2
  926. }
  927. // W5. A sequence of European terminators adjacent to European
  928. // numbers changes to all European numbers.
  929. // W6. Otherwise, separators and terminators change to Other
  930. // Neutral.
  931. for (var i$4 = 0; i$4 < len; ++i$4) {
  932. var type$3 = types[i$4]
  933. if (type$3 == ",") { types[i$4] = "N" }
  934. else if (type$3 == "%") {
  935. var end = (void 0)
  936. for (end = i$4 + 1; end < len && types[end] == "%"; ++end) {}
  937. var replace = (i$4 && types[i$4-1] == "!") || (end < len && types[end] == "1") ? "1" : "N"
  938. for (var j = i$4; j < end; ++j) { types[j] = replace }
  939. i$4 = end - 1
  940. }
  941. }
  942. // W7. Search backwards from each instance of a European number
  943. // until the first strong type (R, L, or sor) is found. If an L is
  944. // found, then change the type of the European number to L.
  945. for (var i$5 = 0, cur$1 = outerType; i$5 < len; ++i$5) {
  946. var type$4 = types[i$5]
  947. if (cur$1 == "L" && type$4 == "1") { types[i$5] = "L" }
  948. else if (isStrong.test(type$4)) { cur$1 = type$4 }
  949. }
  950. // N1. A sequence of neutrals takes the direction of the
  951. // surrounding strong text if the text on both sides has the same
  952. // direction. European and Arabic numbers act as if they were R in
  953. // terms of their influence on neutrals. Start-of-level-run (sor)
  954. // and end-of-level-run (eor) are used at level run boundaries.
  955. // N2. Any remaining neutrals take the embedding direction.
  956. for (var i$6 = 0; i$6 < len; ++i$6) {
  957. if (isNeutral.test(types[i$6])) {
  958. var end$1 = (void 0)
  959. for (end$1 = i$6 + 1; end$1 < len && isNeutral.test(types[end$1]); ++end$1) {}
  960. var before = (i$6 ? types[i$6-1] : outerType) == "L"
  961. var after = (end$1 < len ? types[end$1] : outerType) == "L"
  962. var replace$1 = before == after ? (before ? "L" : "R") : outerType
  963. for (var j$1 = i$6; j$1 < end$1; ++j$1) { types[j$1] = replace$1 }
  964. i$6 = end$1 - 1
  965. }
  966. }
  967. // Here we depart from the documented algorithm, in order to avoid
  968. // building up an actual levels array. Since there are only three
  969. // levels (0, 1, 2) in an implementation that doesn't take
  970. // explicit embedding into account, we can build up the order on
  971. // the fly, without following the level-based algorithm.
  972. var order = [], m
  973. for (var i$7 = 0; i$7 < len;) {
  974. if (countsAsLeft.test(types[i$7])) {
  975. var start = i$7
  976. for (++i$7; i$7 < len && countsAsLeft.test(types[i$7]); ++i$7) {}
  977. order.push(new BidiSpan(0, start, i$7))
  978. } else {
  979. var pos = i$7, at = order.length
  980. for (++i$7; i$7 < len && types[i$7] != "L"; ++i$7) {}
  981. for (var j$2 = pos; j$2 < i$7;) {
  982. if (countsAsNum.test(types[j$2])) {
  983. if (pos < j$2) { order.splice(at, 0, new BidiSpan(1, pos, j$2)) }
  984. var nstart = j$2
  985. for (++j$2; j$2 < i$7 && countsAsNum.test(types[j$2]); ++j$2) {}
  986. order.splice(at, 0, new BidiSpan(2, nstart, j$2))
  987. pos = j$2
  988. } else { ++j$2 }
  989. }
  990. if (pos < i$7) { order.splice(at, 0, new BidiSpan(1, pos, i$7)) }
  991. }
  992. }
  993. if (direction == "ltr") {
  994. if (order[0].level == 1 && (m = str.match(/^\s+/))) {
  995. order[0].from = m[0].length
  996. order.unshift(new BidiSpan(0, 0, m[0].length))
  997. }
  998. if (lst(order).level == 1 && (m = str.match(/\s+$/))) {
  999. lst(order).to -= m[0].length
  1000. order.push(new BidiSpan(0, len - m[0].length, len))
  1001. }
  1002. }
  1003. return direction == "rtl" ? order.reverse() : order
  1004. }
  1005. })()
  1006. // Get the bidi ordering for the given line (and cache it). Returns
  1007. // false for lines that are fully left-to-right, and an array of
  1008. // BidiSpan objects otherwise.
  1009. function getOrder(line, direction) {
  1010. var order = line.order
  1011. if (order == null) { order = line.order = bidiOrdering(line.text, direction) }
  1012. return order
  1013. }
  1014. // EVENT HANDLING
  1015. // Lightweight event framework. on/off also work on DOM nodes,
  1016. // registering native DOM handlers.
  1017. var noHandlers = []
  1018. var on = function(emitter, type, f) {
  1019. if (emitter.addEventListener) {
  1020. emitter.addEventListener(type, f, false)
  1021. } else if (emitter.attachEvent) {
  1022. emitter.attachEvent("on" + type, f)
  1023. } else {
  1024. var map = emitter._handlers || (emitter._handlers = {})
  1025. map[type] = (map[type] || noHandlers).concat(f)
  1026. }
  1027. }
  1028. function getHandlers(emitter, type) {
  1029. return emitter._handlers && emitter._handlers[type] || noHandlers
  1030. }
  1031. function off(emitter, type, f) {
  1032. if (emitter.removeEventListener) {
  1033. emitter.removeEventListener(type, f, false)
  1034. } else if (emitter.detachEvent) {
  1035. emitter.detachEvent("on" + type, f)
  1036. } else {
  1037. var map = emitter._handlers, arr = map && map[type]
  1038. if (arr) {
  1039. var index = indexOf(arr, f)
  1040. if (index > -1)
  1041. { map[type] = arr.slice(0, index).concat(arr.slice(index + 1)) }
  1042. }
  1043. }
  1044. }
  1045. function signal(emitter, type /*, values...*/) {
  1046. var handlers = getHandlers(emitter, type)
  1047. if (!handlers.length) { return }
  1048. var args = Array.prototype.slice.call(arguments, 2)
  1049. for (var i = 0; i < handlers.length; ++i) { handlers[i].apply(null, args) }
  1050. }
  1051. // The DOM events that CodeMirror handles can be overridden by
  1052. // registering a (non-DOM) handler on the editor for the event name,
  1053. // and preventDefault-ing the event in that handler.
  1054. function signalDOMEvent(cm, e, override) {
  1055. if (typeof e == "string")
  1056. { e = {type: e, preventDefault: function() { this.defaultPrevented = true }} }
  1057. signal(cm, override || e.type, cm, e)
  1058. return e_defaultPrevented(e) || e.codemirrorIgnore
  1059. }
  1060. function signalCursorActivity(cm) {
  1061. var arr = cm._handlers && cm._handlers.cursorActivity
  1062. if (!arr) { return }
  1063. var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = [])
  1064. for (var i = 0; i < arr.length; ++i) { if (indexOf(set, arr[i]) == -1)
  1065. { set.push(arr[i]) } }
  1066. }
  1067. function hasHandler(emitter, type) {
  1068. return getHandlers(emitter, type).length > 0
  1069. }
  1070. // Add on and off methods to a constructor's prototype, to make
  1071. // registering events on such objects more convenient.
  1072. function eventMixin(ctor) {
  1073. ctor.prototype.on = function(type, f) {on(this, type, f)}
  1074. ctor.prototype.off = function(type, f) {off(this, type, f)}
  1075. }
  1076. // Due to the fact that we still support jurassic IE versions, some
  1077. // compatibility wrappers are needed.
  1078. function e_preventDefault(e) {
  1079. if (e.preventDefault) { e.preventDefault() }
  1080. else { e.returnValue = false }
  1081. }
  1082. function e_stopPropagation(e) {
  1083. if (e.stopPropagation) { e.stopPropagation() }
  1084. else { e.cancelBubble = true }
  1085. }
  1086. function e_defaultPrevented(e) {
  1087. return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false
  1088. }
  1089. function e_stop(e) {e_preventDefault(e); e_stopPropagation(e)}
  1090. function e_target(e) {return e.target || e.srcElement}
  1091. function e_button(e) {
  1092. var b = e.which
  1093. if (b == null) {
  1094. if (e.button & 1) { b = 1 }
  1095. else if (e.button & 2) { b = 3 }
  1096. else if (e.button & 4) { b = 2 }
  1097. }
  1098. if (mac && e.ctrlKey && b == 1) { b = 3 }
  1099. return b
  1100. }
  1101. // Detect drag-and-drop
  1102. var dragAndDrop = function() {
  1103. // There is *some* kind of drag-and-drop support in IE6-8, but I
  1104. // couldn't get it to work yet.
  1105. if (ie && ie_version < 9) { return false }
  1106. var div = elt('div')
  1107. return "draggable" in div || "dragDrop" in div
  1108. }()
  1109. var zwspSupported
  1110. function zeroWidthElement(measure) {
  1111. if (zwspSupported == null) {
  1112. var test = elt("span", "\u200b")
  1113. removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")]))
  1114. if (measure.firstChild.offsetHeight != 0)
  1115. { zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8) }
  1116. }
  1117. var node = zwspSupported ? elt("span", "\u200b") :
  1118. elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px")
  1119. node.setAttribute("cm-text", "")
  1120. return node
  1121. }
  1122. // Feature-detect IE's crummy client rect reporting for bidi text
  1123. var badBidiRects
  1124. function hasBadBidiRects(measure) {
  1125. if (badBidiRects != null) { return badBidiRects }
  1126. var txt = removeChildrenAndAdd(measure, document.createTextNode("A\u062eA"))
  1127. var r0 = range(txt, 0, 1).getBoundingClientRect()
  1128. var r1 = range(txt, 1, 2).getBoundingClientRect()
  1129. removeChildren(measure)
  1130. if (!r0 || r0.left == r0.right) { return false } // Safari returns null in some cases (#2780)
  1131. return badBidiRects = (r1.right - r0.right < 3)
  1132. }
  1133. // See if "".split is the broken IE version, if so, provide an
  1134. // alternative way to split lines.
  1135. var splitLinesAuto = "\n\nb".split(/\n/).length != 3 ? function (string) {
  1136. var pos = 0, result = [], l = string.length
  1137. while (pos <= l) {
  1138. var nl = string.indexOf("\n", pos)
  1139. if (nl == -1) { nl = string.length }
  1140. var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl)
  1141. var rt = line.indexOf("\r")
  1142. if (rt != -1) {
  1143. result.push(line.slice(0, rt))
  1144. pos += rt + 1
  1145. } else {
  1146. result.push(line)
  1147. pos = nl + 1
  1148. }
  1149. }
  1150. return result
  1151. } : function (string) { return string.split(/\r\n?|\n/); }
  1152. var hasSelection = window.getSelection ? function (te) {
  1153. try { return te.selectionStart != te.selectionEnd }
  1154. catch(e) { return false }
  1155. } : function (te) {
  1156. var range
  1157. try {range = te.ownerDocument.selection.createRange()}
  1158. catch(e) {}
  1159. if (!range || range.parentElement() != te) { return false }
  1160. return range.compareEndPoints("StartToEnd", range) != 0
  1161. }
  1162. var hasCopyEvent = (function () {
  1163. var e = elt("div")
  1164. if ("oncopy" in e) { return true }
  1165. e.setAttribute("oncopy", "return;")
  1166. return typeof e.oncopy == "function"
  1167. })()
  1168. var badZoomedRects = null
  1169. function hasBadZoomedRects(measure) {
  1170. if (badZoomedRects != null) { return badZoomedRects }
  1171. var node = removeChildrenAndAdd(measure, elt("span", "x"))
  1172. var normal = node.getBoundingClientRect()
  1173. var fromRange = range(node, 0, 1).getBoundingClientRect()
  1174. return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1
  1175. }
  1176. var modes = {};
  1177. var mimeModes = {};
  1178. // Extra arguments are stored as the mode's dependencies, which is
  1179. // used by (legacy) mechanisms like loadmode.js to automatically
  1180. // load a mode. (Preferred mechanism is the require/define calls.)
  1181. function defineMode(name, mode) {
  1182. if (arguments.length > 2)
  1183. { mode.dependencies = Array.prototype.slice.call(arguments, 2) }
  1184. modes[name] = mode
  1185. }
  1186. function defineMIME(mime, spec) {
  1187. mimeModes[mime] = spec
  1188. }
  1189. // Given a MIME type, a {name, ...options} config object, or a name
  1190. // string, return a mode config object.
  1191. function resolveMode(spec) {
  1192. if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) {
  1193. spec = mimeModes[spec]
  1194. } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) {
  1195. var found = mimeModes[spec.name]
  1196. if (typeof found == "string") { found = {name: found} }
  1197. spec = createObj(found, spec)
  1198. spec.name = found.name
  1199. } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) {
  1200. return resolveMode("application/xml")
  1201. } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+json$/.test(spec)) {
  1202. return resolveMode("application/json")
  1203. }
  1204. if (typeof spec == "string") { return {name: spec} }
  1205. else { return spec || {name: "null"} }
  1206. }
  1207. // Given a mode spec (anything that resolveMode accepts), find and
  1208. // initialize an actual mode object.
  1209. function getMode(options, spec) {
  1210. spec = resolveMode(spec)
  1211. var mfactory = modes[spec.name]
  1212. if (!mfactory) { return getMode(options, "text/plain") }
  1213. var modeObj = mfactory(options, spec)
  1214. if (modeExtensions.hasOwnProperty(spec.name)) {
  1215. var exts = modeExtensions[spec.name]
  1216. for (var prop in exts) {
  1217. if (!exts.hasOwnProperty(prop)) { continue }
  1218. if (modeObj.hasOwnProperty(prop)) { modeObj["_" + prop] = modeObj[prop] }
  1219. modeObj[prop] = exts[prop]
  1220. }
  1221. }
  1222. modeObj.name = spec.name
  1223. if (spec.helperType) { modeObj.helperType = spec.helperType }
  1224. if (spec.modeProps) { for (var prop$1 in spec.modeProps)
  1225. { modeObj[prop$1] = spec.modeProps[prop$1] } }
  1226. return modeObj
  1227. }
  1228. // This can be used to attach properties to mode objects from
  1229. // outside the actual mode definition.
  1230. var modeExtensions = {}
  1231. function extendMode(mode, properties) {
  1232. var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {})
  1233. copyObj(properties, exts)
  1234. }
  1235. function copyState(mode, state) {
  1236. if (state === true) { return state }
  1237. if (mode.copyState) { return mode.copyState(state) }
  1238. var nstate = {}
  1239. for (var n in state) {
  1240. var val = state[n]
  1241. if (val instanceof Array) { val = val.concat([]) }
  1242. nstate[n] = val
  1243. }
  1244. return nstate
  1245. }
  1246. // Given a mode and a state (for that mode), find the inner mode and
  1247. // state at the position that the state refers to.
  1248. function innerMode(mode, state) {
  1249. var info
  1250. while (mode.innerMode) {
  1251. info = mode.innerMode(state)
  1252. if (!info || info.mode == mode) { break }
  1253. state = info.state
  1254. mode = info.mode
  1255. }
  1256. return info || {mode: mode, state: state}
  1257. }
  1258. function startState(mode, a1, a2) {
  1259. return mode.startState ? mode.startState(a1, a2) : true
  1260. }
  1261. // STRING STREAM
  1262. // Fed to the mode parsers, provides helper functions to make
  1263. // parsers more succinct.
  1264. var StringStream = function(string, tabSize, lineOracle) {
  1265. this.pos = this.start = 0
  1266. this.string = string
  1267. this.tabSize = tabSize || 8
  1268. this.lastColumnPos = this.lastColumnValue = 0
  1269. this.lineStart = 0
  1270. this.lineOracle = lineOracle
  1271. };
  1272. StringStream.prototype.eol = function () {return this.pos >= this.string.length};
  1273. StringStream.prototype.sol = function () {return this.pos == this.lineStart};
  1274. StringStream.prototype.peek = function () {return this.string.charAt(this.pos) || undefined};
  1275. StringStream.prototype.next = function () {
  1276. if (this.pos < this.string.length)
  1277. { return this.string.charAt(this.pos++) }
  1278. };
  1279. StringStream.prototype.eat = function (match) {
  1280. var ch = this.string.charAt(this.pos)
  1281. var ok
  1282. if (typeof match == "string") { ok = ch == match }
  1283. else { ok = ch && (match.test ? match.test(ch) : match(ch)) }
  1284. if (ok) {++this.pos; return ch}
  1285. };
  1286. StringStream.prototype.eatWhile = function (match) {
  1287. var start = this.pos
  1288. while (this.eat(match)){}
  1289. return this.pos > start
  1290. };
  1291. StringStream.prototype.eatSpace = function () {
  1292. var this$1 = this;
  1293. var start = this.pos
  1294. while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) { ++this$1.pos }
  1295. return this.pos > start
  1296. };
  1297. StringStream.prototype.skipToEnd = function () {this.pos = this.string.length};
  1298. StringStream.prototype.skipTo = function (ch) {
  1299. var found = this.string.indexOf(ch, this.pos)
  1300. if (found > -1) {this.pos = found; return true}
  1301. };
  1302. StringStream.prototype.backUp = function (n) {this.pos -= n};
  1303. StringStream.prototype.column = function () {
  1304. if (this.lastColumnPos < this.start) {
  1305. this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue)
  1306. this.lastColumnPos = this.start
  1307. }
  1308. return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0)
  1309. };
  1310. StringStream.prototype.indentation = function () {
  1311. return countColumn(this.string, null, this.tabSize) -
  1312. (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0)
  1313. };
  1314. StringStream.prototype.match = function (pattern, consume, caseInsensitive) {
  1315. if (typeof pattern == "string") {
  1316. var cased = function (str) { return caseInsensitive ? str.toLowerCase() : str; }
  1317. var substr = this.string.substr(this.pos, pattern.length)
  1318. if (cased(substr) == cased(pattern)) {
  1319. if (consume !== false) { this.pos += pattern.length }
  1320. return true
  1321. }
  1322. } else {
  1323. var match = this.string.slice(this.pos).match(pattern)
  1324. if (match && match.index > 0) { return null }
  1325. if (match && consume !== false) { this.pos += match[0].length }
  1326. return match
  1327. }
  1328. };
  1329. StringStream.prototype.current = function (){return this.string.slice(this.start, this.pos)};
  1330. StringStream.prototype.hideFirstChars = function (n, inner) {
  1331. this.lineStart += n
  1332. try { return inner() }
  1333. finally { this.lineStart -= n }
  1334. };
  1335. StringStream.prototype.lookAhead = function (n) {
  1336. var oracle = this.lineOracle
  1337. return oracle && oracle.lookAhead(n)
  1338. };
  1339. StringStream.prototype.baseToken = function () {
  1340. var oracle = this.lineOracle
  1341. return oracle && oracle.baseToken(this.pos)
  1342. };
  1343. var SavedContext = function(state, lookAhead) {
  1344. this.state = state
  1345. this.lookAhead = lookAhead
  1346. };
  1347. var Context = function(doc, state, line, lookAhead) {
  1348. this.state = state
  1349. this.doc = doc
  1350. this.line = line
  1351. this.maxLookAhead = lookAhead || 0
  1352. this.baseTokens = null
  1353. this.baseTokenPos = 1
  1354. };
  1355. Context.prototype.lookAhead = function (n) {
  1356. var line = this.doc.getLine(this.line + n)
  1357. if (line != null && n > this.maxLookAhead) { this.maxLookAhead = n }
  1358. return line
  1359. };
  1360. Context.prototype.baseToken = function (n) {
  1361. var this$1 = this;
  1362. if (!this.baseTokens) { return null }
  1363. while (this.baseTokens[this.baseTokenPos] <= n)
  1364. { this$1.baseTokenPos += 2 }
  1365. var type = this.baseTokens[this.baseTokenPos + 1]
  1366. return {type: type && type.replace(/( |^)overlay .*/, ""),
  1367. size: this.baseTokens[this.baseTokenPos] - n}
  1368. };
  1369. Context.prototype.nextLine = function () {
  1370. this.line++
  1371. if (this.maxLookAhead > 0) { this.maxLookAhead-- }
  1372. };
  1373. Context.fromSaved = function (doc, saved, line) {
  1374. if (saved instanceof SavedContext)
  1375. { return new Context(doc, copyState(doc.mode, saved.state), line, saved.lookAhead) }
  1376. else
  1377. { return new Context(doc, copyState(doc.mode, saved), line) }
  1378. };
  1379. Context.prototype.save = function (copy) {
  1380. var state = copy !== false ? copyState(this.doc.mode, this.state) : this.state
  1381. return this.maxLookAhead > 0 ? new SavedContext(state, this.maxLookAhead) : state
  1382. };
  1383. // Compute a style array (an array starting with a mode generation
  1384. // -- for invalidation -- followed by pairs of end positions and
  1385. // style strings), which is used to highlight the tokens on the
  1386. // line.
  1387. function highlightLine(cm, line, context, forceToEnd) {
  1388. // A styles array always starts with a number identifying the
  1389. // mode/overlays that it is based on (for easy invalidation).
  1390. var st = [cm.state.modeGen], lineClasses = {}
  1391. // Compute the base array of styles
  1392. runMode(cm, line.text, cm.doc.mode, context, function (end, style) { return st.push(end, style); },
  1393. lineClasses, forceToEnd)
  1394. var state = context.state
  1395. // Run overlays, adjust style array.
  1396. var loop = function ( o ) {
  1397. context.baseTokens = st
  1398. var overlay = cm.state.overlays[o], i = 1, at = 0
  1399. context.state = true
  1400. runMode(cm, line.text, overlay.mode, context, function (end, style) {
  1401. var start = i
  1402. // Ensure there's a token end at the current position, and that i points at it
  1403. while (at < end) {
  1404. var i_end = st[i]
  1405. if (i_end > end)
  1406. { st.splice(i, 1, end, st[i+1], i_end) }
  1407. i += 2
  1408. at = Math.min(end, i_end)
  1409. }
  1410. if (!style) { return }
  1411. if (overlay.opaque) {
  1412. st.splice(start, i - start, end, "overlay " + style)
  1413. i = start + 2
  1414. } else {
  1415. for (; start < i; start += 2) {
  1416. var cur = st[start+1]
  1417. st[start+1] = (cur ? cur + " " : "") + "overlay " + style
  1418. }
  1419. }
  1420. }, lineClasses)
  1421. context.state = state
  1422. context.baseTokens = null
  1423. context.baseTokenPos = 1
  1424. };
  1425. for (var o = 0; o < cm.state.overlays.length; ++o) loop( o );
  1426. return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null}
  1427. }
  1428. function getLineStyles(cm, line, updateFrontier) {
  1429. if (!line.styles || line.styles[0] != cm.state.modeGen) {
  1430. var context = getContextBefore(cm, lineNo(line))
  1431. var resetState = line.text.length > cm.options.maxHighlightLength && copyState(cm.doc.mode, context.state)
  1432. var result = highlightLine(cm, line, context)
  1433. if (resetState) { context.state = resetState }
  1434. line.stateAfter = context.save(!resetState)
  1435. line.styles = result.styles
  1436. if (result.classes) { line.styleClasses = result.classes }
  1437. else if (line.styleClasses) { line.styleClasses = null }
  1438. if (updateFrontier === cm.doc.highlightFrontier)
  1439. { cm.doc.modeFrontier = Math.max(cm.doc.modeFrontier, ++cm.doc.highlightFrontier) }
  1440. }
  1441. return line.styles
  1442. }
  1443. function getContextBefore(cm, n, precise) {
  1444. var doc = cm.doc, display = cm.display
  1445. if (!doc.mode.startState) { return new Context(doc, true, n) }
  1446. var start = findStartLine(cm, n, precise)
  1447. var saved = start > doc.first && getLine(doc, start - 1).stateAfter
  1448. var context = saved ? Context.fromSaved(doc, saved, start) : new Context(doc, startState(doc.mode), start)
  1449. doc.iter(start, n, function (line) {
  1450. processLine(cm, line.text, context)
  1451. var pos = context.line
  1452. line.stateAfter = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo ? context.save() : null
  1453. context.nextLine()
  1454. })
  1455. if (precise) { doc.modeFrontier = context.line }
  1456. return context
  1457. }
  1458. // Lightweight form of highlight -- proceed over this line and
  1459. // update state, but don't save a style array. Used for lines that
  1460. // aren't currently visible.
  1461. function processLine(cm, text, context, startAt) {
  1462. var mode = cm.doc.mode
  1463. var stream = new StringStream(text, cm.options.tabSize, context)
  1464. stream.start = stream.pos = startAt || 0
  1465. if (text == "") { callBlankLine(mode, context.state) }
  1466. while (!stream.eol()) {
  1467. readToken(mode, stream, context.state)
  1468. stream.start = stream.pos
  1469. }
  1470. }
  1471. function callBlankLine(mode, state) {
  1472. if (mode.blankLine) { return mode.blankLine(state) }
  1473. if (!mode.innerMode) { return }
  1474. var inner = innerMode(mode, state)
  1475. if (inner.mode.blankLine) { return inner.mode.blankLine(inner.state) }
  1476. }
  1477. function readToken(mode, stream, state, inner) {
  1478. for (var i = 0; i < 10; i++) {
  1479. if (inner) { inner[0] = innerMode(mode, state).mode }
  1480. var style = mode.token(stream, state)
  1481. if (stream.pos > stream.start) { return style }
  1482. }
  1483. throw new Error("Mode " + mode.name + " failed to advance stream.")
  1484. }
  1485. var Token = function(stream, type, state) {
  1486. this.start = stream.start; this.end = stream.pos
  1487. this.string = stream.current()
  1488. this.type = type || null
  1489. this.state = state
  1490. };
  1491. // Utility for getTokenAt and getLineTokens
  1492. function takeToken(cm, pos, precise, asArray) {
  1493. var doc = cm.doc, mode = doc.mode, style
  1494. pos = clipPos(doc, pos)
  1495. var line = getLine(doc, pos.line), context = getContextBefore(cm, pos.line, precise)
  1496. var stream = new StringStream(line.text, cm.options.tabSize, context), tokens
  1497. if (asArray) { tokens = [] }
  1498. while ((asArray || stream.pos < pos.ch) && !stream.eol()) {
  1499. stream.start = stream.pos
  1500. style = readToken(mode, stream, context.state)
  1501. if (asArray) { tokens.push(new Token(stream, style, copyState(doc.mode, context.state))) }
  1502. }
  1503. return asArray ? tokens : new Token(stream, style, context.state)
  1504. }
  1505. function extractLineClasses(type, output) {
  1506. if (type) { for (;;) {
  1507. var lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/)
  1508. if (!lineClass) { break }
  1509. type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length)
  1510. var prop = lineClass[1] ? "bgClass" : "textClass"
  1511. if (output[prop] == null)
  1512. { output[prop] = lineClass[2] }
  1513. else if (!(new RegExp("(?:^|\s)" + lineClass[2] + "(?:$|\s)")).test(output[prop]))
  1514. { output[prop] += " " + lineClass[2] }
  1515. } }
  1516. return type
  1517. }
  1518. // Run the given mode's parser over a line, calling f for each token.
  1519. function runMode(cm, text, mode, context, f, lineClasses, forceToEnd) {
  1520. var flattenSpans = mode.flattenSpans
  1521. if (flattenSpans == null) { flattenSpans = cm.options.flattenSpans }
  1522. var curStart = 0, curStyle = null
  1523. var stream = new StringStream(text, cm.options.tabSize, context), style
  1524. var inner = cm.options.addModeClass && [null]
  1525. if (text == "") { extractLineClasses(callBlankLine(mode, context.state), lineClasses) }
  1526. while (!stream.eol()) {
  1527. if (stream.pos > cm.options.maxHighlightLength) {
  1528. flattenSpans = false
  1529. if (forceToEnd) { processLine(cm, text, context, stream.pos) }
  1530. stream.pos = text.length
  1531. style = null
  1532. } else {
  1533. style = extractLineClasses(readToken(mode, stream, context.state, inner), lineClasses)
  1534. }
  1535. if (inner) {
  1536. var mName = inner[0].name
  1537. if (mName) { style = "m-" + (style ? mName + " " + style : mName) }
  1538. }
  1539. if (!flattenSpans || curStyle != style) {
  1540. while (curStart < stream.start) {
  1541. curStart = Math.min(stream.start, curStart + 5000)
  1542. f(curStart, curStyle)
  1543. }
  1544. curStyle = style
  1545. }
  1546. stream.start = stream.pos
  1547. }
  1548. while (curStart < stream.pos) {
  1549. // Webkit seems to refuse to render text nodes longer than 57444
  1550. // characters, and returns inaccurate measurements in nodes
  1551. // starting around 5000 chars.
  1552. var pos = Math.min(stream.pos, curStart + 5000)
  1553. f(pos, curStyle)
  1554. curStart = pos
  1555. }
  1556. }
  1557. // Finds the line to start with when starting a parse. Tries to
  1558. // find a line with a stateAfter, so that it can start with a
  1559. // valid state. If that fails, it returns the line with the
  1560. // smallest indentation, which tends to need the least context to
  1561. // parse correctly.
  1562. function findStartLine(cm, n, precise) {
  1563. var minindent, minline, doc = cm.doc
  1564. var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100)
  1565. for (var search = n; search > lim; --search) {
  1566. if (search <= doc.first) { return doc.first }
  1567. var line = getLine(doc, search - 1), after = line.stateAfter
  1568. if (after && (!precise || search + (after instanceof SavedContext ? after.lookAhead : 0) <= doc.modeFrontier))
  1569. { return search }
  1570. var indented = countColumn(line.text, null, cm.options.tabSize)
  1571. if (minline == null || minindent > indented) {
  1572. minline = search - 1
  1573. minindent = indented
  1574. }
  1575. }
  1576. return minline
  1577. }
  1578. function retreatFrontier(doc, n) {
  1579. doc.modeFrontier = Math.min(doc.modeFrontier, n)
  1580. if (doc.highlightFrontier < n - 10) { return }
  1581. var start = doc.first
  1582. for (var line = n - 1; line > start; line--) {
  1583. var saved = getLine(doc, line).stateAfter
  1584. // change is on 3
  1585. // state on line 1 looked ahead 2 -- so saw 3
  1586. // test 1 + 2 < 3 should cover this
  1587. if (saved && (!(saved instanceof SavedContext) || line + saved.lookAhead < n)) {
  1588. start = line + 1
  1589. break
  1590. }
  1591. }
  1592. doc.highlightFrontier = Math.min(doc.highlightFrontier, start)
  1593. }
  1594. // LINE DATA STRUCTURE
  1595. // Line objects. These hold state related to a line, including
  1596. // highlighting info (the styles array).
  1597. var Line = function(text, markedSpans, estimateHeight) {
  1598. this.text = text
  1599. attachMarkedSpans(this, markedSpans)
  1600. this.height = estimateHeight ? estimateHeight(this) : 1
  1601. };
  1602. Line.prototype.lineNo = function () { return lineNo(this) };
  1603. eventMixin(Line)
  1604. // Change the content (text, markers) of a line. Automatically
  1605. // invalidates cached information and tries to re-estimate the
  1606. // line's height.
  1607. function updateLine(line, text, markedSpans, estimateHeight) {
  1608. line.text = text
  1609. if (line.stateAfter) { line.stateAfter = null }
  1610. if (line.styles) { line.styles = null }
  1611. if (line.order != null) { line.order = null }
  1612. detachMarkedSpans(line)
  1613. attachMarkedSpans(line, markedSpans)
  1614. var estHeight = estimateHeight ? estimateHeight(line) : 1
  1615. if (estHeight != line.height) { updateLineHeight(line, estHeight) }
  1616. }
  1617. // Detach a line from the document tree and its markers.
  1618. function cleanUpLine(line) {
  1619. line.parent = null
  1620. detachMarkedSpans(line)
  1621. }
  1622. // Convert a style as returned by a mode (either null, or a string
  1623. // containing one or more styles) to a CSS style. This is cached,
  1624. // and also looks for line-wide styles.
  1625. var styleToClassCache = {};
  1626. var styleToClassCacheWithMode = {};
  1627. function interpretTokenStyle(style, options) {
  1628. if (!style || /^\s*$/.test(style)) { return null }
  1629. var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache
  1630. return cache[style] ||
  1631. (cache[style] = style.replace(/\S+/g, "cm-$&"))
  1632. }
  1633. // Render the DOM representation of the text of a line. Also builds
  1634. // up a 'line map', which points at the DOM nodes that represent
  1635. // specific stretches of text, and is used by the measuring code.
  1636. // The returned object contains the DOM node, this map, and
  1637. // information about line-wide styles that were set by the mode.
  1638. function buildLineContent(cm, lineView) {
  1639. // The padding-right forces the element to have a 'border', which
  1640. // is needed on Webkit to be able to get line-level bounding
  1641. // rectangles for it (in measureChar).
  1642. var content = eltP("span", null, null, webkit ? "padding-right: .1px" : null)
  1643. var builder = {pre: eltP("pre", [content], "CodeMirror-line"), content: content,
  1644. col: 0, pos: 0, cm: cm,
  1645. trailingSpace: false,
  1646. splitSpaces: cm.getOption("lineWrapping")}
  1647. lineView.measure = {}
  1648. // Iterate over the logical lines that make up this visual line.
  1649. for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) {
  1650. var line = i ? lineView.rest[i - 1] : lineView.line, order = (void 0)
  1651. builder.pos = 0
  1652. builder.addToken = buildToken
  1653. // Optionally wire in some hacks into the token-rendering
  1654. // algorithm, to deal with browser quirks.
  1655. if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line, cm.doc.direction)))
  1656. { builder.addToken = buildTokenBadBidi(builder.addToken, order) }
  1657. builder.map = []
  1658. var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line)
  1659. insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate))
  1660. if (line.styleClasses) {
  1661. if (line.styleClasses.bgClass)
  1662. { builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || "") }
  1663. if (line.styleClasses.textClass)
  1664. { builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || "") }
  1665. }
  1666. // Ensure at least a single node is present, for measuring.
  1667. if (builder.map.length == 0)
  1668. { builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure))) }
  1669. // Store the map and a cache object for the current logical line
  1670. if (i == 0) {
  1671. lineView.measure.map = builder.map
  1672. lineView.measure.cache = {}
  1673. } else {
  1674. ;(lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map)
  1675. ;(lineView.measure.caches || (lineView.measure.caches = [])).push({})
  1676. }
  1677. }
  1678. // See issue #2901
  1679. if (webkit) {
  1680. var last = builder.content.lastChild
  1681. if (/\bcm-tab\b/.test(last.className) || (last.querySelector && last.querySelector(".cm-tab")))
  1682. { builder.content.className = "cm-tab-wrap-hack" }
  1683. }
  1684. signal(cm, "renderLine", cm, lineView.line, builder.pre)
  1685. if (builder.pre.className)
  1686. { builder.textClass = joinClasses(builder.pre.className, builder.textClass || "") }
  1687. return builder
  1688. }
  1689. function defaultSpecialCharPlaceholder(ch) {
  1690. var token = elt("span", "\u2022", "cm-invalidchar")
  1691. token.title = "\\u" + ch.charCodeAt(0).toString(16)
  1692. token.setAttribute("aria-label", token.title)
  1693. return token
  1694. }
  1695. // Build up the DOM representation for a single token, and add it to
  1696. // the line map. Takes care to render special characters separately.
  1697. function buildToken(builder, text, style, startStyle, endStyle, title, css) {
  1698. if (!text) { return }
  1699. var displayText = builder.splitSpaces ? splitSpaces(text, builder.trailingSpace) : text
  1700. var special = builder.cm.state.specialChars, mustWrap = false
  1701. var content
  1702. if (!special.test(text)) {
  1703. builder.col += text.length
  1704. content = document.createTextNode(displayText)
  1705. builder.map.push(builder.pos, builder.pos + text.length, content)
  1706. if (ie && ie_version < 9) { mustWrap = true }
  1707. builder.pos += text.length
  1708. } else {
  1709. content = document.createDocumentFragment()
  1710. var pos = 0
  1711. while (true) {
  1712. special.lastIndex = pos
  1713. var m = special.exec(text)
  1714. var skipped = m ? m.index - pos : text.length - pos
  1715. if (skipped) {
  1716. var txt = document.createTextNode(displayText.slice(pos, pos + skipped))
  1717. if (ie && ie_version < 9) { content.appendChild(elt("span", [txt])) }
  1718. else { content.appendChild(txt) }
  1719. builder.map.push(builder.pos, builder.pos + skipped, txt)
  1720. builder.col += skipped
  1721. builder.pos += skipped
  1722. }
  1723. if (!m) { break }
  1724. pos += skipped + 1
  1725. var txt$1 = (void 0)
  1726. if (m[0] == "\t") {
  1727. var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize
  1728. txt$1 = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab"))
  1729. txt$1.setAttribute("role", "presentation")
  1730. txt$1.setAttribute("cm-text", "\t")
  1731. builder.col += tabWidth
  1732. } else if (m[0] == "\r" || m[0] == "\n") {
  1733. txt$1 = content.appendChild(elt("span", m[0] == "\r" ? "\u240d" : "\u2424", "cm-invalidchar"))
  1734. txt$1.setAttribute("cm-text", m[0])
  1735. builder.col += 1
  1736. } else {
  1737. txt$1 = builder.cm.options.specialCharPlaceholder(m[0])
  1738. txt$1.setAttribute("cm-text", m[0])
  1739. if (ie && ie_version < 9) { content.appendChild(elt("span", [txt$1])) }
  1740. else { content.appendChild(txt$1) }
  1741. builder.col += 1
  1742. }
  1743. builder.map.push(builder.pos, builder.pos + 1, txt$1)
  1744. builder.pos++
  1745. }
  1746. }
  1747. builder.trailingSpace = displayText.charCodeAt(text.length - 1) == 32
  1748. if (style || startStyle || endStyle || mustWrap || css) {
  1749. var fullStyle = style || ""
  1750. if (startStyle) { fullStyle += startStyle }
  1751. if (endStyle) { fullStyle += endStyle }
  1752. var token = elt("span", [content], fullStyle, css)
  1753. if (title) { token.title = title }
  1754. return builder.content.appendChild(token)
  1755. }
  1756. builder.content.appendChild(content)
  1757. }
  1758. // Change some spaces to NBSP to prevent the browser from collapsing
  1759. // trailing spaces at the end of a line when rendering text (issue #1362).
  1760. function splitSpaces(text, trailingBefore) {
  1761. if (text.length > 1 && !/ /.test(text)) { return text }
  1762. var spaceBefore = trailingBefore, result = ""
  1763. for (var i = 0; i < text.length; i++) {
  1764. var ch = text.charAt(i)
  1765. if (ch == " " && spaceBefore && (i == text.length - 1 || text.charCodeAt(i + 1) == 32))
  1766. { ch = "\u00a0" }
  1767. result += ch
  1768. spaceBefore = ch == " "
  1769. }
  1770. return result
  1771. }
  1772. // Work around nonsense dimensions being reported for stretches of
  1773. // right-to-left text.
  1774. function buildTokenBadBidi(inner, order) {
  1775. return function (builder, text, style, startStyle, endStyle, title, css) {
  1776. style = style ? style + " cm-force-border" : "cm-force-border"
  1777. var start = builder.pos, end = start + text.length
  1778. for (;;) {
  1779. // Find the part that overlaps with the start of this text
  1780. var part = (void 0)
  1781. for (var i = 0; i < order.length; i++) {
  1782. part = order[i]
  1783. if (part.to > start && part.from <= start) { break }
  1784. }
  1785. if (part.to >= end) { return inner(builder, text, style, startStyle, endStyle, title, css) }
  1786. inner(builder, text.slice(0, part.to - start), style, startStyle, null, title, css)
  1787. startStyle = null
  1788. text = text.slice(part.to - start)
  1789. start = part.to
  1790. }
  1791. }
  1792. }
  1793. function buildCollapsedSpan(builder, size, marker, ignoreWidget) {
  1794. var widget = !ignoreWidget && marker.widgetNode
  1795. if (widget) { builder.map.push(builder.pos, builder.pos + size, widget) }
  1796. if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) {
  1797. if (!widget)
  1798. { widget = builder.content.appendChild(document.createElement("span")) }
  1799. widget.setAttribute("cm-marker", marker.id)
  1800. }
  1801. if (widget) {
  1802. builder.cm.display.input.setUneditable(widget)
  1803. builder.content.appendChild(widget)
  1804. }
  1805. builder.pos += size
  1806. builder.trailingSpace = false
  1807. }
  1808. // Outputs a number of spans to make up a line, taking highlighting
  1809. // and marked text into account.
  1810. function insertLineContent(line, builder, styles) {
  1811. var spans = line.markedSpans, allText = line.text, at = 0
  1812. if (!spans) {
  1813. for (var i$1 = 1; i$1 < styles.length; i$1+=2)
  1814. { builder.addToken(builder, allText.slice(at, at = styles[i$1]), interpretTokenStyle(styles[i$1+1], builder.cm.options)) }
  1815. return
  1816. }
  1817. var len = allText.length, pos = 0, i = 1, text = "", style, css
  1818. var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, title, collapsed
  1819. for (;;) {
  1820. if (nextChange == pos) { // Update current marker set
  1821. spanStyle = spanEndStyle = spanStartStyle = title = css = ""
  1822. collapsed = null; nextChange = Infinity
  1823. var foundBookmarks = [], endStyles = (void 0)
  1824. for (var j = 0; j < spans.length; ++j) {
  1825. var sp = spans[j], m = sp.marker
  1826. if (m.type == "bookmark" && sp.from == pos && m.widgetNode) {
  1827. foundBookmarks.push(m)
  1828. } else if (sp.from <= pos && (sp.to == null || sp.to > pos || m.collapsed && sp.to == pos && sp.from == pos)) {
  1829. if (sp.to != null && sp.to != pos && nextChange > sp.to) {
  1830. nextChange = sp.to
  1831. spanEndStyle = ""
  1832. }
  1833. if (m.className) { spanStyle += " " + m.className }
  1834. if (m.css) { css = (css ? css + ";" : "") + m.css }
  1835. if (m.startStyle && sp.from == pos) { spanStartStyle += " " + m.startStyle }
  1836. if (m.endStyle && sp.to == nextChange) { (endStyles || (endStyles = [])).push(m.endStyle, sp.to) }
  1837. if (m.title && !title) { title = m.title }
  1838. if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0))
  1839. { collapsed = sp }
  1840. } else if (sp.from > pos && nextChange > sp.from) {
  1841. nextChange = sp.from
  1842. }
  1843. }
  1844. if (endStyles) { for (var j$1 = 0; j$1 < endStyles.length; j$1 += 2)
  1845. { if (endStyles[j$1 + 1] == nextChange) { spanEndStyle += " " + endStyles[j$1] } } }
  1846. if (!collapsed || collapsed.from == pos) { for (var j$2 = 0; j$2 < foundBookmarks.length; ++j$2)
  1847. { buildCollapsedSpan(builder, 0, foundBookmarks[j$2]) } }
  1848. if (collapsed && (collapsed.from || 0) == pos) {
  1849. buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos,
  1850. collapsed.marker, collapsed.from == null)
  1851. if (collapsed.to == null) { return }
  1852. if (collapsed.to == pos) { collapsed = false }
  1853. }
  1854. }
  1855. if (pos >= len) { break }
  1856. var upto = Math.min(len, nextChange)
  1857. while (true) {
  1858. if (text) {
  1859. var end = pos + text.length
  1860. if (!collapsed) {
  1861. var tokenText = end > upto ? text.slice(0, upto - pos) : text
  1862. builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle,
  1863. spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", title, css)
  1864. }
  1865. if (end >= upto) {text = text.slice(upto - pos); pos = upto; break}
  1866. pos = end
  1867. spanStartStyle = ""
  1868. }
  1869. text = allText.slice(at, at = styles[i++])
  1870. style = interpretTokenStyle(styles[i++], builder.cm.options)
  1871. }
  1872. }
  1873. }
  1874. // These objects are used to represent the visible (currently drawn)
  1875. // part of the document. A LineView may correspond to multiple
  1876. // logical lines, if those are connected by collapsed ranges.
  1877. function LineView(doc, line, lineN) {
  1878. // The starting line
  1879. this.line = line
  1880. // Continuing lines, if any
  1881. this.rest = visualLineContinued(line)
  1882. // Number of logical lines in this visual line
  1883. this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1
  1884. this.node = this.text = null
  1885. this.hidden = lineIsHidden(doc, line)
  1886. }
  1887. // Create a range of LineView objects for the given lines.
  1888. function buildViewArray(cm, from, to) {
  1889. var array = [], nextPos
  1890. for (var pos = from; pos < to; pos = nextPos) {
  1891. var view = new LineView(cm.doc, getLine(cm.doc, pos), pos)
  1892. nextPos = pos + view.size
  1893. array.push(view)
  1894. }
  1895. return array
  1896. }
  1897. var operationGroup = null
  1898. function pushOperation(op) {
  1899. if (operationGroup) {
  1900. operationGroup.ops.push(op)
  1901. } else {
  1902. op.ownsGroup = operationGroup = {
  1903. ops: [op],
  1904. delayedCallbacks: []
  1905. }
  1906. }
  1907. }
  1908. function fireCallbacksForOps(group) {
  1909. // Calls delayed callbacks and cursorActivity handlers until no
  1910. // new ones appear
  1911. var callbacks = group.delayedCallbacks, i = 0
  1912. do {
  1913. for (; i < callbacks.length; i++)
  1914. { callbacks[i].call(null) }
  1915. for (var j = 0; j < group.ops.length; j++) {
  1916. var op = group.ops[j]
  1917. if (op.cursorActivityHandlers)
  1918. { while (op.cursorActivityCalled < op.cursorActivityHandlers.length)
  1919. { op.cursorActivityHandlers[op.cursorActivityCalled++].call(null, op.cm) } }
  1920. }
  1921. } while (i < callbacks.length)
  1922. }
  1923. function finishOperation(op, endCb) {
  1924. var group = op.ownsGroup
  1925. if (!group) { return }
  1926. try { fireCallbacksForOps(group) }
  1927. finally {
  1928. operationGroup = null
  1929. endCb(group)
  1930. }
  1931. }
  1932. var orphanDelayedCallbacks = null
  1933. // Often, we want to signal events at a point where we are in the
  1934. // middle of some work, but don't want the handler to start calling
  1935. // other methods on the editor, which might be in an inconsistent
  1936. // state or simply not expect any other events to happen.
  1937. // signalLater looks whether there are any handlers, and schedules
  1938. // them to be executed when the last operation ends, or, if no
  1939. // operation is active, when a timeout fires.
  1940. function signalLater(emitter, type /*, values...*/) {
  1941. var arr = getHandlers(emitter, type)
  1942. if (!arr.length) { return }
  1943. var args = Array.prototype.slice.call(arguments, 2), list
  1944. if (operationGroup) {
  1945. list = operationGroup.delayedCallbacks
  1946. } else if (orphanDelayedCallbacks) {
  1947. list = orphanDelayedCallbacks
  1948. } else {
  1949. list = orphanDelayedCallbacks = []
  1950. setTimeout(fireOrphanDelayed, 0)
  1951. }
  1952. var loop = function ( i ) {
  1953. list.push(function () { return arr[i].apply(null, args); })
  1954. };
  1955. for (var i = 0; i < arr.length; ++i)
  1956. loop( i );
  1957. }
  1958. function fireOrphanDelayed() {
  1959. var delayed = orphanDelayedCallbacks
  1960. orphanDelayedCallbacks = null
  1961. for (var i = 0; i < delayed.length; ++i) { delayed[i]() }
  1962. }
  1963. // When an aspect of a line changes, a string is added to
  1964. // lineView.changes. This updates the relevant part of the line's
  1965. // DOM structure.
  1966. function updateLineForChanges(cm, lineView, lineN, dims) {
  1967. for (var j = 0; j < lineView.changes.length; j++) {
  1968. var type = lineView.changes[j]
  1969. if (type == "text") { updateLineText(cm, lineView) }
  1970. else if (type == "gutter") { updateLineGutter(cm, lineView, lineN, dims) }
  1971. else if (type == "class") { updateLineClasses(cm, lineView) }
  1972. else if (type == "widget") { updateLineWidgets(cm, lineView, dims) }
  1973. }
  1974. lineView.changes = null
  1975. }
  1976. // Lines with gutter elements, widgets or a background class need to
  1977. // be wrapped, and have the extra elements added to the wrapper div
  1978. function ensureLineWrapped(lineView) {
  1979. if (lineView.node == lineView.text) {
  1980. lineView.node = elt("div", null, null, "position: relative")
  1981. if (lineView.text.parentNode)
  1982. { lineView.text.parentNode.replaceChild(lineView.node, lineView.text) }
  1983. lineView.node.appendChild(lineView.text)
  1984. if (ie && ie_version < 8) { lineView.node.style.zIndex = 2 }
  1985. }
  1986. return lineView.node
  1987. }
  1988. function updateLineBackground(cm, lineView) {
  1989. var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass
  1990. if (cls) { cls += " CodeMirror-linebackground" }
  1991. if (lineView.background) {
  1992. if (cls) { lineView.background.className = cls }
  1993. else { lineView.background.parentNode.removeChild(lineView.background); lineView.background = null }
  1994. } else if (cls) {
  1995. var wrap = ensureLineWrapped(lineView)
  1996. lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild)
  1997. cm.display.input.setUneditable(lineView.background)
  1998. }
  1999. }
  2000. // Wrapper around buildLineContent which will reuse the structure
  2001. // in display.externalMeasured when possible.
  2002. function getLineContent(cm, lineView) {
  2003. var ext = cm.display.externalMeasured
  2004. if (ext && ext.line == lineView.line) {
  2005. cm.display.externalMeasured = null
  2006. lineView.measure = ext.measure
  2007. return ext.built
  2008. }
  2009. return buildLineContent(cm, lineView)
  2010. }
  2011. // Redraw the line's text. Interacts with the background and text
  2012. // classes because the mode may output tokens that influence these
  2013. // classes.
  2014. function updateLineText(cm, lineView) {
  2015. var cls = lineView.text.className
  2016. var built = getLineContent(cm, lineView)
  2017. if (lineView.text == lineView.node) { lineView.node = built.pre }
  2018. lineView.text.parentNode.replaceChild(built.pre, lineView.text)
  2019. lineView.text = built.pre
  2020. if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) {
  2021. lineView.bgClass = built.bgClass
  2022. lineView.textClass = built.textClass
  2023. updateLineClasses(cm, lineView)
  2024. } else if (cls) {
  2025. lineView.text.className = cls
  2026. }
  2027. }
  2028. function updateLineClasses(cm, lineView) {
  2029. updateLineBackground(cm, lineView)
  2030. if (lineView.line.wrapClass)
  2031. { ensureLineWrapped(lineView).className = lineView.line.wrapClass }
  2032. else if (lineView.node != lineView.text)
  2033. { lineView.node.className = "" }
  2034. var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass
  2035. lineView.text.className = textClass || ""
  2036. }
  2037. function updateLineGutter(cm, lineView, lineN, dims) {
  2038. if (lineView.gutter) {
  2039. lineView.node.removeChild(lineView.gutter)
  2040. lineView.gutter = null
  2041. }
  2042. if (lineView.gutterBackground) {
  2043. lineView.node.removeChild(lineView.gutterBackground)
  2044. lineView.gutterBackground = null
  2045. }
  2046. if (lineView.line.gutterClass) {
  2047. var wrap = ensureLineWrapped(lineView)
  2048. lineView.gutterBackground = elt("div", null, "CodeMirror-gutter-background " + lineView.line.gutterClass,
  2049. ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px; width: " + (dims.gutterTotalWidth) + "px"))
  2050. cm.display.input.setUneditable(lineView.gutterBackground)
  2051. wrap.insertBefore(lineView.gutterBackground, lineView.text)
  2052. }
  2053. var markers = lineView.line.gutterMarkers
  2054. if (cm.options.lineNumbers || markers) {
  2055. var wrap$1 = ensureLineWrapped(lineView)
  2056. var gutterWrap = lineView.gutter = elt("div", null, "CodeMirror-gutter-wrapper", ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px"))
  2057. cm.display.input.setUneditable(gutterWrap)
  2058. wrap$1.insertBefore(gutterWrap, lineView.text)
  2059. if (lineView.line.gutterClass)
  2060. { gutterWrap.className += " " + lineView.line.gutterClass }
  2061. if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"]))
  2062. { lineView.lineNumber = gutterWrap.appendChild(
  2063. elt("div", lineNumberFor(cm.options, lineN),
  2064. "CodeMirror-linenumber CodeMirror-gutter-elt",
  2065. ("left: " + (dims.gutterLeft["CodeMirror-linenumbers"]) + "px; width: " + (cm.display.lineNumInnerWidth) + "px"))) }
  2066. if (markers) { for (var k = 0; k < cm.options.gutters.length; ++k) {
  2067. var id = cm.options.gutters[k], found = markers.hasOwnProperty(id) && markers[id]
  2068. if (found)
  2069. { gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt",
  2070. ("left: " + (dims.gutterLeft[id]) + "px; width: " + (dims.gutterWidth[id]) + "px"))) }
  2071. } }
  2072. }
  2073. }
  2074. function updateLineWidgets(cm, lineView, dims) {
  2075. if (lineView.alignable) { lineView.alignable = null }
  2076. for (var node = lineView.node.firstChild, next = (void 0); node; node = next) {
  2077. next = node.nextSibling
  2078. if (node.className == "CodeMirror-linewidget")
  2079. { lineView.node.removeChild(node) }
  2080. }
  2081. insertLineWidgets(cm, lineView, dims)
  2082. }
  2083. // Build a line's DOM representation from scratch
  2084. function buildLineElement(cm, lineView, lineN, dims) {
  2085. var built = getLineContent(cm, lineView)
  2086. lineView.text = lineView.node = built.pre
  2087. if (built.bgClass) { lineView.bgClass = built.bgClass }
  2088. if (built.textClass) { lineView.textClass = built.textClass }
  2089. updateLineClasses(cm, lineView)
  2090. updateLineGutter(cm, lineView, lineN, dims)
  2091. insertLineWidgets(cm, lineView, dims)
  2092. return lineView.node
  2093. }
  2094. // A lineView may contain multiple logical lines (when merged by
  2095. // collapsed spans). The widgets for all of them need to be drawn.
  2096. function insertLineWidgets(cm, lineView, dims) {
  2097. insertLineWidgetsFor(cm, lineView.line, lineView, dims, true)
  2098. if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++)
  2099. { insertLineWidgetsFor(cm, lineView.rest[i], lineView, dims, false) } }
  2100. }
  2101. function insertLineWidgetsFor(cm, line, lineView, dims, allowAbove) {
  2102. if (!line.widgets) { return }
  2103. var wrap = ensureLineWrapped(lineView)
  2104. for (var i = 0, ws = line.widgets; i < ws.length; ++i) {
  2105. var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget")
  2106. if (!widget.handleMouseEvents) { node.setAttribute("cm-ignore-events", "true") }
  2107. positionLineWidget(widget, node, lineView, dims)
  2108. cm.display.input.setUneditable(node)
  2109. if (allowAbove && widget.above)
  2110. { wrap.insertBefore(node, lineView.gutter || lineView.text) }
  2111. else
  2112. { wrap.appendChild(node) }
  2113. signalLater(widget, "redraw")
  2114. }
  2115. }
  2116. function positionLineWidget(widget, node, lineView, dims) {
  2117. if (widget.noHScroll) {
  2118. ;(lineView.alignable || (lineView.alignable = [])).push(node)
  2119. var width = dims.wrapperWidth
  2120. node.style.left = dims.fixedPos + "px"
  2121. if (!widget.coverGutter) {
  2122. width -= dims.gutterTotalWidth
  2123. node.style.paddingLeft = dims.gutterTotalWidth + "px"
  2124. }
  2125. node.style.width = width + "px"
  2126. }
  2127. if (widget.coverGutter) {
  2128. node.style.zIndex = 5
  2129. node.style.position = "relative"
  2130. if (!widget.noHScroll) { node.style.marginLeft = -dims.gutterTotalWidth + "px" }
  2131. }
  2132. }
  2133. function widgetHeight(widget) {
  2134. if (widget.height != null) { return widget.height }
  2135. var cm = widget.doc.cm
  2136. if (!cm) { return 0 }
  2137. if (!contains(document.body, widget.node)) {
  2138. var parentStyle = "position: relative;"
  2139. if (widget.coverGutter)
  2140. { parentStyle += "margin-left: -" + cm.display.gutters.offsetWidth + "px;" }
  2141. if (widget.noHScroll)
  2142. { parentStyle += "width: " + cm.display.wrapper.clientWidth + "px;" }
  2143. removeChildrenAndAdd(cm.display.measure, elt("div", [widget.node], null, parentStyle))
  2144. }
  2145. return widget.height = widget.node.parentNode.offsetHeight
  2146. }
  2147. // Return true when the given mouse event happened in a widget
  2148. function eventInWidget(display, e) {
  2149. for (var n = e_target(e); n != display.wrapper; n = n.parentNode) {
  2150. if (!n || (n.nodeType == 1 && n.getAttribute("cm-ignore-events") == "true") ||
  2151. (n.parentNode == display.sizer && n != display.mover))
  2152. { return true }
  2153. }
  2154. }
  2155. // POSITION MEASUREMENT
  2156. function paddingTop(display) {return display.lineSpace.offsetTop}
  2157. function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight}
  2158. function paddingH(display) {
  2159. if (display.cachedPaddingH) { return display.cachedPaddingH }
  2160. var e = removeChildrenAndAdd(display.measure, elt("pre", "x"))
  2161. var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle
  2162. var data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)}
  2163. if (!isNaN(data.left) && !isNaN(data.right)) { display.cachedPaddingH = data }
  2164. return data
  2165. }
  2166. function scrollGap(cm) { return scrollerGap - cm.display.nativeBarWidth }
  2167. function displayWidth(cm) {
  2168. return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth
  2169. }
  2170. function displayHeight(cm) {
  2171. return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight
  2172. }
  2173. // Ensure the lineView.wrapping.heights array is populated. This is
  2174. // an array of bottom offsets for the lines that make up a drawn
  2175. // line. When lineWrapping is on, there might be more than one
  2176. // height.
  2177. function ensureLineHeights(cm, lineView, rect) {
  2178. var wrapping = cm.options.lineWrapping
  2179. var curWidth = wrapping && displayWidth(cm)
  2180. if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) {
  2181. var heights = lineView.measure.heights = []
  2182. if (wrapping) {
  2183. lineView.measure.width = curWidth
  2184. var rects = lineView.text.firstChild.getClientRects()
  2185. for (var i = 0; i < rects.length - 1; i++) {
  2186. var cur = rects[i], next = rects[i + 1]
  2187. if (Math.abs(cur.bottom - next.bottom) > 2)
  2188. { heights.push((cur.bottom + next.top) / 2 - rect.top) }
  2189. }
  2190. }
  2191. heights.push(rect.bottom - rect.top)
  2192. }
  2193. }
  2194. // Find a line map (mapping character offsets to text nodes) and a
  2195. // measurement cache for the given line number. (A line view might
  2196. // contain multiple lines when collapsed ranges are present.)
  2197. function mapFromLineView(lineView, line, lineN) {
  2198. if (lineView.line == line)
  2199. { return {map: lineView.measure.map, cache: lineView.measure.cache} }
  2200. for (var i = 0; i < lineView.rest.length; i++)
  2201. { if (lineView.rest[i] == line)
  2202. { return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i]} } }
  2203. for (var i$1 = 0; i$1 < lineView.rest.length; i$1++)
  2204. { if (lineNo(lineView.rest[i$1]) > lineN)
  2205. { return {map: lineView.measure.maps[i$1], cache: lineView.measure.caches[i$1], before: true} } }
  2206. }
  2207. // Render a line into the hidden node display.externalMeasured. Used
  2208. // when measurement is needed for a line that's not in the viewport.
  2209. function updateExternalMeasurement(cm, line) {
  2210. line = visualLine(line)
  2211. var lineN = lineNo(line)
  2212. var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN)
  2213. view.lineN = lineN
  2214. var built = view.built = buildLineContent(cm, view)
  2215. view.text = built.pre
  2216. removeChildrenAndAdd(cm.display.lineMeasure, built.pre)
  2217. return view
  2218. }
  2219. // Get a {top, bottom, left, right} box (in line-local coordinates)
  2220. // for a given character.
  2221. function measureChar(cm, line, ch, bias) {
  2222. return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias)
  2223. }
  2224. // Find a line view that corresponds to the given line number.
  2225. function findViewForLine(cm, lineN) {
  2226. if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo)
  2227. { return cm.display.view[findViewIndex(cm, lineN)] }
  2228. var ext = cm.display.externalMeasured
  2229. if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size)
  2230. { return ext }
  2231. }
  2232. // Measurement can be split in two steps, the set-up work that
  2233. // applies to the whole line, and the measurement of the actual
  2234. // character. Functions like coordsChar, that need to do a lot of
  2235. // measurements in a row, can thus ensure that the set-up work is
  2236. // only done once.
  2237. function prepareMeasureForLine(cm, line) {
  2238. var lineN = lineNo(line)
  2239. var view = findViewForLine(cm, lineN)
  2240. if (view && !view.text) {
  2241. view = null
  2242. } else if (view && view.changes) {
  2243. updateLineForChanges(cm, view, lineN, getDimensions(cm))
  2244. cm.curOp.forceUpdate = true
  2245. }
  2246. if (!view)
  2247. { view = updateExternalMeasurement(cm, line) }
  2248. var info = mapFromLineView(view, line, lineN)
  2249. return {
  2250. line: line, view: view, rect: null,
  2251. map: info.map, cache: info.cache, before: info.before,
  2252. hasHeights: false
  2253. }
  2254. }
  2255. // Given a prepared measurement object, measures the position of an
  2256. // actual character (or fetches it from the cache).
  2257. function measureCharPrepared(cm, prepared, ch, bias, varHeight) {
  2258. if (prepared.before) { ch = -1 }
  2259. var key = ch + (bias || ""), found
  2260. if (prepared.cache.hasOwnProperty(key)) {
  2261. found = prepared.cache[key]
  2262. } else {
  2263. if (!prepared.rect)
  2264. { prepared.rect = prepared.view.text.getBoundingClientRect() }
  2265. if (!prepared.hasHeights) {
  2266. ensureLineHeights(cm, prepared.view, prepared.rect)
  2267. prepared.hasHeights = true
  2268. }
  2269. found = measureCharInner(cm, prepared, ch, bias)
  2270. if (!found.bogus) { prepared.cache[key] = found }
  2271. }
  2272. return {left: found.left, right: found.right,
  2273. top: varHeight ? found.rtop : found.top,
  2274. bottom: varHeight ? found.rbottom : found.bottom}
  2275. }
  2276. var nullRect = {left: 0, right: 0, top: 0, bottom: 0}
  2277. function nodeAndOffsetInLineMap(map, ch, bias) {
  2278. var node, start, end, collapse, mStart, mEnd
  2279. // First, search the line map for the text node corresponding to,
  2280. // or closest to, the target character.
  2281. for (var i = 0; i < map.length; i += 3) {
  2282. mStart = map[i]
  2283. mEnd = map[i + 1]
  2284. if (ch < mStart) {
  2285. start = 0; end = 1
  2286. collapse = "left"
  2287. } else if (ch < mEnd) {
  2288. start = ch - mStart
  2289. end = start + 1
  2290. } else if (i == map.length - 3 || ch == mEnd && map[i + 3] > ch) {
  2291. end = mEnd - mStart
  2292. start = end - 1
  2293. if (ch >= mEnd) { collapse = "right" }
  2294. }
  2295. if (start != null) {
  2296. node = map[i + 2]
  2297. if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right"))
  2298. { collapse = bias }
  2299. if (bias == "left" && start == 0)
  2300. { while (i && map[i - 2] == map[i - 3] && map[i - 1].insertLeft) {
  2301. node = map[(i -= 3) + 2]
  2302. collapse = "left"
  2303. } }
  2304. if (bias == "right" && start == mEnd - mStart)
  2305. { while (i < map.length - 3 && map[i + 3] == map[i + 4] && !map[i + 5].insertLeft) {
  2306. node = map[(i += 3) + 2]
  2307. collapse = "right"
  2308. } }
  2309. break
  2310. }
  2311. }
  2312. return {node: node, start: start, end: end, collapse: collapse, coverStart: mStart, coverEnd: mEnd}
  2313. }
  2314. function getUsefulRect(rects, bias) {
  2315. var rect = nullRect
  2316. if (bias == "left") { for (var i = 0; i < rects.length; i++) {
  2317. if ((rect = rects[i]).left != rect.right) { break }
  2318. } } else { for (var i$1 = rects.length - 1; i$1 >= 0; i$1--) {
  2319. if ((rect = rects[i$1]).left != rect.right) { break }
  2320. } }
  2321. return rect
  2322. }
  2323. function measureCharInner(cm, prepared, ch, bias) {
  2324. var place = nodeAndOffsetInLineMap(prepared.map, ch, bias)
  2325. var node = place.node, start = place.start, end = place.end, collapse = place.collapse
  2326. var rect
  2327. if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates.
  2328. for (var i$1 = 0; i$1 < 4; i$1++) { // Retry a maximum of 4 times when nonsense rectangles are returned
  2329. while (start && isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) { --start }
  2330. while (place.coverStart + end < place.coverEnd && isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) { ++end }
  2331. if (ie && ie_version < 9 && start == 0 && end == place.coverEnd - place.coverStart)
  2332. { rect = node.parentNode.getBoundingClientRect() }
  2333. else
  2334. { rect = getUsefulRect(range(node, start, end).getClientRects(), bias) }
  2335. if (rect.left || rect.right || start == 0) { break }
  2336. end = start
  2337. start = start - 1
  2338. collapse = "right"
  2339. }
  2340. if (ie && ie_version < 11) { rect = maybeUpdateRectForZooming(cm.display.measure, rect) }
  2341. } else { // If it is a widget, simply get the box for the whole widget.
  2342. if (start > 0) { collapse = bias = "right" }
  2343. var rects
  2344. if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1)
  2345. { rect = rects[bias == "right" ? rects.length - 1 : 0] }
  2346. else
  2347. { rect = node.getBoundingClientRect() }
  2348. }
  2349. if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) {
  2350. var rSpan = node.parentNode.getClientRects()[0]
  2351. if (rSpan)
  2352. { rect = {left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom} }
  2353. else
  2354. { rect = nullRect }
  2355. }
  2356. var rtop = rect.top - prepared.rect.top, rbot = rect.bottom - prepared.rect.top
  2357. var mid = (rtop + rbot) / 2
  2358. var heights = prepared.view.measure.heights
  2359. var i = 0
  2360. for (; i < heights.length - 1; i++)
  2361. { if (mid < heights[i]) { break } }
  2362. var top = i ? heights[i - 1] : 0, bot = heights[i]
  2363. var result = {left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left,
  2364. right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left,
  2365. top: top, bottom: bot}
  2366. if (!rect.left && !rect.right) { result.bogus = true }
  2367. if (!cm.options.singleCursorHeightPerLine) { result.rtop = rtop; result.rbottom = rbot }
  2368. return result
  2369. }
  2370. // Work around problem with bounding client rects on ranges being
  2371. // returned incorrectly when zoomed on IE10 and below.
  2372. function maybeUpdateRectForZooming(measure, rect) {
  2373. if (!window.screen || screen.logicalXDPI == null ||
  2374. screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure))
  2375. { return rect }
  2376. var scaleX = screen.logicalXDPI / screen.deviceXDPI
  2377. var scaleY = screen.logicalYDPI / screen.deviceYDPI
  2378. return {left: rect.left * scaleX, right: rect.right * scaleX,
  2379. top: rect.top * scaleY, bottom: rect.bottom * scaleY}
  2380. }
  2381. function clearLineMeasurementCacheFor(lineView) {
  2382. if (lineView.measure) {
  2383. lineView.measure.cache = {}
  2384. lineView.measure.heights = null
  2385. if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++)
  2386. { lineView.measure.caches[i] = {} } }
  2387. }
  2388. }
  2389. function clearLineMeasurementCache(cm) {
  2390. cm.display.externalMeasure = null
  2391. removeChildren(cm.display.lineMeasure)
  2392. for (var i = 0; i < cm.display.view.length; i++)
  2393. { clearLineMeasurementCacheFor(cm.display.view[i]) }
  2394. }
  2395. function clearCaches(cm) {
  2396. clearLineMeasurementCache(cm)
  2397. cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null
  2398. if (!cm.options.lineWrapping) { cm.display.maxLineChanged = true }
  2399. cm.display.lineNumChars = null
  2400. }
  2401. function pageScrollX() {
  2402. // Work around https://bugs.chromium.org/p/chromium/issues/detail?id=489206
  2403. // which causes page_Offset and bounding client rects to use
  2404. // different reference viewports and invalidate our calculations.
  2405. if (chrome && android) { return -(document.body.getBoundingClientRect().left - parseInt(getComputedStyle(document.body).marginLeft)) }
  2406. return window.pageXOffset || (document.documentElement || document.body).scrollLeft
  2407. }
  2408. function pageScrollY() {
  2409. if (chrome && android) { return -(document.body.getBoundingClientRect().top - parseInt(getComputedStyle(document.body).marginTop)) }
  2410. return window.pageYOffset || (document.documentElement || document.body).scrollTop
  2411. }
  2412. function widgetTopHeight(lineObj) {
  2413. var height = 0
  2414. if (lineObj.widgets) { for (var i = 0; i < lineObj.widgets.length; ++i) { if (lineObj.widgets[i].above)
  2415. { height += widgetHeight(lineObj.widgets[i]) } } }
  2416. return height
  2417. }
  2418. // Converts a {top, bottom, left, right} box from line-local
  2419. // coordinates into another coordinate system. Context may be one of
  2420. // "line", "div" (display.lineDiv), "local"./null (editor), "window",
  2421. // or "page".
  2422. function intoCoordSystem(cm, lineObj, rect, context, includeWidgets) {
  2423. if (!includeWidgets) {
  2424. var height = widgetTopHeight(lineObj)
  2425. rect.top += height; rect.bottom += height
  2426. }
  2427. if (context == "line") { return rect }
  2428. if (!context) { context = "local" }
  2429. var yOff = heightAtLine(lineObj)
  2430. if (context == "local") { yOff += paddingTop(cm.display) }
  2431. else { yOff -= cm.display.viewOffset }
  2432. if (context == "page" || context == "window") {
  2433. var lOff = cm.display.lineSpace.getBoundingClientRect()
  2434. yOff += lOff.top + (context == "window" ? 0 : pageScrollY())
  2435. var xOff = lOff.left + (context == "window" ? 0 : pageScrollX())
  2436. rect.left += xOff; rect.right += xOff
  2437. }
  2438. rect.top += yOff; rect.bottom += yOff
  2439. return rect
  2440. }
  2441. // Coverts a box from "div" coords to another coordinate system.
  2442. // Context may be "window", "page", "div", or "local"./null.
  2443. function fromCoordSystem(cm, coords, context) {
  2444. if (context == "div") { return coords }
  2445. var left = coords.left, top = coords.top
  2446. // First move into "page" coordinate system
  2447. if (context == "page") {
  2448. left -= pageScrollX()
  2449. top -= pageScrollY()
  2450. } else if (context == "local" || !context) {
  2451. var localBox = cm.display.sizer.getBoundingClientRect()
  2452. left += localBox.left
  2453. top += localBox.top
  2454. }
  2455. var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect()
  2456. return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top}
  2457. }
  2458. function charCoords(cm, pos, context, lineObj, bias) {
  2459. if (!lineObj) { lineObj = getLine(cm.doc, pos.line) }
  2460. return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context)
  2461. }
  2462. // Returns a box for a given cursor position, which may have an
  2463. // 'other' property containing the position of the secondary cursor
  2464. // on a bidi boundary.
  2465. // A cursor Pos(line, char, "before") is on the same visual line as `char - 1`
  2466. // and after `char - 1` in writing order of `char - 1`
  2467. // A cursor Pos(line, char, "after") is on the same visual line as `char`
  2468. // and before `char` in writing order of `char`
  2469. // Examples (upper-case letters are RTL, lower-case are LTR):
  2470. // Pos(0, 1, ...)
  2471. // before after
  2472. // ab a|b a|b
  2473. // aB a|B aB|
  2474. // Ab |Ab A|b
  2475. // AB B|A B|A
  2476. // Every position after the last character on a line is considered to stick
  2477. // to the last character on the line.
  2478. function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) {
  2479. lineObj = lineObj || getLine(cm.doc, pos.line)
  2480. if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj) }
  2481. function get(ch, right) {
  2482. var m = measureCharPrepared(cm, preparedMeasure, ch, right ? "right" : "left", varHeight)
  2483. if (right) { m.left = m.right; } else { m.right = m.left }
  2484. return intoCoordSystem(cm, lineObj, m, context)
  2485. }
  2486. var order = getOrder(lineObj, cm.doc.direction), ch = pos.ch, sticky = pos.sticky
  2487. if (ch >= lineObj.text.length) {
  2488. ch = lineObj.text.length
  2489. sticky = "before"
  2490. } else if (ch <= 0) {
  2491. ch = 0
  2492. sticky = "after"
  2493. }
  2494. if (!order) { return get(sticky == "before" ? ch - 1 : ch, sticky == "before") }
  2495. function getBidi(ch, partPos, invert) {
  2496. var part = order[partPos], right = part.level == 1
  2497. return get(invert ? ch - 1 : ch, right != invert)
  2498. }
  2499. var partPos = getBidiPartAt(order, ch, sticky)
  2500. var other = bidiOther
  2501. var val = getBidi(ch, partPos, sticky == "before")
  2502. if (other != null) { val.other = getBidi(ch, other, sticky != "before") }
  2503. return val
  2504. }
  2505. // Used to cheaply estimate the coordinates for a position. Used for
  2506. // intermediate scroll updates.
  2507. function estimateCoords(cm, pos) {
  2508. var left = 0
  2509. pos = clipPos(cm.doc, pos)
  2510. if (!cm.options.lineWrapping) { left = charWidth(cm.display) * pos.ch }
  2511. var lineObj = getLine(cm.doc, pos.line)
  2512. var top = heightAtLine(lineObj) + paddingTop(cm.display)
  2513. return {left: left, right: left, top: top, bottom: top + lineObj.height}
  2514. }
  2515. // Positions returned by coordsChar contain some extra information.
  2516. // xRel is the relative x position of the input coordinates compared
  2517. // to the found position (so xRel > 0 means the coordinates are to
  2518. // the right of the character position, for example). When outside
  2519. // is true, that means the coordinates lie outside the line's
  2520. // vertical range.
  2521. function PosWithInfo(line, ch, sticky, outside, xRel) {
  2522. var pos = Pos(line, ch, sticky)
  2523. pos.xRel = xRel
  2524. if (outside) { pos.outside = true }
  2525. return pos
  2526. }
  2527. // Compute the character position closest to the given coordinates.
  2528. // Input must be lineSpace-local ("div" coordinate system).
  2529. function coordsChar(cm, x, y) {
  2530. var doc = cm.doc
  2531. y += cm.display.viewOffset
  2532. if (y < 0) { return PosWithInfo(doc.first, 0, null, true, -1) }
  2533. var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1
  2534. if (lineN > last)
  2535. { return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, null, true, 1) }
  2536. if (x < 0) { x = 0 }
  2537. var lineObj = getLine(doc, lineN)
  2538. for (;;) {
  2539. var found = coordsCharInner(cm, lineObj, lineN, x, y)
  2540. var collapsed = collapsedSpanAround(lineObj, found.ch + (found.xRel > 0 ? 1 : 0))
  2541. if (!collapsed) { return found }
  2542. var rangeEnd = collapsed.find(1)
  2543. if (rangeEnd.line == lineN) { return rangeEnd }
  2544. lineObj = getLine(doc, lineN = rangeEnd.line)
  2545. }
  2546. }
  2547. function wrappedLineExtent(cm, lineObj, preparedMeasure, y) {
  2548. y -= widgetTopHeight(lineObj)
  2549. var end = lineObj.text.length
  2550. var begin = findFirst(function (ch) { return measureCharPrepared(cm, preparedMeasure, ch - 1).bottom <= y; }, end, 0)
  2551. end = findFirst(function (ch) { return measureCharPrepared(cm, preparedMeasure, ch).top > y; }, begin, end)
  2552. return {begin: begin, end: end}
  2553. }
  2554. function wrappedLineExtentChar(cm, lineObj, preparedMeasure, target) {
  2555. if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj) }
  2556. var targetTop = intoCoordSystem(cm, lineObj, measureCharPrepared(cm, preparedMeasure, target), "line").top
  2557. return wrappedLineExtent(cm, lineObj, preparedMeasure, targetTop)
  2558. }
  2559. // Returns true if the given side of a box is after the given
  2560. // coordinates, in top-to-bottom, left-to-right order.
  2561. function boxIsAfter(box, x, y, left) {
  2562. return box.bottom <= y ? false : box.top > y ? true : (left ? box.left : box.right) > x
  2563. }
  2564. function coordsCharInner(cm, lineObj, lineNo, x, y) {
  2565. // Move y into line-local coordinate space
  2566. y -= heightAtLine(lineObj)
  2567. var preparedMeasure = prepareMeasureForLine(cm, lineObj)
  2568. // When directly calling `measureCharPrepared`, we have to adjust
  2569. // for the widgets at this line.
  2570. var widgetHeight = widgetTopHeight(lineObj)
  2571. var begin = 0, end = lineObj.text.length, ltr = true
  2572. var order = getOrder(lineObj, cm.doc.direction)
  2573. // If the line isn't plain left-to-right text, first figure out
  2574. // which bidi section the coordinates fall into.
  2575. if (order) {
  2576. var part = (cm.options.lineWrapping ? coordsBidiPartWrapped : coordsBidiPart)
  2577. (cm, lineObj, lineNo, preparedMeasure, order, x, y)
  2578. ltr = part.level != 1
  2579. // The awkward -1 offsets are needed because findFirst (called
  2580. // on these below) will treat its first bound as inclusive,
  2581. // second as exclusive, but we want to actually address the
  2582. // characters in the part's range
  2583. begin = ltr ? part.from : part.to - 1
  2584. end = ltr ? part.to : part.from - 1
  2585. }
  2586. // A binary search to find the first character whose bounding box
  2587. // starts after the coordinates. If we run across any whose box wrap
  2588. // the coordinates, store that.
  2589. var chAround = null, boxAround = null
  2590. var ch = findFirst(function (ch) {
  2591. var box = measureCharPrepared(cm, preparedMeasure, ch)
  2592. box.top += widgetHeight; box.bottom += widgetHeight
  2593. if (!boxIsAfter(box, x, y, false)) { return false }
  2594. if (box.top <= y && box.left <= x) {
  2595. chAround = ch
  2596. boxAround = box
  2597. }
  2598. return true
  2599. }, begin, end)
  2600. var baseX, sticky, outside = false
  2601. // If a box around the coordinates was found, use that
  2602. if (boxAround) {
  2603. // Distinguish coordinates nearer to the left or right side of the box
  2604. var atLeft = x - boxAround.left < boxAround.right - x, atStart = atLeft == ltr
  2605. ch = chAround + (atStart ? 0 : 1)
  2606. sticky = atStart ? "after" : "before"
  2607. baseX = atLeft ? boxAround.left : boxAround.right
  2608. } else {
  2609. // (Adjust for extended bound, if necessary.)
  2610. if (!ltr && (ch == end || ch == begin)) { ch++ }
  2611. // To determine which side to associate with, get the box to the
  2612. // left of the character and compare it's vertical position to the
  2613. // coordinates
  2614. sticky = ch == 0 ? "after" : ch == lineObj.text.length ? "before" :
  2615. (measureCharPrepared(cm, preparedMeasure, ch - (ltr ? 1 : 0)).bottom + widgetHeight <= y) == ltr ?
  2616. "after" : "before"
  2617. // Now get accurate coordinates for this place, in order to get a
  2618. // base X position
  2619. var coords = cursorCoords(cm, Pos(lineNo, ch, sticky), "line", lineObj, preparedMeasure)
  2620. baseX = coords.left
  2621. outside = y < coords.top || y >= coords.bottom
  2622. }
  2623. ch = skipExtendingChars(lineObj.text, ch, 1)
  2624. return PosWithInfo(lineNo, ch, sticky, outside, x - baseX)
  2625. }
  2626. function coordsBidiPart(cm, lineObj, lineNo, preparedMeasure, order, x, y) {
  2627. // Bidi parts are sorted left-to-right, and in a non-line-wrapping
  2628. // situation, we can take this ordering to correspond to the visual
  2629. // ordering. This finds the first part whose end is after the given
  2630. // coordinates.
  2631. var index = findFirst(function (i) {
  2632. var part = order[i], ltr = part.level != 1
  2633. return boxIsAfter(cursorCoords(cm, Pos(lineNo, ltr ? part.to : part.from, ltr ? "before" : "after"),
  2634. "line", lineObj, preparedMeasure), x, y, true)
  2635. }, 0, order.length - 1)
  2636. var part = order[index]
  2637. // If this isn't the first part, the part's start is also after
  2638. // the coordinates, and the coordinates aren't on the same line as
  2639. // that start, move one part back.
  2640. if (index > 0) {
  2641. var ltr = part.level != 1
  2642. var start = cursorCoords(cm, Pos(lineNo, ltr ? part.from : part.to, ltr ? "after" : "before"),
  2643. "line", lineObj, preparedMeasure)
  2644. if (boxIsAfter(start, x, y, true) && start.top > y)
  2645. { part = order[index - 1] }
  2646. }
  2647. return part
  2648. }
  2649. function coordsBidiPartWrapped(cm, lineObj, _lineNo, preparedMeasure, order, x, y) {
  2650. // In a wrapped line, rtl text on wrapping boundaries can do things
  2651. // that don't correspond to the ordering in our `order` array at
  2652. // all, so a binary search doesn't work, and we want to return a
  2653. // part that only spans one line so that the binary search in
  2654. // coordsCharInner is safe. As such, we first find the extent of the
  2655. // wrapped line, and then do a flat search in which we discard any
  2656. // spans that aren't on the line.
  2657. var ref = wrappedLineExtent(cm, lineObj, preparedMeasure, y);
  2658. var begin = ref.begin;
  2659. var end = ref.end;
  2660. if (/\s/.test(lineObj.text.charAt(end - 1))) { end-- }
  2661. var part = null, closestDist = null
  2662. for (var i = 0; i < order.length; i++) {
  2663. var p = order[i]
  2664. if (p.from >= end || p.to <= begin) { continue }
  2665. var ltr = p.level != 1
  2666. var endX = measureCharPrepared(cm, preparedMeasure, ltr ? Math.min(end, p.to) - 1 : Math.max(begin, p.from)).right
  2667. // Weigh against spans ending before this, so that they are only
  2668. // picked if nothing ends after
  2669. var dist = endX < x ? x - endX + 1e9 : endX - x
  2670. if (!part || closestDist > dist) {
  2671. part = p
  2672. closestDist = dist
  2673. }
  2674. }
  2675. if (!part) { part = order[order.length - 1] }
  2676. // Clip the part to the wrapped line.
  2677. if (part.from < begin) { part = {from: begin, to: part.to, level: part.level} }
  2678. if (part.to > end) { part = {from: part.from, to: end, level: part.level} }
  2679. return part
  2680. }
  2681. var measureText
  2682. // Compute the default text height.
  2683. function textHeight(display) {
  2684. if (display.cachedTextHeight != null) { return display.cachedTextHeight }
  2685. if (measureText == null) {
  2686. measureText = elt("pre")
  2687. // Measure a bunch of lines, for browsers that compute
  2688. // fractional heights.
  2689. for (var i = 0; i < 49; ++i) {
  2690. measureText.appendChild(document.createTextNode("x"))
  2691. measureText.appendChild(elt("br"))
  2692. }
  2693. measureText.appendChild(document.createTextNode("x"))
  2694. }
  2695. removeChildrenAndAdd(display.measure, measureText)
  2696. var height = measureText.offsetHeight / 50
  2697. if (height > 3) { display.cachedTextHeight = height }
  2698. removeChildren(display.measure)
  2699. return height || 1
  2700. }
  2701. // Compute the default character width.
  2702. function charWidth(display) {
  2703. if (display.cachedCharWidth != null) { return display.cachedCharWidth }
  2704. var anchor = elt("span", "xxxxxxxxxx")
  2705. var pre = elt("pre", [anchor])
  2706. removeChildrenAndAdd(display.measure, pre)
  2707. var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10
  2708. if (width > 2) { display.cachedCharWidth = width }
  2709. return width || 10
  2710. }
  2711. // Do a bulk-read of the DOM positions and sizes needed to draw the
  2712. // view, so that we don't interleave reading and writing to the DOM.
  2713. function getDimensions(cm) {
  2714. var d = cm.display, left = {}, width = {}
  2715. var gutterLeft = d.gutters.clientLeft
  2716. for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) {
  2717. left[cm.options.gutters[i]] = n.offsetLeft + n.clientLeft + gutterLeft
  2718. width[cm.options.gutters[i]] = n.clientWidth
  2719. }
  2720. return {fixedPos: compensateForHScroll(d),
  2721. gutterTotalWidth: d.gutters.offsetWidth,
  2722. gutterLeft: left,
  2723. gutterWidth: width,
  2724. wrapperWidth: d.wrapper.clientWidth}
  2725. }
  2726. // Computes display.scroller.scrollLeft + display.gutters.offsetWidth,
  2727. // but using getBoundingClientRect to get a sub-pixel-accurate
  2728. // result.
  2729. function compensateForHScroll(display) {
  2730. return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left
  2731. }
  2732. // Returns a function that estimates the height of a line, to use as
  2733. // first approximation until the line becomes visible (and is thus
  2734. // properly measurable).
  2735. function estimateHeight(cm) {
  2736. var th = textHeight(cm.display), wrapping = cm.options.lineWrapping
  2737. var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3)
  2738. return function (line) {
  2739. if (lineIsHidden(cm.doc, line)) { return 0 }
  2740. var widgetsHeight = 0
  2741. if (line.widgets) { for (var i = 0; i < line.widgets.length; i++) {
  2742. if (line.widgets[i].height) { widgetsHeight += line.widgets[i].height }
  2743. } }
  2744. if (wrapping)
  2745. { return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th }
  2746. else
  2747. { return widgetsHeight + th }
  2748. }
  2749. }
  2750. function estimateLineHeights(cm) {
  2751. var doc = cm.doc, est = estimateHeight(cm)
  2752. doc.iter(function (line) {
  2753. var estHeight = est(line)
  2754. if (estHeight != line.height) { updateLineHeight(line, estHeight) }
  2755. })
  2756. }
  2757. // Given a mouse event, find the corresponding position. If liberal
  2758. // is false, it checks whether a gutter or scrollbar was clicked,
  2759. // and returns null if it was. forRect is used by rectangular
  2760. // selections, and tries to estimate a character position even for
  2761. // coordinates beyond the right of the text.
  2762. function posFromMouse(cm, e, liberal, forRect) {
  2763. var display = cm.display
  2764. if (!liberal && e_target(e).getAttribute("cm-not-content") == "true") { return null }
  2765. var x, y, space = display.lineSpace.getBoundingClientRect()
  2766. // Fails unpredictably on IE[67] when mouse is dragged around quickly.
  2767. try { x = e.clientX - space.left; y = e.clientY - space.top }
  2768. catch (e) { return null }
  2769. var coords = coordsChar(cm, x, y), line
  2770. if (forRect && coords.xRel == 1 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) {
  2771. var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length
  2772. coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff))
  2773. }
  2774. return coords
  2775. }
  2776. // Find the view element corresponding to a given line. Return null
  2777. // when the line isn't visible.
  2778. function findViewIndex(cm, n) {
  2779. if (n >= cm.display.viewTo) { return null }
  2780. n -= cm.display.viewFrom
  2781. if (n < 0) { return null }
  2782. var view = cm.display.view
  2783. for (var i = 0; i < view.length; i++) {
  2784. n -= view[i].size
  2785. if (n < 0) { return i }
  2786. }
  2787. }
  2788. function updateSelection(cm) {
  2789. cm.display.input.showSelection(cm.display.input.prepareSelection())
  2790. }
  2791. function prepareSelection(cm, primary) {
  2792. if ( primary === void 0 ) primary = true;
  2793. var doc = cm.doc, result = {}
  2794. var curFragment = result.cursors = document.createDocumentFragment()
  2795. var selFragment = result.selection = document.createDocumentFragment()
  2796. for (var i = 0; i < doc.sel.ranges.length; i++) {
  2797. if (!primary && i == doc.sel.primIndex) { continue }
  2798. var range = doc.sel.ranges[i]
  2799. if (range.from().line >= cm.display.viewTo || range.to().line < cm.display.viewFrom) { continue }
  2800. var collapsed = range.empty()
  2801. if (collapsed || cm.options.showCursorWhenSelecting)
  2802. { drawSelectionCursor(cm, range.head, curFragment) }
  2803. if (!collapsed)
  2804. { drawSelectionRange(cm, range, selFragment) }
  2805. }
  2806. return result
  2807. }
  2808. // Draws a cursor for the given range
  2809. function drawSelectionCursor(cm, head, output) {
  2810. var pos = cursorCoords(cm, head, "div", null, null, !cm.options.singleCursorHeightPerLine)
  2811. var cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor"))
  2812. cursor.style.left = pos.left + "px"
  2813. cursor.style.top = pos.top + "px"
  2814. cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px"
  2815. if (pos.other) {
  2816. // Secondary cursor, shown when on a 'jump' in bi-directional text
  2817. var otherCursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor"))
  2818. otherCursor.style.display = ""
  2819. otherCursor.style.left = pos.other.left + "px"
  2820. otherCursor.style.top = pos.other.top + "px"
  2821. otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px"
  2822. }
  2823. }
  2824. function cmpCoords(a, b) { return a.top - b.top || a.left - b.left }
  2825. // Draws the given range as a highlighted selection
  2826. function drawSelectionRange(cm, range, output) {
  2827. var display = cm.display, doc = cm.doc
  2828. var fragment = document.createDocumentFragment()
  2829. var padding = paddingH(cm.display), leftSide = padding.left
  2830. var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right
  2831. var docLTR = doc.direction == "ltr"
  2832. function add(left, top, width, bottom) {
  2833. if (top < 0) { top = 0 }
  2834. top = Math.round(top)
  2835. bottom = Math.round(bottom)
  2836. 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")))
  2837. }
  2838. function drawForLine(line, fromArg, toArg) {
  2839. var lineObj = getLine(doc, line)
  2840. var lineLen = lineObj.text.length
  2841. var start, end
  2842. function coords(ch, bias) {
  2843. return charCoords(cm, Pos(line, ch), "div", lineObj, bias)
  2844. }
  2845. function wrapX(pos, dir, side) {
  2846. var extent = wrappedLineExtentChar(cm, lineObj, null, pos)
  2847. var prop = (dir == "ltr") == (side == "after") ? "left" : "right"
  2848. var ch = side == "after" ? extent.begin : extent.end - (/\s/.test(lineObj.text.charAt(extent.end - 1)) ? 2 : 1)
  2849. return coords(ch, prop)[prop]
  2850. }
  2851. var order = getOrder(lineObj, doc.direction)
  2852. iterateBidiSections(order, fromArg || 0, toArg == null ? lineLen : toArg, function (from, to, dir, i) {
  2853. var ltr = dir == "ltr"
  2854. var fromPos = coords(from, ltr ? "left" : "right")
  2855. var toPos = coords(to - 1, ltr ? "right" : "left")
  2856. var openStart = fromArg == null && from == 0, openEnd = toArg == null && to == lineLen
  2857. var first = i == 0, last = !order || i == order.length - 1
  2858. if (toPos.top - fromPos.top <= 3) { // Single line
  2859. var openLeft = (docLTR ? openStart : openEnd) && first
  2860. var openRight = (docLTR ? openEnd : openStart) && last
  2861. var left = openLeft ? leftSide : (ltr ? fromPos : toPos).left
  2862. var right = openRight ? rightSide : (ltr ? toPos : fromPos).right
  2863. add(left, fromPos.top, right - left, fromPos.bottom)
  2864. } else { // Multiple lines
  2865. var topLeft, topRight, botLeft, botRight
  2866. if (ltr) {
  2867. topLeft = docLTR && openStart && first ? leftSide : fromPos.left
  2868. topRight = docLTR ? rightSide : wrapX(from, dir, "before")
  2869. botLeft = docLTR ? leftSide : wrapX(to, dir, "after")
  2870. botRight = docLTR && openEnd && last ? rightSide : toPos.right
  2871. } else {
  2872. topLeft = !docLTR ? leftSide : wrapX(from, dir, "before")
  2873. topRight = !docLTR && openStart && first ? rightSide : fromPos.right
  2874. botLeft = !docLTR && openEnd && last ? leftSide : toPos.left
  2875. botRight = !docLTR ? rightSide : wrapX(to, dir, "after")
  2876. }
  2877. add(topLeft, fromPos.top, topRight - topLeft, fromPos.bottom)
  2878. if (fromPos.bottom < toPos.top) { add(leftSide, fromPos.bottom, null, toPos.top) }
  2879. add(botLeft, toPos.top, botRight - botLeft, toPos.bottom)
  2880. }
  2881. if (!start || cmpCoords(fromPos, start) < 0) { start = fromPos }
  2882. if (cmpCoords(toPos, start) < 0) { start = toPos }
  2883. if (!end || cmpCoords(fromPos, end) < 0) { end = fromPos }
  2884. if (cmpCoords(toPos, end) < 0) { end = toPos }
  2885. })
  2886. return {start: start, end: end}
  2887. }
  2888. var sFrom = range.from(), sTo = range.to()
  2889. if (sFrom.line == sTo.line) {
  2890. drawForLine(sFrom.line, sFrom.ch, sTo.ch)
  2891. } else {
  2892. var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line)
  2893. var singleVLine = visualLine(fromLine) == visualLine(toLine)
  2894. var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end
  2895. var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start
  2896. if (singleVLine) {
  2897. if (leftEnd.top < rightStart.top - 2) {
  2898. add(leftEnd.right, leftEnd.top, null, leftEnd.bottom)
  2899. add(leftSide, rightStart.top, rightStart.left, rightStart.bottom)
  2900. } else {
  2901. add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom)
  2902. }
  2903. }
  2904. if (leftEnd.bottom < rightStart.top)
  2905. { add(leftSide, leftEnd.bottom, null, rightStart.top) }
  2906. }
  2907. output.appendChild(fragment)
  2908. }
  2909. // Cursor-blinking
  2910. function restartBlink(cm) {
  2911. if (!cm.state.focused) { return }
  2912. var display = cm.display
  2913. clearInterval(display.blinker)
  2914. var on = true
  2915. display.cursorDiv.style.visibility = ""
  2916. if (cm.options.cursorBlinkRate > 0)
  2917. { display.blinker = setInterval(function () { return display.cursorDiv.style.visibility = (on = !on) ? "" : "hidden"; },
  2918. cm.options.cursorBlinkRate) }
  2919. else if (cm.options.cursorBlinkRate < 0)
  2920. { display.cursorDiv.style.visibility = "hidden" }
  2921. }
  2922. function ensureFocus(cm) {
  2923. if (!cm.state.focused) { cm.display.input.focus(); onFocus(cm) }
  2924. }
  2925. function delayBlurEvent(cm) {
  2926. cm.state.delayingBlurEvent = true
  2927. setTimeout(function () { if (cm.state.delayingBlurEvent) {
  2928. cm.state.delayingBlurEvent = false
  2929. onBlur(cm)
  2930. } }, 100)
  2931. }
  2932. function onFocus(cm, e) {
  2933. if (cm.state.delayingBlurEvent) { cm.state.delayingBlurEvent = false }
  2934. if (cm.options.readOnly == "nocursor") { return }
  2935. if (!cm.state.focused) {
  2936. signal(cm, "focus", cm, e)
  2937. cm.state.focused = true
  2938. addClass(cm.display.wrapper, "CodeMirror-focused")
  2939. // This test prevents this from firing when a context
  2940. // menu is closed (since the input reset would kill the
  2941. // select-all detection hack)
  2942. if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) {
  2943. cm.display.input.reset()
  2944. if (webkit) { setTimeout(function () { return cm.display.input.reset(true); }, 20) } // Issue #1730
  2945. }
  2946. cm.display.input.receivedFocus()
  2947. }
  2948. restartBlink(cm)
  2949. }
  2950. function onBlur(cm, e) {
  2951. if (cm.state.delayingBlurEvent) { return }
  2952. if (cm.state.focused) {
  2953. signal(cm, "blur", cm, e)
  2954. cm.state.focused = false
  2955. rmClass(cm.display.wrapper, "CodeMirror-focused")
  2956. }
  2957. clearInterval(cm.display.blinker)
  2958. setTimeout(function () { if (!cm.state.focused) { cm.display.shift = false } }, 150)
  2959. }
  2960. // Read the actual heights of the rendered lines, and update their
  2961. // stored heights to match.
  2962. function updateHeightsInViewport(cm) {
  2963. var display = cm.display
  2964. var prevBottom = display.lineDiv.offsetTop
  2965. for (var i = 0; i < display.view.length; i++) {
  2966. var cur = display.view[i], height = (void 0)
  2967. if (cur.hidden) { continue }
  2968. if (ie && ie_version < 8) {
  2969. var bot = cur.node.offsetTop + cur.node.offsetHeight
  2970. height = bot - prevBottom
  2971. prevBottom = bot
  2972. } else {
  2973. var box = cur.node.getBoundingClientRect()
  2974. height = box.bottom - box.top
  2975. }
  2976. var diff = cur.line.height - height
  2977. if (height < 2) { height = textHeight(display) }
  2978. if (diff > .005 || diff < -.005) {
  2979. updateLineHeight(cur.line, height)
  2980. updateWidgetHeight(cur.line)
  2981. if (cur.rest) { for (var j = 0; j < cur.rest.length; j++)
  2982. { updateWidgetHeight(cur.rest[j]) } }
  2983. }
  2984. }
  2985. }
  2986. // Read and store the height of line widgets associated with the
  2987. // given line.
  2988. function updateWidgetHeight(line) {
  2989. if (line.widgets) { for (var i = 0; i < line.widgets.length; ++i) {
  2990. var w = line.widgets[i], parent = w.node.parentNode
  2991. if (parent) { w.height = parent.offsetHeight }
  2992. } }
  2993. }
  2994. // Compute the lines that are visible in a given viewport (defaults
  2995. // the the current scroll position). viewport may contain top,
  2996. // height, and ensure (see op.scrollToPos) properties.
  2997. function visibleLines(display, doc, viewport) {
  2998. var top = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop
  2999. top = Math.floor(top - paddingTop(display))
  3000. var bottom = viewport && viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight
  3001. var from = lineAtHeight(doc, top), to = lineAtHeight(doc, bottom)
  3002. // Ensure is a {from: {line, ch}, to: {line, ch}} object, and
  3003. // forces those lines into the viewport (if possible).
  3004. if (viewport && viewport.ensure) {
  3005. var ensureFrom = viewport.ensure.from.line, ensureTo = viewport.ensure.to.line
  3006. if (ensureFrom < from) {
  3007. from = ensureFrom
  3008. to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight)
  3009. } else if (Math.min(ensureTo, doc.lastLine()) >= to) {
  3010. from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight)
  3011. to = ensureTo
  3012. }
  3013. }
  3014. return {from: from, to: Math.max(to, from + 1)}
  3015. }
  3016. // Re-align line numbers and gutter marks to compensate for
  3017. // horizontal scrolling.
  3018. function alignHorizontally(cm) {
  3019. var display = cm.display, view = display.view
  3020. if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) { return }
  3021. var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft
  3022. var gutterW = display.gutters.offsetWidth, left = comp + "px"
  3023. for (var i = 0; i < view.length; i++) { if (!view[i].hidden) {
  3024. if (cm.options.fixedGutter) {
  3025. if (view[i].gutter)
  3026. { view[i].gutter.style.left = left }
  3027. if (view[i].gutterBackground)
  3028. { view[i].gutterBackground.style.left = left }
  3029. }
  3030. var align = view[i].alignable
  3031. if (align) { for (var j = 0; j < align.length; j++)
  3032. { align[j].style.left = left } }
  3033. } }
  3034. if (cm.options.fixedGutter)
  3035. { display.gutters.style.left = (comp + gutterW) + "px" }
  3036. }
  3037. // Used to ensure that the line number gutter is still the right
  3038. // size for the current document size. Returns true when an update
  3039. // is needed.
  3040. function maybeUpdateLineNumberWidth(cm) {
  3041. if (!cm.options.lineNumbers) { return false }
  3042. var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display
  3043. if (last.length != display.lineNumChars) {
  3044. var test = display.measure.appendChild(elt("div", [elt("div", last)],
  3045. "CodeMirror-linenumber CodeMirror-gutter-elt"))
  3046. var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW
  3047. display.lineGutter.style.width = ""
  3048. display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding) + 1
  3049. display.lineNumWidth = display.lineNumInnerWidth + padding
  3050. display.lineNumChars = display.lineNumInnerWidth ? last.length : -1
  3051. display.lineGutter.style.width = display.lineNumWidth + "px"
  3052. updateGutterSpace(cm)
  3053. return true
  3054. }
  3055. return false
  3056. }
  3057. // SCROLLING THINGS INTO VIEW
  3058. // If an editor sits on the top or bottom of the window, partially
  3059. // scrolled out of view, this ensures that the cursor is visible.
  3060. function maybeScrollWindow(cm, rect) {
  3061. if (signalDOMEvent(cm, "scrollCursorIntoView")) { return }
  3062. var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null
  3063. if (rect.top + box.top < 0) { doScroll = true }
  3064. else if (rect.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) { doScroll = false }
  3065. if (doScroll != null && !phantom) {
  3066. 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;"))
  3067. cm.display.lineSpace.appendChild(scrollNode)
  3068. scrollNode.scrollIntoView(doScroll)
  3069. cm.display.lineSpace.removeChild(scrollNode)
  3070. }
  3071. }
  3072. // Scroll a given position into view (immediately), verifying that
  3073. // it actually became visible (as line heights are accurately
  3074. // measured, the position of something may 'drift' during drawing).
  3075. function scrollPosIntoView(cm, pos, end, margin) {
  3076. if (margin == null) { margin = 0 }
  3077. var rect
  3078. if (!cm.options.lineWrapping && pos == end) {
  3079. // Set pos and end to the cursor positions around the character pos sticks to
  3080. // If pos.sticky == "before", that is around pos.ch - 1, otherwise around pos.ch
  3081. // If pos == Pos(_, 0, "before"), pos and end are unchanged
  3082. pos = pos.ch ? Pos(pos.line, pos.sticky == "before" ? pos.ch - 1 : pos.ch, "after") : pos
  3083. end = pos.sticky == "before" ? Pos(pos.line, pos.ch + 1, "before") : pos
  3084. }
  3085. for (var limit = 0; limit < 5; limit++) {
  3086. var changed = false
  3087. var coords = cursorCoords(cm, pos)
  3088. var endCoords = !end || end == pos ? coords : cursorCoords(cm, end)
  3089. rect = {left: Math.min(coords.left, endCoords.left),
  3090. top: Math.min(coords.top, endCoords.top) - margin,
  3091. right: Math.max(coords.left, endCoords.left),
  3092. bottom: Math.max(coords.bottom, endCoords.bottom) + margin}
  3093. var scrollPos = calculateScrollPos(cm, rect)
  3094. var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft
  3095. if (scrollPos.scrollTop != null) {
  3096. updateScrollTop(cm, scrollPos.scrollTop)
  3097. if (Math.abs(cm.doc.scrollTop - startTop) > 1) { changed = true }
  3098. }
  3099. if (scrollPos.scrollLeft != null) {
  3100. setScrollLeft(cm, scrollPos.scrollLeft)
  3101. if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) { changed = true }
  3102. }
  3103. if (!changed) { break }
  3104. }
  3105. return rect
  3106. }
  3107. // Scroll a given set of coordinates into view (immediately).
  3108. function scrollIntoView(cm, rect) {
  3109. var scrollPos = calculateScrollPos(cm, rect)
  3110. if (scrollPos.scrollTop != null) { updateScrollTop(cm, scrollPos.scrollTop) }
  3111. if (scrollPos.scrollLeft != null) { setScrollLeft(cm, scrollPos.scrollLeft) }
  3112. }
  3113. // Calculate a new scroll position needed to scroll the given
  3114. // rectangle into view. Returns an object with scrollTop and
  3115. // scrollLeft properties. When these are undefined, the
  3116. // vertical/horizontal position does not need to be adjusted.
  3117. function calculateScrollPos(cm, rect) {
  3118. var display = cm.display, snapMargin = textHeight(cm.display)
  3119. if (rect.top < 0) { rect.top = 0 }
  3120. var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop
  3121. var screen = displayHeight(cm), result = {}
  3122. if (rect.bottom - rect.top > screen) { rect.bottom = rect.top + screen }
  3123. var docBottom = cm.doc.height + paddingVert(display)
  3124. var atTop = rect.top < snapMargin, atBottom = rect.bottom > docBottom - snapMargin
  3125. if (rect.top < screentop) {
  3126. result.scrollTop = atTop ? 0 : rect.top
  3127. } else if (rect.bottom > screentop + screen) {
  3128. var newTop = Math.min(rect.top, (atBottom ? docBottom : rect.bottom) - screen)
  3129. if (newTop != screentop) { result.scrollTop = newTop }
  3130. }
  3131. var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft
  3132. var screenw = displayWidth(cm) - (cm.options.fixedGutter ? display.gutters.offsetWidth : 0)
  3133. var tooWide = rect.right - rect.left > screenw
  3134. if (tooWide) { rect.right = rect.left + screenw }
  3135. if (rect.left < 10)
  3136. { result.scrollLeft = 0 }
  3137. else if (rect.left < screenleft)
  3138. { result.scrollLeft = Math.max(0, rect.left - (tooWide ? 0 : 10)) }
  3139. else if (rect.right > screenw + screenleft - 3)
  3140. { result.scrollLeft = rect.right + (tooWide ? 0 : 10) - screenw }
  3141. return result
  3142. }
  3143. // Store a relative adjustment to the scroll position in the current
  3144. // operation (to be applied when the operation finishes).
  3145. function addToScrollTop(cm, top) {
  3146. if (top == null) { return }
  3147. resolveScrollToPos(cm)
  3148. cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top
  3149. }
  3150. // Make sure that at the end of the operation the current cursor is
  3151. // shown.
  3152. function ensureCursorVisible(cm) {
  3153. resolveScrollToPos(cm)
  3154. var cur = cm.getCursor()
  3155. cm.curOp.scrollToPos = {from: cur, to: cur, margin: cm.options.cursorScrollMargin}
  3156. }
  3157. function scrollToCoords(cm, x, y) {
  3158. if (x != null || y != null) { resolveScrollToPos(cm) }
  3159. if (x != null) { cm.curOp.scrollLeft = x }
  3160. if (y != null) { cm.curOp.scrollTop = y }
  3161. }
  3162. function scrollToRange(cm, range) {
  3163. resolveScrollToPos(cm)
  3164. cm.curOp.scrollToPos = range
  3165. }
  3166. // When an operation has its scrollToPos property set, and another
  3167. // scroll action is applied before the end of the operation, this
  3168. // 'simulates' scrolling that position into view in a cheap way, so
  3169. // that the effect of intermediate scroll commands is not ignored.
  3170. function resolveScrollToPos(cm) {
  3171. var range = cm.curOp.scrollToPos
  3172. if (range) {
  3173. cm.curOp.scrollToPos = null
  3174. var from = estimateCoords(cm, range.from), to = estimateCoords(cm, range.to)
  3175. scrollToCoordsRange(cm, from, to, range.margin)
  3176. }
  3177. }
  3178. function scrollToCoordsRange(cm, from, to, margin) {
  3179. var sPos = calculateScrollPos(cm, {
  3180. left: Math.min(from.left, to.left),
  3181. top: Math.min(from.top, to.top) - margin,
  3182. right: Math.max(from.right, to.right),
  3183. bottom: Math.max(from.bottom, to.bottom) + margin
  3184. })
  3185. scrollToCoords(cm, sPos.scrollLeft, sPos.scrollTop)
  3186. }
  3187. // Sync the scrollable area and scrollbars, ensure the viewport
  3188. // covers the visible area.
  3189. function updateScrollTop(cm, val) {
  3190. if (Math.abs(cm.doc.scrollTop - val) < 2) { return }
  3191. if (!gecko) { updateDisplaySimple(cm, {top: val}) }
  3192. setScrollTop(cm, val, true)
  3193. if (gecko) { updateDisplaySimple(cm) }
  3194. startWorker(cm, 100)
  3195. }
  3196. function setScrollTop(cm, val, forceScroll) {
  3197. val = Math.min(cm.display.scroller.scrollHeight - cm.display.scroller.clientHeight, val)
  3198. if (cm.display.scroller.scrollTop == val && !forceScroll) { return }
  3199. cm.doc.scrollTop = val
  3200. cm.display.scrollbars.setScrollTop(val)
  3201. if (cm.display.scroller.scrollTop != val) { cm.display.scroller.scrollTop = val }
  3202. }
  3203. // Sync scroller and scrollbar, ensure the gutter elements are
  3204. // aligned.
  3205. function setScrollLeft(cm, val, isScroller, forceScroll) {
  3206. val = Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth)
  3207. if ((isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) && !forceScroll) { return }
  3208. cm.doc.scrollLeft = val
  3209. alignHorizontally(cm)
  3210. if (cm.display.scroller.scrollLeft != val) { cm.display.scroller.scrollLeft = val }
  3211. cm.display.scrollbars.setScrollLeft(val)
  3212. }
  3213. // SCROLLBARS
  3214. // Prepare DOM reads needed to update the scrollbars. Done in one
  3215. // shot to minimize update/measure roundtrips.
  3216. function measureForScrollbars(cm) {
  3217. var d = cm.display, gutterW = d.gutters.offsetWidth
  3218. var docH = Math.round(cm.doc.height + paddingVert(cm.display))
  3219. return {
  3220. clientHeight: d.scroller.clientHeight,
  3221. viewHeight: d.wrapper.clientHeight,
  3222. scrollWidth: d.scroller.scrollWidth, clientWidth: d.scroller.clientWidth,
  3223. viewWidth: d.wrapper.clientWidth,
  3224. barLeft: cm.options.fixedGutter ? gutterW : 0,
  3225. docHeight: docH,
  3226. scrollHeight: docH + scrollGap(cm) + d.barHeight,
  3227. nativeBarWidth: d.nativeBarWidth,
  3228. gutterWidth: gutterW
  3229. }
  3230. }
  3231. var NativeScrollbars = function(place, scroll, cm) {
  3232. this.cm = cm
  3233. var vert = this.vert = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar")
  3234. var horiz = this.horiz = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar")
  3235. vert.tabIndex = horiz.tabIndex = -1
  3236. place(vert); place(horiz)
  3237. on(vert, "scroll", function () {
  3238. if (vert.clientHeight) { scroll(vert.scrollTop, "vertical") }
  3239. })
  3240. on(horiz, "scroll", function () {
  3241. if (horiz.clientWidth) { scroll(horiz.scrollLeft, "horizontal") }
  3242. })
  3243. this.checkedZeroWidth = false
  3244. // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8).
  3245. if (ie && ie_version < 8) { this.horiz.style.minHeight = this.vert.style.minWidth = "18px" }
  3246. };
  3247. NativeScrollbars.prototype.update = function (measure) {
  3248. var needsH = measure.scrollWidth > measure.clientWidth + 1
  3249. var needsV = measure.scrollHeight > measure.clientHeight + 1
  3250. var sWidth = measure.nativeBarWidth
  3251. if (needsV) {
  3252. this.vert.style.display = "block"
  3253. this.vert.style.bottom = needsH ? sWidth + "px" : "0"
  3254. var totalHeight = measure.viewHeight - (needsH ? sWidth : 0)
  3255. // A bug in IE8 can cause this value to be negative, so guard it.
  3256. this.vert.firstChild.style.height =
  3257. Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + "px"
  3258. } else {
  3259. this.vert.style.display = ""
  3260. this.vert.firstChild.style.height = "0"
  3261. }
  3262. if (needsH) {
  3263. this.horiz.style.display = "block"
  3264. this.horiz.style.right = needsV ? sWidth + "px" : "0"
  3265. this.horiz.style.left = measure.barLeft + "px"
  3266. var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0)
  3267. this.horiz.firstChild.style.width =
  3268. Math.max(0, measure.scrollWidth - measure.clientWidth + totalWidth) + "px"
  3269. } else {
  3270. this.horiz.style.display = ""
  3271. this.horiz.firstChild.style.width = "0"
  3272. }
  3273. if (!this.checkedZeroWidth && measure.clientHeight > 0) {
  3274. if (sWidth == 0) { this.zeroWidthHack() }
  3275. this.checkedZeroWidth = true
  3276. }
  3277. return {right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0}
  3278. };
  3279. NativeScrollbars.prototype.setScrollLeft = function (pos) {
  3280. if (this.horiz.scrollLeft != pos) { this.horiz.scrollLeft = pos }
  3281. if (this.disableHoriz) { this.enableZeroWidthBar(this.horiz, this.disableHoriz, "horiz") }
  3282. };
  3283. NativeScrollbars.prototype.setScrollTop = function (pos) {
  3284. if (this.vert.scrollTop != pos) { this.vert.scrollTop = pos }
  3285. if (this.disableVert) { this.enableZeroWidthBar(this.vert, this.disableVert, "vert") }
  3286. };
  3287. NativeScrollbars.prototype.zeroWidthHack = function () {
  3288. var w = mac && !mac_geMountainLion ? "12px" : "18px"
  3289. this.horiz.style.height = this.vert.style.width = w
  3290. this.horiz.style.pointerEvents = this.vert.style.pointerEvents = "none"
  3291. this.disableHoriz = new Delayed
  3292. this.disableVert = new Delayed
  3293. };
  3294. NativeScrollbars.prototype.enableZeroWidthBar = function (bar, delay, type) {
  3295. bar.style.pointerEvents = "auto"
  3296. function maybeDisable() {
  3297. // To find out whether the scrollbar is still visible, we
  3298. // check whether the element under the pixel in the bottom
  3299. // right corner of the scrollbar box is the scrollbar box
  3300. // itself (when the bar is still visible) or its filler child
  3301. // (when the bar is hidden). If it is still visible, we keep
  3302. // it enabled, if it's hidden, we disable pointer events.
  3303. var box = bar.getBoundingClientRect()
  3304. var elt = type == "vert" ? document.elementFromPoint(box.right - 1, (box.top + box.bottom) / 2)
  3305. : document.elementFromPoint((box.right + box.left) / 2, box.bottom - 1)
  3306. if (elt != bar) { bar.style.pointerEvents = "none" }
  3307. else { delay.set(1000, maybeDisable) }
  3308. }
  3309. delay.set(1000, maybeDisable)
  3310. };
  3311. NativeScrollbars.prototype.clear = function () {
  3312. var parent = this.horiz.parentNode
  3313. parent.removeChild(this.horiz)
  3314. parent.removeChild(this.vert)
  3315. };
  3316. var NullScrollbars = function () {};
  3317. NullScrollbars.prototype.update = function () { return {bottom: 0, right: 0} };
  3318. NullScrollbars.prototype.setScrollLeft = function () {};
  3319. NullScrollbars.prototype.setScrollTop = function () {};
  3320. NullScrollbars.prototype.clear = function () {};
  3321. function updateScrollbars(cm, measure) {
  3322. if (!measure) { measure = measureForScrollbars(cm) }
  3323. var startWidth = cm.display.barWidth, startHeight = cm.display.barHeight
  3324. updateScrollbarsInner(cm, measure)
  3325. for (var i = 0; i < 4 && startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i++) {
  3326. if (startWidth != cm.display.barWidth && cm.options.lineWrapping)
  3327. { updateHeightsInViewport(cm) }
  3328. updateScrollbarsInner(cm, measureForScrollbars(cm))
  3329. startWidth = cm.display.barWidth; startHeight = cm.display.barHeight
  3330. }
  3331. }
  3332. // Re-synchronize the fake scrollbars with the actual size of the
  3333. // content.
  3334. function updateScrollbarsInner(cm, measure) {
  3335. var d = cm.display
  3336. var sizes = d.scrollbars.update(measure)
  3337. d.sizer.style.paddingRight = (d.barWidth = sizes.right) + "px"
  3338. d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + "px"
  3339. d.heightForcer.style.borderBottom = sizes.bottom + "px solid transparent"
  3340. if (sizes.right && sizes.bottom) {
  3341. d.scrollbarFiller.style.display = "block"
  3342. d.scrollbarFiller.style.height = sizes.bottom + "px"
  3343. d.scrollbarFiller.style.width = sizes.right + "px"
  3344. } else { d.scrollbarFiller.style.display = "" }
  3345. if (sizes.bottom && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) {
  3346. d.gutterFiller.style.display = "block"
  3347. d.gutterFiller.style.height = sizes.bottom + "px"
  3348. d.gutterFiller.style.width = measure.gutterWidth + "px"
  3349. } else { d.gutterFiller.style.display = "" }
  3350. }
  3351. var scrollbarModel = {"native": NativeScrollbars, "null": NullScrollbars}
  3352. function initScrollbars(cm) {
  3353. if (cm.display.scrollbars) {
  3354. cm.display.scrollbars.clear()
  3355. if (cm.display.scrollbars.addClass)
  3356. { rmClass(cm.display.wrapper, cm.display.scrollbars.addClass) }
  3357. }
  3358. cm.display.scrollbars = new scrollbarModel[cm.options.scrollbarStyle](function (node) {
  3359. cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller)
  3360. // Prevent clicks in the scrollbars from killing focus
  3361. on(node, "mousedown", function () {
  3362. if (cm.state.focused) { setTimeout(function () { return cm.display.input.focus(); }, 0) }
  3363. })
  3364. node.setAttribute("cm-not-content", "true")
  3365. }, function (pos, axis) {
  3366. if (axis == "horizontal") { setScrollLeft(cm, pos) }
  3367. else { updateScrollTop(cm, pos) }
  3368. }, cm)
  3369. if (cm.display.scrollbars.addClass)
  3370. { addClass(cm.display.wrapper, cm.display.scrollbars.addClass) }
  3371. }
  3372. // Operations are used to wrap a series of changes to the editor
  3373. // state in such a way that each change won't have to update the
  3374. // cursor and display (which would be awkward, slow, and
  3375. // error-prone). Instead, display updates are batched and then all
  3376. // combined and executed at once.
  3377. var nextOpId = 0
  3378. // Start a new operation.
  3379. function startOperation(cm) {
  3380. cm.curOp = {
  3381. cm: cm,
  3382. viewChanged: false, // Flag that indicates that lines might need to be redrawn
  3383. startHeight: cm.doc.height, // Used to detect need to update scrollbar
  3384. forceUpdate: false, // Used to force a redraw
  3385. updateInput: null, // Whether to reset the input textarea
  3386. typing: false, // Whether this reset should be careful to leave existing text (for compositing)
  3387. changeObjs: null, // Accumulated changes, for firing change events
  3388. cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on
  3389. cursorActivityCalled: 0, // Tracks which cursorActivity handlers have been called already
  3390. selectionChanged: false, // Whether the selection needs to be redrawn
  3391. updateMaxLine: false, // Set when the widest line needs to be determined anew
  3392. scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet
  3393. scrollToPos: null, // Used to scroll to a specific position
  3394. focus: false,
  3395. id: ++nextOpId // Unique ID
  3396. }
  3397. pushOperation(cm.curOp)
  3398. }
  3399. // Finish an operation, updating the display and signalling delayed events
  3400. function endOperation(cm) {
  3401. var op = cm.curOp
  3402. finishOperation(op, function (group) {
  3403. for (var i = 0; i < group.ops.length; i++)
  3404. { group.ops[i].cm.curOp = null }
  3405. endOperations(group)
  3406. })
  3407. }
  3408. // The DOM updates done when an operation finishes are batched so
  3409. // that the minimum number of relayouts are required.
  3410. function endOperations(group) {
  3411. var ops = group.ops
  3412. for (var i = 0; i < ops.length; i++) // Read DOM
  3413. { endOperation_R1(ops[i]) }
  3414. for (var i$1 = 0; i$1 < ops.length; i$1++) // Write DOM (maybe)
  3415. { endOperation_W1(ops[i$1]) }
  3416. for (var i$2 = 0; i$2 < ops.length; i$2++) // Read DOM
  3417. { endOperation_R2(ops[i$2]) }
  3418. for (var i$3 = 0; i$3 < ops.length; i$3++) // Write DOM (maybe)
  3419. { endOperation_W2(ops[i$3]) }
  3420. for (var i$4 = 0; i$4 < ops.length; i$4++) // Read DOM
  3421. { endOperation_finish(ops[i$4]) }
  3422. }
  3423. function endOperation_R1(op) {
  3424. var cm = op.cm, display = cm.display
  3425. maybeClipScrollbars(cm)
  3426. if (op.updateMaxLine) { findMaxLine(cm) }
  3427. op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null ||
  3428. op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom ||
  3429. op.scrollToPos.to.line >= display.viewTo) ||
  3430. display.maxLineChanged && cm.options.lineWrapping
  3431. op.update = op.mustUpdate &&
  3432. new DisplayUpdate(cm, op.mustUpdate && {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate)
  3433. }
  3434. function endOperation_W1(op) {
  3435. op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update)
  3436. }
  3437. function endOperation_R2(op) {
  3438. var cm = op.cm, display = cm.display
  3439. if (op.updatedDisplay) { updateHeightsInViewport(cm) }
  3440. op.barMeasure = measureForScrollbars(cm)
  3441. // If the max line changed since it was last measured, measure it,
  3442. // and ensure the document's width matches it.
  3443. // updateDisplay_W2 will use these properties to do the actual resizing
  3444. if (display.maxLineChanged && !cm.options.lineWrapping) {
  3445. op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3
  3446. cm.display.sizerWidth = op.adjustWidthTo
  3447. op.barMeasure.scrollWidth =
  3448. Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth)
  3449. op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm))
  3450. }
  3451. if (op.updatedDisplay || op.selectionChanged)
  3452. { op.preparedSelection = display.input.prepareSelection() }
  3453. }
  3454. function endOperation_W2(op) {
  3455. var cm = op.cm
  3456. if (op.adjustWidthTo != null) {
  3457. cm.display.sizer.style.minWidth = op.adjustWidthTo + "px"
  3458. if (op.maxScrollLeft < cm.doc.scrollLeft)
  3459. { setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true) }
  3460. cm.display.maxLineChanged = false
  3461. }
  3462. var takeFocus = op.focus && op.focus == activeElt()
  3463. if (op.preparedSelection)
  3464. { cm.display.input.showSelection(op.preparedSelection, takeFocus) }
  3465. if (op.updatedDisplay || op.startHeight != cm.doc.height)
  3466. { updateScrollbars(cm, op.barMeasure) }
  3467. if (op.updatedDisplay)
  3468. { setDocumentHeight(cm, op.barMeasure) }
  3469. if (op.selectionChanged) { restartBlink(cm) }
  3470. if (cm.state.focused && op.updateInput)
  3471. { cm.display.input.reset(op.typing) }
  3472. if (takeFocus) { ensureFocus(op.cm) }
  3473. }
  3474. function endOperation_finish(op) {
  3475. var cm = op.cm, display = cm.display, doc = cm.doc
  3476. if (op.updatedDisplay) { postUpdateDisplay(cm, op.update) }
  3477. // Abort mouse wheel delta measurement, when scrolling explicitly
  3478. if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos))
  3479. { display.wheelStartX = display.wheelStartY = null }
  3480. // Propagate the scroll position to the actual DOM scroller
  3481. if (op.scrollTop != null) { setScrollTop(cm, op.scrollTop, op.forceScroll) }
  3482. if (op.scrollLeft != null) { setScrollLeft(cm, op.scrollLeft, true, true) }
  3483. // If we need to scroll a specific position into view, do so.
  3484. if (op.scrollToPos) {
  3485. var rect = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from),
  3486. clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin)
  3487. maybeScrollWindow(cm, rect)
  3488. }
  3489. // Fire events for markers that are hidden/unidden by editing or
  3490. // undoing
  3491. var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers
  3492. if (hidden) { for (var i = 0; i < hidden.length; ++i)
  3493. { if (!hidden[i].lines.length) { signal(hidden[i], "hide") } } }
  3494. if (unhidden) { for (var i$1 = 0; i$1 < unhidden.length; ++i$1)
  3495. { if (unhidden[i$1].lines.length) { signal(unhidden[i$1], "unhide") } } }
  3496. if (display.wrapper.offsetHeight)
  3497. { doc.scrollTop = cm.display.scroller.scrollTop }
  3498. // Fire change events, and delayed event handlers
  3499. if (op.changeObjs)
  3500. { signal(cm, "changes", cm, op.changeObjs) }
  3501. if (op.update)
  3502. { op.update.finish() }
  3503. }
  3504. // Run the given function in an operation
  3505. function runInOp(cm, f) {
  3506. if (cm.curOp) { return f() }
  3507. startOperation(cm)
  3508. try { return f() }
  3509. finally { endOperation(cm) }
  3510. }
  3511. // Wraps a function in an operation. Returns the wrapped function.
  3512. function operation(cm, f) {
  3513. return function() {
  3514. if (cm.curOp) { return f.apply(cm, arguments) }
  3515. startOperation(cm)
  3516. try { return f.apply(cm, arguments) }
  3517. finally { endOperation(cm) }
  3518. }
  3519. }
  3520. // Used to add methods to editor and doc instances, wrapping them in
  3521. // operations.
  3522. function methodOp(f) {
  3523. return function() {
  3524. if (this.curOp) { return f.apply(this, arguments) }
  3525. startOperation(this)
  3526. try { return f.apply(this, arguments) }
  3527. finally { endOperation(this) }
  3528. }
  3529. }
  3530. function docMethodOp(f) {
  3531. return function() {
  3532. var cm = this.cm
  3533. if (!cm || cm.curOp) { return f.apply(this, arguments) }
  3534. startOperation(cm)
  3535. try { return f.apply(this, arguments) }
  3536. finally { endOperation(cm) }
  3537. }
  3538. }
  3539. // Updates the display.view data structure for a given change to the
  3540. // document. From and to are in pre-change coordinates. Lendiff is
  3541. // the amount of lines added or subtracted by the change. This is
  3542. // used for changes that span multiple lines, or change the way
  3543. // lines are divided into visual lines. regLineChange (below)
  3544. // registers single-line changes.
  3545. function regChange(cm, from, to, lendiff) {
  3546. if (from == null) { from = cm.doc.first }
  3547. if (to == null) { to = cm.doc.first + cm.doc.size }
  3548. if (!lendiff) { lendiff = 0 }
  3549. var display = cm.display
  3550. if (lendiff && to < display.viewTo &&
  3551. (display.updateLineNumbers == null || display.updateLineNumbers > from))
  3552. { display.updateLineNumbers = from }
  3553. cm.curOp.viewChanged = true
  3554. if (from >= display.viewTo) { // Change after
  3555. if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo)
  3556. { resetView(cm) }
  3557. } else if (to <= display.viewFrom) { // Change before
  3558. if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) {
  3559. resetView(cm)
  3560. } else {
  3561. display.viewFrom += lendiff
  3562. display.viewTo += lendiff
  3563. }
  3564. } else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap
  3565. resetView(cm)
  3566. } else if (from <= display.viewFrom) { // Top overlap
  3567. var cut = viewCuttingPoint(cm, to, to + lendiff, 1)
  3568. if (cut) {
  3569. display.view = display.view.slice(cut.index)
  3570. display.viewFrom = cut.lineN
  3571. display.viewTo += lendiff
  3572. } else {
  3573. resetView(cm)
  3574. }
  3575. } else if (to >= display.viewTo) { // Bottom overlap
  3576. var cut$1 = viewCuttingPoint(cm, from, from, -1)
  3577. if (cut$1) {
  3578. display.view = display.view.slice(0, cut$1.index)
  3579. display.viewTo = cut$1.lineN
  3580. } else {
  3581. resetView(cm)
  3582. }
  3583. } else { // Gap in the middle
  3584. var cutTop = viewCuttingPoint(cm, from, from, -1)
  3585. var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1)
  3586. if (cutTop && cutBot) {
  3587. display.view = display.view.slice(0, cutTop.index)
  3588. .concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN))
  3589. .concat(display.view.slice(cutBot.index))
  3590. display.viewTo += lendiff
  3591. } else {
  3592. resetView(cm)
  3593. }
  3594. }
  3595. var ext = display.externalMeasured
  3596. if (ext) {
  3597. if (to < ext.lineN)
  3598. { ext.lineN += lendiff }
  3599. else if (from < ext.lineN + ext.size)
  3600. { display.externalMeasured = null }
  3601. }
  3602. }
  3603. // Register a change to a single line. Type must be one of "text",
  3604. // "gutter", "class", "widget"
  3605. function regLineChange(cm, line, type) {
  3606. cm.curOp.viewChanged = true
  3607. var display = cm.display, ext = cm.display.externalMeasured
  3608. if (ext && line >= ext.lineN && line < ext.lineN + ext.size)
  3609. { display.externalMeasured = null }
  3610. if (line < display.viewFrom || line >= display.viewTo) { return }
  3611. var lineView = display.view[findViewIndex(cm, line)]
  3612. if (lineView.node == null) { return }
  3613. var arr = lineView.changes || (lineView.changes = [])
  3614. if (indexOf(arr, type) == -1) { arr.push(type) }
  3615. }
  3616. // Clear the view.
  3617. function resetView(cm) {
  3618. cm.display.viewFrom = cm.display.viewTo = cm.doc.first
  3619. cm.display.view = []
  3620. cm.display.viewOffset = 0
  3621. }
  3622. function viewCuttingPoint(cm, oldN, newN, dir) {
  3623. var index = findViewIndex(cm, oldN), diff, view = cm.display.view
  3624. if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size)
  3625. { return {index: index, lineN: newN} }
  3626. var n = cm.display.viewFrom
  3627. for (var i = 0; i < index; i++)
  3628. { n += view[i].size }
  3629. if (n != oldN) {
  3630. if (dir > 0) {
  3631. if (index == view.length - 1) { return null }
  3632. diff = (n + view[index].size) - oldN
  3633. index++
  3634. } else {
  3635. diff = n - oldN
  3636. }
  3637. oldN += diff; newN += diff
  3638. }
  3639. while (visualLineNo(cm.doc, newN) != newN) {
  3640. if (index == (dir < 0 ? 0 : view.length - 1)) { return null }
  3641. newN += dir * view[index - (dir < 0 ? 1 : 0)].size
  3642. index += dir
  3643. }
  3644. return {index: index, lineN: newN}
  3645. }
  3646. // Force the view to cover a given range, adding empty view element
  3647. // or clipping off existing ones as needed.
  3648. function adjustView(cm, from, to) {
  3649. var display = cm.display, view = display.view
  3650. if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) {
  3651. display.view = buildViewArray(cm, from, to)
  3652. display.viewFrom = from
  3653. } else {
  3654. if (display.viewFrom > from)
  3655. { display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view) }
  3656. else if (display.viewFrom < from)
  3657. { display.view = display.view.slice(findViewIndex(cm, from)) }
  3658. display.viewFrom = from
  3659. if (display.viewTo < to)
  3660. { display.view = display.view.concat(buildViewArray(cm, display.viewTo, to)) }
  3661. else if (display.viewTo > to)
  3662. { display.view = display.view.slice(0, findViewIndex(cm, to)) }
  3663. }
  3664. display.viewTo = to
  3665. }
  3666. // Count the number of lines in the view whose DOM representation is
  3667. // out of date (or nonexistent).
  3668. function countDirtyView(cm) {
  3669. var view = cm.display.view, dirty = 0
  3670. for (var i = 0; i < view.length; i++) {
  3671. var lineView = view[i]
  3672. if (!lineView.hidden && (!lineView.node || lineView.changes)) { ++dirty }
  3673. }
  3674. return dirty
  3675. }
  3676. // HIGHLIGHT WORKER
  3677. function startWorker(cm, time) {
  3678. if (cm.doc.highlightFrontier < cm.display.viewTo)
  3679. { cm.state.highlight.set(time, bind(highlightWorker, cm)) }
  3680. }
  3681. function highlightWorker(cm) {
  3682. var doc = cm.doc
  3683. if (doc.highlightFrontier >= cm.display.viewTo) { return }
  3684. var end = +new Date + cm.options.workTime
  3685. var context = getContextBefore(cm, doc.highlightFrontier)
  3686. var changedLines = []
  3687. doc.iter(context.line, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function (line) {
  3688. if (context.line >= cm.display.viewFrom) { // Visible
  3689. var oldStyles = line.styles
  3690. var resetState = line.text.length > cm.options.maxHighlightLength ? copyState(doc.mode, context.state) : null
  3691. var highlighted = highlightLine(cm, line, context, true)
  3692. if (resetState) { context.state = resetState }
  3693. line.styles = highlighted.styles
  3694. var oldCls = line.styleClasses, newCls = highlighted.classes
  3695. if (newCls) { line.styleClasses = newCls }
  3696. else if (oldCls) { line.styleClasses = null }
  3697. var ischange = !oldStyles || oldStyles.length != line.styles.length ||
  3698. oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass)
  3699. for (var i = 0; !ischange && i < oldStyles.length; ++i) { ischange = oldStyles[i] != line.styles[i] }
  3700. if (ischange) { changedLines.push(context.line) }
  3701. line.stateAfter = context.save()
  3702. context.nextLine()
  3703. } else {
  3704. if (line.text.length <= cm.options.maxHighlightLength)
  3705. { processLine(cm, line.text, context) }
  3706. line.stateAfter = context.line % 5 == 0 ? context.save() : null
  3707. context.nextLine()
  3708. }
  3709. if (+new Date > end) {
  3710. startWorker(cm, cm.options.workDelay)
  3711. return true
  3712. }
  3713. })
  3714. doc.highlightFrontier = context.line
  3715. doc.modeFrontier = Math.max(doc.modeFrontier, context.line)
  3716. if (changedLines.length) { runInOp(cm, function () {
  3717. for (var i = 0; i < changedLines.length; i++)
  3718. { regLineChange(cm, changedLines[i], "text") }
  3719. }) }
  3720. }
  3721. // DISPLAY DRAWING
  3722. var DisplayUpdate = function(cm, viewport, force) {
  3723. var display = cm.display
  3724. this.viewport = viewport
  3725. // Store some values that we'll need later (but don't want to force a relayout for)
  3726. this.visible = visibleLines(display, cm.doc, viewport)
  3727. this.editorIsHidden = !display.wrapper.offsetWidth
  3728. this.wrapperHeight = display.wrapper.clientHeight
  3729. this.wrapperWidth = display.wrapper.clientWidth
  3730. this.oldDisplayWidth = displayWidth(cm)
  3731. this.force = force
  3732. this.dims = getDimensions(cm)
  3733. this.events = []
  3734. };
  3735. DisplayUpdate.prototype.signal = function (emitter, type) {
  3736. if (hasHandler(emitter, type))
  3737. { this.events.push(arguments) }
  3738. };
  3739. DisplayUpdate.prototype.finish = function () {
  3740. var this$1 = this;
  3741. for (var i = 0; i < this.events.length; i++)
  3742. { signal.apply(null, this$1.events[i]) }
  3743. };
  3744. function maybeClipScrollbars(cm) {
  3745. var display = cm.display
  3746. if (!display.scrollbarsClipped && display.scroller.offsetWidth) {
  3747. display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth
  3748. display.heightForcer.style.height = scrollGap(cm) + "px"
  3749. display.sizer.style.marginBottom = -display.nativeBarWidth + "px"
  3750. display.sizer.style.borderRightWidth = scrollGap(cm) + "px"
  3751. display.scrollbarsClipped = true
  3752. }
  3753. }
  3754. function selectionSnapshot(cm) {
  3755. if (cm.hasFocus()) { return null }
  3756. var active = activeElt()
  3757. if (!active || !contains(cm.display.lineDiv, active)) { return null }
  3758. var result = {activeElt: active}
  3759. if (window.getSelection) {
  3760. var sel = window.getSelection()
  3761. if (sel.anchorNode && sel.extend && contains(cm.display.lineDiv, sel.anchorNode)) {
  3762. result.anchorNode = sel.anchorNode
  3763. result.anchorOffset = sel.anchorOffset
  3764. result.focusNode = sel.focusNode
  3765. result.focusOffset = sel.focusOffset
  3766. }
  3767. }
  3768. return result
  3769. }
  3770. function restoreSelection(snapshot) {
  3771. if (!snapshot || !snapshot.activeElt || snapshot.activeElt == activeElt()) { return }
  3772. snapshot.activeElt.focus()
  3773. if (snapshot.anchorNode && contains(document.body, snapshot.anchorNode) && contains(document.body, snapshot.focusNode)) {
  3774. var sel = window.getSelection(), range = document.createRange()
  3775. range.setEnd(snapshot.anchorNode, snapshot.anchorOffset)
  3776. range.collapse(false)
  3777. sel.removeAllRanges()
  3778. sel.addRange(range)
  3779. sel.extend(snapshot.focusNode, snapshot.focusOffset)
  3780. }
  3781. }
  3782. // Does the actual updating of the line display. Bails out
  3783. // (returning false) when there is nothing to be done and forced is
  3784. // false.
  3785. function updateDisplayIfNeeded(cm, update) {
  3786. var display = cm.display, doc = cm.doc
  3787. if (update.editorIsHidden) {
  3788. resetView(cm)
  3789. return false
  3790. }
  3791. // Bail out if the visible area is already rendered and nothing changed.
  3792. if (!update.force &&
  3793. update.visible.from >= display.viewFrom && update.visible.to <= display.viewTo &&
  3794. (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) &&
  3795. display.renderedView == display.view && countDirtyView(cm) == 0)
  3796. { return false }
  3797. if (maybeUpdateLineNumberWidth(cm)) {
  3798. resetView(cm)
  3799. update.dims = getDimensions(cm)
  3800. }
  3801. // Compute a suitable new viewport (from & to)
  3802. var end = doc.first + doc.size
  3803. var from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first)
  3804. var to = Math.min(end, update.visible.to + cm.options.viewportMargin)
  3805. if (display.viewFrom < from && from - display.viewFrom < 20) { from = Math.max(doc.first, display.viewFrom) }
  3806. if (display.viewTo > to && display.viewTo - to < 20) { to = Math.min(end, display.viewTo) }
  3807. if (sawCollapsedSpans) {
  3808. from = visualLineNo(cm.doc, from)
  3809. to = visualLineEndNo(cm.doc, to)
  3810. }
  3811. var different = from != display.viewFrom || to != display.viewTo ||
  3812. display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth
  3813. adjustView(cm, from, to)
  3814. display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom))
  3815. // Position the mover div to align with the current scroll position
  3816. cm.display.mover.style.top = display.viewOffset + "px"
  3817. var toUpdate = countDirtyView(cm)
  3818. if (!different && toUpdate == 0 && !update.force && display.renderedView == display.view &&
  3819. (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo))
  3820. { return false }
  3821. // For big changes, we hide the enclosing element during the
  3822. // update, since that speeds up the operations on most browsers.
  3823. var selSnapshot = selectionSnapshot(cm)
  3824. if (toUpdate > 4) { display.lineDiv.style.display = "none" }
  3825. patchDisplay(cm, display.updateLineNumbers, update.dims)
  3826. if (toUpdate > 4) { display.lineDiv.style.display = "" }
  3827. display.renderedView = display.view
  3828. // There might have been a widget with a focused element that got
  3829. // hidden or updated, if so re-focus it.
  3830. restoreSelection(selSnapshot)
  3831. // Prevent selection and cursors from interfering with the scroll
  3832. // width and height.
  3833. removeChildren(display.cursorDiv)
  3834. removeChildren(display.selectionDiv)
  3835. display.gutters.style.height = display.sizer.style.minHeight = 0
  3836. if (different) {
  3837. display.lastWrapHeight = update.wrapperHeight
  3838. display.lastWrapWidth = update.wrapperWidth
  3839. startWorker(cm, 400)
  3840. }
  3841. display.updateLineNumbers = null
  3842. return true
  3843. }
  3844. function postUpdateDisplay(cm, update) {
  3845. var viewport = update.viewport
  3846. for (var first = true;; first = false) {
  3847. if (!first || !cm.options.lineWrapping || update.oldDisplayWidth == displayWidth(cm)) {
  3848. // Clip forced viewport to actual scrollable area.
  3849. if (viewport && viewport.top != null)
  3850. { viewport = {top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top)} }
  3851. // Updated line heights might result in the drawn area not
  3852. // actually covering the viewport. Keep looping until it does.
  3853. update.visible = visibleLines(cm.display, cm.doc, viewport)
  3854. if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo)
  3855. { break }
  3856. }
  3857. if (!updateDisplayIfNeeded(cm, update)) { break }
  3858. updateHeightsInViewport(cm)
  3859. var barMeasure = measureForScrollbars(cm)
  3860. updateSelection(cm)
  3861. updateScrollbars(cm, barMeasure)
  3862. setDocumentHeight(cm, barMeasure)
  3863. update.force = false
  3864. }
  3865. update.signal(cm, "update", cm)
  3866. if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) {
  3867. update.signal(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo)
  3868. cm.display.reportedViewFrom = cm.display.viewFrom; cm.display.reportedViewTo = cm.display.viewTo
  3869. }
  3870. }
  3871. function updateDisplaySimple(cm, viewport) {
  3872. var update = new DisplayUpdate(cm, viewport)
  3873. if (updateDisplayIfNeeded(cm, update)) {
  3874. updateHeightsInViewport(cm)
  3875. postUpdateDisplay(cm, update)
  3876. var barMeasure = measureForScrollbars(cm)
  3877. updateSelection(cm)
  3878. updateScrollbars(cm, barMeasure)
  3879. setDocumentHeight(cm, barMeasure)
  3880. update.finish()
  3881. }
  3882. }
  3883. // Sync the actual display DOM structure with display.view, removing
  3884. // nodes for lines that are no longer in view, and creating the ones
  3885. // that are not there yet, and updating the ones that are out of
  3886. // date.
  3887. function patchDisplay(cm, updateNumbersFrom, dims) {
  3888. var display = cm.display, lineNumbers = cm.options.lineNumbers
  3889. var container = display.lineDiv, cur = container.firstChild
  3890. function rm(node) {
  3891. var next = node.nextSibling
  3892. // Works around a throw-scroll bug in OS X Webkit
  3893. if (webkit && mac && cm.display.currentWheelTarget == node)
  3894. { node.style.display = "none" }
  3895. else
  3896. { node.parentNode.removeChild(node) }
  3897. return next
  3898. }
  3899. var view = display.view, lineN = display.viewFrom
  3900. // Loop over the elements in the view, syncing cur (the DOM nodes
  3901. // in display.lineDiv) with the view as we go.
  3902. for (var i = 0; i < view.length; i++) {
  3903. var lineView = view[i]
  3904. if (lineView.hidden) {
  3905. } else if (!lineView.node || lineView.node.parentNode != container) { // Not drawn yet
  3906. var node = buildLineElement(cm, lineView, lineN, dims)
  3907. container.insertBefore(node, cur)
  3908. } else { // Already drawn
  3909. while (cur != lineView.node) { cur = rm(cur) }
  3910. var updateNumber = lineNumbers && updateNumbersFrom != null &&
  3911. updateNumbersFrom <= lineN && lineView.lineNumber
  3912. if (lineView.changes) {
  3913. if (indexOf(lineView.changes, "gutter") > -1) { updateNumber = false }
  3914. updateLineForChanges(cm, lineView, lineN, dims)
  3915. }
  3916. if (updateNumber) {
  3917. removeChildren(lineView.lineNumber)
  3918. lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN)))
  3919. }
  3920. cur = lineView.node.nextSibling
  3921. }
  3922. lineN += lineView.size
  3923. }
  3924. while (cur) { cur = rm(cur) }
  3925. }
  3926. function updateGutterSpace(cm) {
  3927. var width = cm.display.gutters.offsetWidth
  3928. cm.display.sizer.style.marginLeft = width + "px"
  3929. }
  3930. function setDocumentHeight(cm, measure) {
  3931. cm.display.sizer.style.minHeight = measure.docHeight + "px"
  3932. cm.display.heightForcer.style.top = measure.docHeight + "px"
  3933. cm.display.gutters.style.height = (measure.docHeight + cm.display.barHeight + scrollGap(cm)) + "px"
  3934. }
  3935. // Rebuild the gutter elements, ensure the margin to the left of the
  3936. // code matches their width.
  3937. function updateGutters(cm) {
  3938. var gutters = cm.display.gutters, specs = cm.options.gutters
  3939. removeChildren(gutters)
  3940. var i = 0
  3941. for (; i < specs.length; ++i) {
  3942. var gutterClass = specs[i]
  3943. var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + gutterClass))
  3944. if (gutterClass == "CodeMirror-linenumbers") {
  3945. cm.display.lineGutter = gElt
  3946. gElt.style.width = (cm.display.lineNumWidth || 1) + "px"
  3947. }
  3948. }
  3949. gutters.style.display = i ? "" : "none"
  3950. updateGutterSpace(cm)
  3951. }
  3952. // Make sure the gutters options contains the element
  3953. // "CodeMirror-linenumbers" when the lineNumbers option is true.
  3954. function setGuttersForLineNumbers(options) {
  3955. var found = indexOf(options.gutters, "CodeMirror-linenumbers")
  3956. if (found == -1 && options.lineNumbers) {
  3957. options.gutters = options.gutters.concat(["CodeMirror-linenumbers"])
  3958. } else if (found > -1 && !options.lineNumbers) {
  3959. options.gutters = options.gutters.slice(0)
  3960. options.gutters.splice(found, 1)
  3961. }
  3962. }
  3963. var wheelSamples = 0;
  3964. var wheelPixelsPerUnit = null;
  3965. // Fill in a browser-detected starting value on browsers where we
  3966. // know one. These don't have to be accurate -- the result of them
  3967. // being wrong would just be a slight flicker on the first wheel
  3968. // scroll (if it is large enough).
  3969. if (ie) { wheelPixelsPerUnit = -.53 }
  3970. else if (gecko) { wheelPixelsPerUnit = 15 }
  3971. else if (chrome) { wheelPixelsPerUnit = -.7 }
  3972. else if (safari) { wheelPixelsPerUnit = -1/3 }
  3973. function wheelEventDelta(e) {
  3974. var dx = e.wheelDeltaX, dy = e.wheelDeltaY
  3975. if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) { dx = e.detail }
  3976. if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) { dy = e.detail }
  3977. else if (dy == null) { dy = e.wheelDelta }
  3978. return {x: dx, y: dy}
  3979. }
  3980. function wheelEventPixels(e) {
  3981. var delta = wheelEventDelta(e)
  3982. delta.x *= wheelPixelsPerUnit
  3983. delta.y *= wheelPixelsPerUnit
  3984. return delta
  3985. }
  3986. function onScrollWheel(cm, e) {
  3987. var delta = wheelEventDelta(e), dx = delta.x, dy = delta.y
  3988. var display = cm.display, scroll = display.scroller
  3989. // Quit if there's nothing to scroll here
  3990. var canScrollX = scroll.scrollWidth > scroll.clientWidth
  3991. var canScrollY = scroll.scrollHeight > scroll.clientHeight
  3992. if (!(dx && canScrollX || dy && canScrollY)) { return }
  3993. // Webkit browsers on OS X abort momentum scrolls when the target
  3994. // of the scroll event is removed from the scrollable element.
  3995. // This hack (see related code in patchDisplay) makes sure the
  3996. // element is kept around.
  3997. if (dy && mac && webkit) {
  3998. outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) {
  3999. for (var i = 0; i < view.length; i++) {
  4000. if (view[i].node == cur) {
  4001. cm.display.currentWheelTarget = cur
  4002. break outer
  4003. }
  4004. }
  4005. }
  4006. }
  4007. // On some browsers, horizontal scrolling will cause redraws to
  4008. // happen before the gutter has been realigned, causing it to
  4009. // wriggle around in a most unseemly way. When we have an
  4010. // estimated pixels/delta value, we just handle horizontal
  4011. // scrolling entirely here. It'll be slightly off from native, but
  4012. // better than glitching out.
  4013. if (dx && !gecko && !presto && wheelPixelsPerUnit != null) {
  4014. if (dy && canScrollY)
  4015. { updateScrollTop(cm, Math.max(0, scroll.scrollTop + dy * wheelPixelsPerUnit)) }
  4016. setScrollLeft(cm, Math.max(0, scroll.scrollLeft + dx * wheelPixelsPerUnit))
  4017. // Only prevent default scrolling if vertical scrolling is
  4018. // actually possible. Otherwise, it causes vertical scroll
  4019. // jitter on OSX trackpads when deltaX is small and deltaY
  4020. // is large (issue #3579)
  4021. if (!dy || (dy && canScrollY))
  4022. { e_preventDefault(e) }
  4023. display.wheelStartX = null // Abort measurement, if in progress
  4024. return
  4025. }
  4026. // 'Project' the visible viewport to cover the area that is being
  4027. // scrolled into view (if we know enough to estimate it).
  4028. if (dy && wheelPixelsPerUnit != null) {
  4029. var pixels = dy * wheelPixelsPerUnit
  4030. var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight
  4031. if (pixels < 0) { top = Math.max(0, top + pixels - 50) }
  4032. else { bot = Math.min(cm.doc.height, bot + pixels + 50) }
  4033. updateDisplaySimple(cm, {top: top, bottom: bot})
  4034. }
  4035. if (wheelSamples < 20) {
  4036. if (display.wheelStartX == null) {
  4037. display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop
  4038. display.wheelDX = dx; display.wheelDY = dy
  4039. setTimeout(function () {
  4040. if (display.wheelStartX == null) { return }
  4041. var movedX = scroll.scrollLeft - display.wheelStartX
  4042. var movedY = scroll.scrollTop - display.wheelStartY
  4043. var sample = (movedY && display.wheelDY && movedY / display.wheelDY) ||
  4044. (movedX && display.wheelDX && movedX / display.wheelDX)
  4045. display.wheelStartX = display.wheelStartY = null
  4046. if (!sample) { return }
  4047. wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1)
  4048. ++wheelSamples
  4049. }, 200)
  4050. } else {
  4051. display.wheelDX += dx; display.wheelDY += dy
  4052. }
  4053. }
  4054. }
  4055. // Selection objects are immutable. A new one is created every time
  4056. // the selection changes. A selection is one or more non-overlapping
  4057. // (and non-touching) ranges, sorted, and an integer that indicates
  4058. // which one is the primary selection (the one that's scrolled into
  4059. // view, that getCursor returns, etc).
  4060. var Selection = function(ranges, primIndex) {
  4061. this.ranges = ranges
  4062. this.primIndex = primIndex
  4063. };
  4064. Selection.prototype.primary = function () { return this.ranges[this.primIndex] };
  4065. Selection.prototype.equals = function (other) {
  4066. var this$1 = this;
  4067. if (other == this) { return true }
  4068. if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) { return false }
  4069. for (var i = 0; i < this.ranges.length; i++) {
  4070. var here = this$1.ranges[i], there = other.ranges[i]
  4071. if (!equalCursorPos(here.anchor, there.anchor) || !equalCursorPos(here.head, there.head)) { return false }
  4072. }
  4073. return true
  4074. };
  4075. Selection.prototype.deepCopy = function () {
  4076. var this$1 = this;
  4077. var out = []
  4078. for (var i = 0; i < this.ranges.length; i++)
  4079. { out[i] = new Range(copyPos(this$1.ranges[i].anchor), copyPos(this$1.ranges[i].head)) }
  4080. return new Selection(out, this.primIndex)
  4081. };
  4082. Selection.prototype.somethingSelected = function () {
  4083. var this$1 = this;
  4084. for (var i = 0; i < this.ranges.length; i++)
  4085. { if (!this$1.ranges[i].empty()) { return true } }
  4086. return false
  4087. };
  4088. Selection.prototype.contains = function (pos, end) {
  4089. var this$1 = this;
  4090. if (!end) { end = pos }
  4091. for (var i = 0; i < this.ranges.length; i++) {
  4092. var range = this$1.ranges[i]
  4093. if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0)
  4094. { return i }
  4095. }
  4096. return -1
  4097. };
  4098. var Range = function(anchor, head) {
  4099. this.anchor = anchor; this.head = head
  4100. };
  4101. Range.prototype.from = function () { return minPos(this.anchor, this.head) };
  4102. Range.prototype.to = function () { return maxPos(this.anchor, this.head) };
  4103. Range.prototype.empty = function () { return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch };
  4104. // Take an unsorted, potentially overlapping set of ranges, and
  4105. // build a selection out of it. 'Consumes' ranges array (modifying
  4106. // it).
  4107. function normalizeSelection(ranges, primIndex) {
  4108. var prim = ranges[primIndex]
  4109. ranges.sort(function (a, b) { return cmp(a.from(), b.from()); })
  4110. primIndex = indexOf(ranges, prim)
  4111. for (var i = 1; i < ranges.length; i++) {
  4112. var cur = ranges[i], prev = ranges[i - 1]
  4113. if (cmp(prev.to(), cur.from()) >= 0) {
  4114. var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to())
  4115. var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head
  4116. if (i <= primIndex) { --primIndex }
  4117. ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to))
  4118. }
  4119. }
  4120. return new Selection(ranges, primIndex)
  4121. }
  4122. function simpleSelection(anchor, head) {
  4123. return new Selection([new Range(anchor, head || anchor)], 0)
  4124. }
  4125. // Compute the position of the end of a change (its 'to' property
  4126. // refers to the pre-change end).
  4127. function changeEnd(change) {
  4128. if (!change.text) { return change.to }
  4129. return Pos(change.from.line + change.text.length - 1,
  4130. lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0))
  4131. }
  4132. // Adjust a position to refer to the post-change position of the
  4133. // same text, or the end of the change if the change covers it.
  4134. function adjustForChange(pos, change) {
  4135. if (cmp(pos, change.from) < 0) { return pos }
  4136. if (cmp(pos, change.to) <= 0) { return changeEnd(change) }
  4137. var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch
  4138. if (pos.line == change.to.line) { ch += changeEnd(change).ch - change.to.ch }
  4139. return Pos(line, ch)
  4140. }
  4141. function computeSelAfterChange(doc, change) {
  4142. var out = []
  4143. for (var i = 0; i < doc.sel.ranges.length; i++) {
  4144. var range = doc.sel.ranges[i]
  4145. out.push(new Range(adjustForChange(range.anchor, change),
  4146. adjustForChange(range.head, change)))
  4147. }
  4148. return normalizeSelection(out, doc.sel.primIndex)
  4149. }
  4150. function offsetPos(pos, old, nw) {
  4151. if (pos.line == old.line)
  4152. { return Pos(nw.line, pos.ch - old.ch + nw.ch) }
  4153. else
  4154. { return Pos(nw.line + (pos.line - old.line), pos.ch) }
  4155. }
  4156. // Used by replaceSelections to allow moving the selection to the
  4157. // start or around the replaced test. Hint may be "start" or "around".
  4158. function computeReplacedSel(doc, changes, hint) {
  4159. var out = []
  4160. var oldPrev = Pos(doc.first, 0), newPrev = oldPrev
  4161. for (var i = 0; i < changes.length; i++) {
  4162. var change = changes[i]
  4163. var from = offsetPos(change.from, oldPrev, newPrev)
  4164. var to = offsetPos(changeEnd(change), oldPrev, newPrev)
  4165. oldPrev = change.to
  4166. newPrev = to
  4167. if (hint == "around") {
  4168. var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) < 0
  4169. out[i] = new Range(inv ? to : from, inv ? from : to)
  4170. } else {
  4171. out[i] = new Range(from, from)
  4172. }
  4173. }
  4174. return new Selection(out, doc.sel.primIndex)
  4175. }
  4176. // Used to get the editor into a consistent state again when options change.
  4177. function loadMode(cm) {
  4178. cm.doc.mode = getMode(cm.options, cm.doc.modeOption)
  4179. resetModeState(cm)
  4180. }
  4181. function resetModeState(cm) {
  4182. cm.doc.iter(function (line) {
  4183. if (line.stateAfter) { line.stateAfter = null }
  4184. if (line.styles) { line.styles = null }
  4185. })
  4186. cm.doc.modeFrontier = cm.doc.highlightFrontier = cm.doc.first
  4187. startWorker(cm, 100)
  4188. cm.state.modeGen++
  4189. if (cm.curOp) { regChange(cm) }
  4190. }
  4191. // DOCUMENT DATA STRUCTURE
  4192. // By default, updates that start and end at the beginning of a line
  4193. // are treated specially, in order to make the association of line
  4194. // widgets and marker elements with the text behave more intuitive.
  4195. function isWholeLineUpdate(doc, change) {
  4196. return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" &&
  4197. (!doc.cm || doc.cm.options.wholeLineUpdateBefore)
  4198. }
  4199. // Perform a change on the document data structure.
  4200. function updateDoc(doc, change, markedSpans, estimateHeight) {
  4201. function spansFor(n) {return markedSpans ? markedSpans[n] : null}
  4202. function update(line, text, spans) {
  4203. updateLine(line, text, spans, estimateHeight)
  4204. signalLater(line, "change", line, change)
  4205. }
  4206. function linesFor(start, end) {
  4207. var result = []
  4208. for (var i = start; i < end; ++i)
  4209. { result.push(new Line(text[i], spansFor(i), estimateHeight)) }
  4210. return result
  4211. }
  4212. var from = change.from, to = change.to, text = change.text
  4213. var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line)
  4214. var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line
  4215. // Adjust the line structure
  4216. if (change.full) {
  4217. doc.insert(0, linesFor(0, text.length))
  4218. doc.remove(text.length, doc.size - text.length)
  4219. } else if (isWholeLineUpdate(doc, change)) {
  4220. // This is a whole-line replace. Treated specially to make
  4221. // sure line objects move the way they are supposed to.
  4222. var added = linesFor(0, text.length - 1)
  4223. update(lastLine, lastLine.text, lastSpans)
  4224. if (nlines) { doc.remove(from.line, nlines) }
  4225. if (added.length) { doc.insert(from.line, added) }
  4226. } else if (firstLine == lastLine) {
  4227. if (text.length == 1) {
  4228. update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans)
  4229. } else {
  4230. var added$1 = linesFor(1, text.length - 1)
  4231. added$1.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight))
  4232. update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0))
  4233. doc.insert(from.line + 1, added$1)
  4234. }
  4235. } else if (text.length == 1) {
  4236. update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0))
  4237. doc.remove(from.line + 1, nlines)
  4238. } else {
  4239. update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0))
  4240. update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans)
  4241. var added$2 = linesFor(1, text.length - 1)
  4242. if (nlines > 1) { doc.remove(from.line + 1, nlines - 1) }
  4243. doc.insert(from.line + 1, added$2)
  4244. }
  4245. signalLater(doc, "change", doc, change)
  4246. }
  4247. // Call f for all linked documents.
  4248. function linkedDocs(doc, f, sharedHistOnly) {
  4249. function propagate(doc, skip, sharedHist) {
  4250. if (doc.linked) { for (var i = 0; i < doc.linked.length; ++i) {
  4251. var rel = doc.linked[i]
  4252. if (rel.doc == skip) { continue }
  4253. var shared = sharedHist && rel.sharedHist
  4254. if (sharedHistOnly && !shared) { continue }
  4255. f(rel.doc, shared)
  4256. propagate(rel.doc, doc, shared)
  4257. } }
  4258. }
  4259. propagate(doc, null, true)
  4260. }
  4261. // Attach a document to an editor.
  4262. function attachDoc(cm, doc) {
  4263. if (doc.cm) { throw new Error("This document is already in use.") }
  4264. cm.doc = doc
  4265. doc.cm = cm
  4266. estimateLineHeights(cm)
  4267. loadMode(cm)
  4268. setDirectionClass(cm)
  4269. if (!cm.options.lineWrapping) { findMaxLine(cm) }
  4270. cm.options.mode = doc.modeOption
  4271. regChange(cm)
  4272. }
  4273. function setDirectionClass(cm) {
  4274. ;(cm.doc.direction == "rtl" ? addClass : rmClass)(cm.display.lineDiv, "CodeMirror-rtl")
  4275. }
  4276. function directionChanged(cm) {
  4277. runInOp(cm, function () {
  4278. setDirectionClass(cm)
  4279. regChange(cm)
  4280. })
  4281. }
  4282. function History(startGen) {
  4283. // Arrays of change events and selections. Doing something adds an
  4284. // event to done and clears undo. Undoing moves events from done
  4285. // to undone, redoing moves them in the other direction.
  4286. this.done = []; this.undone = []
  4287. this.undoDepth = Infinity
  4288. // Used to track when changes can be merged into a single undo
  4289. // event
  4290. this.lastModTime = this.lastSelTime = 0
  4291. this.lastOp = this.lastSelOp = null
  4292. this.lastOrigin = this.lastSelOrigin = null
  4293. // Used by the isClean() method
  4294. this.generation = this.maxGeneration = startGen || 1
  4295. }
  4296. // Create a history change event from an updateDoc-style change
  4297. // object.
  4298. function historyChangeFromChange(doc, change) {
  4299. var histChange = {from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to)}
  4300. attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1)
  4301. linkedDocs(doc, function (doc) { return attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1); }, true)
  4302. return histChange
  4303. }
  4304. // Pop all selection events off the end of a history array. Stop at
  4305. // a change event.
  4306. function clearSelectionEvents(array) {
  4307. while (array.length) {
  4308. var last = lst(array)
  4309. if (last.ranges) { array.pop() }
  4310. else { break }
  4311. }
  4312. }
  4313. // Find the top change event in the history. Pop off selection
  4314. // events that are in the way.
  4315. function lastChangeEvent(hist, force) {
  4316. if (force) {
  4317. clearSelectionEvents(hist.done)
  4318. return lst(hist.done)
  4319. } else if (hist.done.length && !lst(hist.done).ranges) {
  4320. return lst(hist.done)
  4321. } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) {
  4322. hist.done.pop()
  4323. return lst(hist.done)
  4324. }
  4325. }
  4326. // Register a change in the history. Merges changes that are within
  4327. // a single operation, or are close together with an origin that
  4328. // allows merging (starting with "+") into a single event.
  4329. function addChangeToHistory(doc, change, selAfter, opId) {
  4330. var hist = doc.history
  4331. hist.undone.length = 0
  4332. var time = +new Date, cur
  4333. var last
  4334. if ((hist.lastOp == opId ||
  4335. hist.lastOrigin == change.origin && change.origin &&
  4336. ((change.origin.charAt(0) == "+" && hist.lastModTime > time - (doc.cm ? doc.cm.options.historyEventDelay : 500)) ||
  4337. change.origin.charAt(0) == "*")) &&
  4338. (cur = lastChangeEvent(hist, hist.lastOp == opId))) {
  4339. // Merge this change into the last event
  4340. last = lst(cur.changes)
  4341. if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) {
  4342. // Optimized case for simple insertion -- don't want to add
  4343. // new changesets for every character typed
  4344. last.to = changeEnd(change)
  4345. } else {
  4346. // Add new sub-event
  4347. cur.changes.push(historyChangeFromChange(doc, change))
  4348. }
  4349. } else {
  4350. // Can not be merged, start a new event.
  4351. var before = lst(hist.done)
  4352. if (!before || !before.ranges)
  4353. { pushSelectionToHistory(doc.sel, hist.done) }
  4354. cur = {changes: [historyChangeFromChange(doc, change)],
  4355. generation: hist.generation}
  4356. hist.done.push(cur)
  4357. while (hist.done.length > hist.undoDepth) {
  4358. hist.done.shift()
  4359. if (!hist.done[0].ranges) { hist.done.shift() }
  4360. }
  4361. }
  4362. hist.done.push(selAfter)
  4363. hist.generation = ++hist.maxGeneration
  4364. hist.lastModTime = hist.lastSelTime = time
  4365. hist.lastOp = hist.lastSelOp = opId
  4366. hist.lastOrigin = hist.lastSelOrigin = change.origin
  4367. if (!last) { signal(doc, "historyAdded") }
  4368. }
  4369. function selectionEventCanBeMerged(doc, origin, prev, sel) {
  4370. var ch = origin.charAt(0)
  4371. return ch == "*" ||
  4372. ch == "+" &&
  4373. prev.ranges.length == sel.ranges.length &&
  4374. prev.somethingSelected() == sel.somethingSelected() &&
  4375. new Date - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500)
  4376. }
  4377. // Called whenever the selection changes, sets the new selection as
  4378. // the pending selection in the history, and pushes the old pending
  4379. // selection into the 'done' array when it was significantly
  4380. // different (in number of selected ranges, emptiness, or time).
  4381. function addSelectionToHistory(doc, sel, opId, options) {
  4382. var hist = doc.history, origin = options && options.origin
  4383. // A new event is started when the previous origin does not match
  4384. // the current, or the origins don't allow matching. Origins
  4385. // starting with * are always merged, those starting with + are
  4386. // merged when similar and close together in time.
  4387. if (opId == hist.lastSelOp ||
  4388. (origin && hist.lastSelOrigin == origin &&
  4389. (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin ||
  4390. selectionEventCanBeMerged(doc, origin, lst(hist.done), sel))))
  4391. { hist.done[hist.done.length - 1] = sel }
  4392. else
  4393. { pushSelectionToHistory(sel, hist.done) }
  4394. hist.lastSelTime = +new Date
  4395. hist.lastSelOrigin = origin
  4396. hist.lastSelOp = opId
  4397. if (options && options.clearRedo !== false)
  4398. { clearSelectionEvents(hist.undone) }
  4399. }
  4400. function pushSelectionToHistory(sel, dest) {
  4401. var top = lst(dest)
  4402. if (!(top && top.ranges && top.equals(sel)))
  4403. { dest.push(sel) }
  4404. }
  4405. // Used to store marked span information in the history.
  4406. function attachLocalSpans(doc, change, from, to) {
  4407. var existing = change["spans_" + doc.id], n = 0
  4408. doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function (line) {
  4409. if (line.markedSpans)
  4410. { (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans }
  4411. ++n
  4412. })
  4413. }
  4414. // When un/re-doing restores text containing marked spans, those
  4415. // that have been explicitly cleared should not be restored.
  4416. function removeClearedSpans(spans) {
  4417. if (!spans) { return null }
  4418. var out
  4419. for (var i = 0; i < spans.length; ++i) {
  4420. if (spans[i].marker.explicitlyCleared) { if (!out) { out = spans.slice(0, i) } }
  4421. else if (out) { out.push(spans[i]) }
  4422. }
  4423. return !out ? spans : out.length ? out : null
  4424. }
  4425. // Retrieve and filter the old marked spans stored in a change event.
  4426. function getOldSpans(doc, change) {
  4427. var found = change["spans_" + doc.id]
  4428. if (!found) { return null }
  4429. var nw = []
  4430. for (var i = 0; i < change.text.length; ++i)
  4431. { nw.push(removeClearedSpans(found[i])) }
  4432. return nw
  4433. }
  4434. // Used for un/re-doing changes from the history. Combines the
  4435. // result of computing the existing spans with the set of spans that
  4436. // existed in the history (so that deleting around a span and then
  4437. // undoing brings back the span).
  4438. function mergeOldSpans(doc, change) {
  4439. var old = getOldSpans(doc, change)
  4440. var stretched = stretchSpansOverChange(doc, change)
  4441. if (!old) { return stretched }
  4442. if (!stretched) { return old }
  4443. for (var i = 0; i < old.length; ++i) {
  4444. var oldCur = old[i], stretchCur = stretched[i]
  4445. if (oldCur && stretchCur) {
  4446. spans: for (var j = 0; j < stretchCur.length; ++j) {
  4447. var span = stretchCur[j]
  4448. for (var k = 0; k < oldCur.length; ++k)
  4449. { if (oldCur[k].marker == span.marker) { continue spans } }
  4450. oldCur.push(span)
  4451. }
  4452. } else if (stretchCur) {
  4453. old[i] = stretchCur
  4454. }
  4455. }
  4456. return old
  4457. }
  4458. // Used both to provide a JSON-safe object in .getHistory, and, when
  4459. // detaching a document, to split the history in two
  4460. function copyHistoryArray(events, newGroup, instantiateSel) {
  4461. var copy = []
  4462. for (var i = 0; i < events.length; ++i) {
  4463. var event = events[i]
  4464. if (event.ranges) {
  4465. copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event)
  4466. continue
  4467. }
  4468. var changes = event.changes, newChanges = []
  4469. copy.push({changes: newChanges})
  4470. for (var j = 0; j < changes.length; ++j) {
  4471. var change = changes[j], m = (void 0)
  4472. newChanges.push({from: change.from, to: change.to, text: change.text})
  4473. if (newGroup) { for (var prop in change) { if (m = prop.match(/^spans_(\d+)$/)) {
  4474. if (indexOf(newGroup, Number(m[1])) > -1) {
  4475. lst(newChanges)[prop] = change[prop]
  4476. delete change[prop]
  4477. }
  4478. } } }
  4479. }
  4480. }
  4481. return copy
  4482. }
  4483. // The 'scroll' parameter given to many of these indicated whether
  4484. // the new cursor position should be scrolled into view after
  4485. // modifying the selection.
  4486. // If shift is held or the extend flag is set, extends a range to
  4487. // include a given position (and optionally a second position).
  4488. // Otherwise, simply returns the range between the given positions.
  4489. // Used for cursor motion and such.
  4490. function extendRange(range, head, other, extend) {
  4491. if (extend) {
  4492. var anchor = range.anchor
  4493. if (other) {
  4494. var posBefore = cmp(head, anchor) < 0
  4495. if (posBefore != (cmp(other, anchor) < 0)) {
  4496. anchor = head
  4497. head = other
  4498. } else if (posBefore != (cmp(head, other) < 0)) {
  4499. head = other
  4500. }
  4501. }
  4502. return new Range(anchor, head)
  4503. } else {
  4504. return new Range(other || head, head)
  4505. }
  4506. }
  4507. // Extend the primary selection range, discard the rest.
  4508. function extendSelection(doc, head, other, options, extend) {
  4509. if (extend == null) { extend = doc.cm && (doc.cm.display.shift || doc.extend) }
  4510. setSelection(doc, new Selection([extendRange(doc.sel.primary(), head, other, extend)], 0), options)
  4511. }
  4512. // Extend all selections (pos is an array of selections with length
  4513. // equal the number of selections)
  4514. function extendSelections(doc, heads, options) {
  4515. var out = []
  4516. var extend = doc.cm && (doc.cm.display.shift || doc.extend)
  4517. for (var i = 0; i < doc.sel.ranges.length; i++)
  4518. { out[i] = extendRange(doc.sel.ranges[i], heads[i], null, extend) }
  4519. var newSel = normalizeSelection(out, doc.sel.primIndex)
  4520. setSelection(doc, newSel, options)
  4521. }
  4522. // Updates a single range in the selection.
  4523. function replaceOneSelection(doc, i, range, options) {
  4524. var ranges = doc.sel.ranges.slice(0)
  4525. ranges[i] = range
  4526. setSelection(doc, normalizeSelection(ranges, doc.sel.primIndex), options)
  4527. }
  4528. // Reset the selection to a single range.
  4529. function setSimpleSelection(doc, anchor, head, options) {
  4530. setSelection(doc, simpleSelection(anchor, head), options)
  4531. }
  4532. // Give beforeSelectionChange handlers a change to influence a
  4533. // selection update.
  4534. function filterSelectionChange(doc, sel, options) {
  4535. var obj = {
  4536. ranges: sel.ranges,
  4537. update: function(ranges) {
  4538. var this$1 = this;
  4539. this.ranges = []
  4540. for (var i = 0; i < ranges.length; i++)
  4541. { this$1.ranges[i] = new Range(clipPos(doc, ranges[i].anchor),
  4542. clipPos(doc, ranges[i].head)) }
  4543. },
  4544. origin: options && options.origin
  4545. }
  4546. signal(doc, "beforeSelectionChange", doc, obj)
  4547. if (doc.cm) { signal(doc.cm, "beforeSelectionChange", doc.cm, obj) }
  4548. if (obj.ranges != sel.ranges) { return normalizeSelection(obj.ranges, obj.ranges.length - 1) }
  4549. else { return sel }
  4550. }
  4551. function setSelectionReplaceHistory(doc, sel, options) {
  4552. var done = doc.history.done, last = lst(done)
  4553. if (last && last.ranges) {
  4554. done[done.length - 1] = sel
  4555. setSelectionNoUndo(doc, sel, options)
  4556. } else {
  4557. setSelection(doc, sel, options)
  4558. }
  4559. }
  4560. // Set a new selection.
  4561. function setSelection(doc, sel, options) {
  4562. setSelectionNoUndo(doc, sel, options)
  4563. addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options)
  4564. }
  4565. function setSelectionNoUndo(doc, sel, options) {
  4566. if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange"))
  4567. { sel = filterSelectionChange(doc, sel, options) }
  4568. var bias = options && options.bias ||
  4569. (cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1)
  4570. setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true))
  4571. if (!(options && options.scroll === false) && doc.cm)
  4572. { ensureCursorVisible(doc.cm) }
  4573. }
  4574. function setSelectionInner(doc, sel) {
  4575. if (sel.equals(doc.sel)) { return }
  4576. doc.sel = sel
  4577. if (doc.cm) {
  4578. doc.cm.curOp.updateInput = doc.cm.curOp.selectionChanged = true
  4579. signalCursorActivity(doc.cm)
  4580. }
  4581. signalLater(doc, "cursorActivity", doc)
  4582. }
  4583. // Verify that the selection does not partially select any atomic
  4584. // marked ranges.
  4585. function reCheckSelection(doc) {
  4586. setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false))
  4587. }
  4588. // Return a selection that does not partially select any atomic
  4589. // ranges.
  4590. function skipAtomicInSelection(doc, sel, bias, mayClear) {
  4591. var out
  4592. for (var i = 0; i < sel.ranges.length; i++) {
  4593. var range = sel.ranges[i]
  4594. var old = sel.ranges.length == doc.sel.ranges.length && doc.sel.ranges[i]
  4595. var newAnchor = skipAtomic(doc, range.anchor, old && old.anchor, bias, mayClear)
  4596. var newHead = skipAtomic(doc, range.head, old && old.head, bias, mayClear)
  4597. if (out || newAnchor != range.anchor || newHead != range.head) {
  4598. if (!out) { out = sel.ranges.slice(0, i) }
  4599. out[i] = new Range(newAnchor, newHead)
  4600. }
  4601. }
  4602. return out ? normalizeSelection(out, sel.primIndex) : sel
  4603. }
  4604. function skipAtomicInner(doc, pos, oldPos, dir, mayClear) {
  4605. var line = getLine(doc, pos.line)
  4606. if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) {
  4607. var sp = line.markedSpans[i], m = sp.marker
  4608. if ((sp.from == null || (m.inclusiveLeft ? sp.from <= pos.ch : sp.from < pos.ch)) &&
  4609. (sp.to == null || (m.inclusiveRight ? sp.to >= pos.ch : sp.to > pos.ch))) {
  4610. if (mayClear) {
  4611. signal(m, "beforeCursorEnter")
  4612. if (m.explicitlyCleared) {
  4613. if (!line.markedSpans) { break }
  4614. else {--i; continue}
  4615. }
  4616. }
  4617. if (!m.atomic) { continue }
  4618. if (oldPos) {
  4619. var near = m.find(dir < 0 ? 1 : -1), diff = (void 0)
  4620. if (dir < 0 ? m.inclusiveRight : m.inclusiveLeft)
  4621. { near = movePos(doc, near, -dir, near && near.line == pos.line ? line : null) }
  4622. if (near && near.line == pos.line && (diff = cmp(near, oldPos)) && (dir < 0 ? diff < 0 : diff > 0))
  4623. { return skipAtomicInner(doc, near, pos, dir, mayClear) }
  4624. }
  4625. var far = m.find(dir < 0 ? -1 : 1)
  4626. if (dir < 0 ? m.inclusiveLeft : m.inclusiveRight)
  4627. { far = movePos(doc, far, dir, far.line == pos.line ? line : null) }
  4628. return far ? skipAtomicInner(doc, far, pos, dir, mayClear) : null
  4629. }
  4630. } }
  4631. return pos
  4632. }
  4633. // Ensure a given position is not inside an atomic range.
  4634. function skipAtomic(doc, pos, oldPos, bias, mayClear) {
  4635. var dir = bias || 1
  4636. var found = skipAtomicInner(doc, pos, oldPos, dir, mayClear) ||
  4637. (!mayClear && skipAtomicInner(doc, pos, oldPos, dir, true)) ||
  4638. skipAtomicInner(doc, pos, oldPos, -dir, mayClear) ||
  4639. (!mayClear && skipAtomicInner(doc, pos, oldPos, -dir, true))
  4640. if (!found) {
  4641. doc.cantEdit = true
  4642. return Pos(doc.first, 0)
  4643. }
  4644. return found
  4645. }
  4646. function movePos(doc, pos, dir, line) {
  4647. if (dir < 0 && pos.ch == 0) {
  4648. if (pos.line > doc.first) { return clipPos(doc, Pos(pos.line - 1)) }
  4649. else { return null }
  4650. } else if (dir > 0 && pos.ch == (line || getLine(doc, pos.line)).text.length) {
  4651. if (pos.line < doc.first + doc.size - 1) { return Pos(pos.line + 1, 0) }
  4652. else { return null }
  4653. } else {
  4654. return new Pos(pos.line, pos.ch + dir)
  4655. }
  4656. }
  4657. function selectAll(cm) {
  4658. cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll)
  4659. }
  4660. // UPDATING
  4661. // Allow "beforeChange" event handlers to influence a change
  4662. function filterChange(doc, change, update) {
  4663. var obj = {
  4664. canceled: false,
  4665. from: change.from,
  4666. to: change.to,
  4667. text: change.text,
  4668. origin: change.origin,
  4669. cancel: function () { return obj.canceled = true; }
  4670. }
  4671. if (update) { obj.update = function (from, to, text, origin) {
  4672. if (from) { obj.from = clipPos(doc, from) }
  4673. if (to) { obj.to = clipPos(doc, to) }
  4674. if (text) { obj.text = text }
  4675. if (origin !== undefined) { obj.origin = origin }
  4676. } }
  4677. signal(doc, "beforeChange", doc, obj)
  4678. if (doc.cm) { signal(doc.cm, "beforeChange", doc.cm, obj) }
  4679. if (obj.canceled) { return null }
  4680. return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin}
  4681. }
  4682. // Apply a change to a document, and add it to the document's
  4683. // history, and propagating it to all linked documents.
  4684. function makeChange(doc, change, ignoreReadOnly) {
  4685. if (doc.cm) {
  4686. if (!doc.cm.curOp) { return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly) }
  4687. if (doc.cm.state.suppressEdits) { return }
  4688. }
  4689. if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) {
  4690. change = filterChange(doc, change, true)
  4691. if (!change) { return }
  4692. }
  4693. // Possibly split or suppress the update based on the presence
  4694. // of read-only spans in its range.
  4695. var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to)
  4696. if (split) {
  4697. for (var i = split.length - 1; i >= 0; --i)
  4698. { makeChangeInner(doc, {from: split[i].from, to: split[i].to, text: i ? [""] : change.text, origin: change.origin}) }
  4699. } else {
  4700. makeChangeInner(doc, change)
  4701. }
  4702. }
  4703. function makeChangeInner(doc, change) {
  4704. if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) { return }
  4705. var selAfter = computeSelAfterChange(doc, change)
  4706. addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN)
  4707. makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change))
  4708. var rebased = []
  4709. linkedDocs(doc, function (doc, sharedHist) {
  4710. if (!sharedHist && indexOf(rebased, doc.history) == -1) {
  4711. rebaseHist(doc.history, change)
  4712. rebased.push(doc.history)
  4713. }
  4714. makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change))
  4715. })
  4716. }
  4717. // Revert a change stored in a document's history.
  4718. function makeChangeFromHistory(doc, type, allowSelectionOnly) {
  4719. var suppress = doc.cm && doc.cm.state.suppressEdits
  4720. if (suppress && !allowSelectionOnly) { return }
  4721. var hist = doc.history, event, selAfter = doc.sel
  4722. var source = type == "undo" ? hist.done : hist.undone, dest = type == "undo" ? hist.undone : hist.done
  4723. // Verify that there is a useable event (so that ctrl-z won't
  4724. // needlessly clear selection events)
  4725. var i = 0
  4726. for (; i < source.length; i++) {
  4727. event = source[i]
  4728. if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges)
  4729. { break }
  4730. }
  4731. if (i == source.length) { return }
  4732. hist.lastOrigin = hist.lastSelOrigin = null
  4733. for (;;) {
  4734. event = source.pop()
  4735. if (event.ranges) {
  4736. pushSelectionToHistory(event, dest)
  4737. if (allowSelectionOnly && !event.equals(doc.sel)) {
  4738. setSelection(doc, event, {clearRedo: false})
  4739. return
  4740. }
  4741. selAfter = event
  4742. } else if (suppress) {
  4743. source.push(event)
  4744. return
  4745. } else { break }
  4746. }
  4747. // Build up a reverse change object to add to the opposite history
  4748. // stack (redo when undoing, and vice versa).
  4749. var antiChanges = []
  4750. pushSelectionToHistory(selAfter, dest)
  4751. dest.push({changes: antiChanges, generation: hist.generation})
  4752. hist.generation = event.generation || ++hist.maxGeneration
  4753. var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")
  4754. var loop = function ( i ) {
  4755. var change = event.changes[i]
  4756. change.origin = type
  4757. if (filter && !filterChange(doc, change, false)) {
  4758. source.length = 0
  4759. return {}
  4760. }
  4761. antiChanges.push(historyChangeFromChange(doc, change))
  4762. var after = i ? computeSelAfterChange(doc, change) : lst(source)
  4763. makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change))
  4764. if (!i && doc.cm) { doc.cm.scrollIntoView({from: change.from, to: changeEnd(change)}) }
  4765. var rebased = []
  4766. // Propagate to the linked documents
  4767. linkedDocs(doc, function (doc, sharedHist) {
  4768. if (!sharedHist && indexOf(rebased, doc.history) == -1) {
  4769. rebaseHist(doc.history, change)
  4770. rebased.push(doc.history)
  4771. }
  4772. makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change))
  4773. })
  4774. };
  4775. for (var i$1 = event.changes.length - 1; i$1 >= 0; --i$1) {
  4776. var returned = loop( i$1 );
  4777. if ( returned ) return returned.v;
  4778. }
  4779. }
  4780. // Sub-views need their line numbers shifted when text is added
  4781. // above or below them in the parent document.
  4782. function shiftDoc(doc, distance) {
  4783. if (distance == 0) { return }
  4784. doc.first += distance
  4785. doc.sel = new Selection(map(doc.sel.ranges, function (range) { return new Range(
  4786. Pos(range.anchor.line + distance, range.anchor.ch),
  4787. Pos(range.head.line + distance, range.head.ch)
  4788. ); }), doc.sel.primIndex)
  4789. if (doc.cm) {
  4790. regChange(doc.cm, doc.first, doc.first - distance, distance)
  4791. for (var d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++)
  4792. { regLineChange(doc.cm, l, "gutter") }
  4793. }
  4794. }
  4795. // More lower-level change function, handling only a single document
  4796. // (not linked ones).
  4797. function makeChangeSingleDoc(doc, change, selAfter, spans) {
  4798. if (doc.cm && !doc.cm.curOp)
  4799. { return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans) }
  4800. if (change.to.line < doc.first) {
  4801. shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line))
  4802. return
  4803. }
  4804. if (change.from.line > doc.lastLine()) { return }
  4805. // Clip the change to the size of this doc
  4806. if (change.from.line < doc.first) {
  4807. var shift = change.text.length - 1 - (doc.first - change.from.line)
  4808. shiftDoc(doc, shift)
  4809. change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch),
  4810. text: [lst(change.text)], origin: change.origin}
  4811. }
  4812. var last = doc.lastLine()
  4813. if (change.to.line > last) {
  4814. change = {from: change.from, to: Pos(last, getLine(doc, last).text.length),
  4815. text: [change.text[0]], origin: change.origin}
  4816. }
  4817. change.removed = getBetween(doc, change.from, change.to)
  4818. if (!selAfter) { selAfter = computeSelAfterChange(doc, change) }
  4819. if (doc.cm) { makeChangeSingleDocInEditor(doc.cm, change, spans) }
  4820. else { updateDoc(doc, change, spans) }
  4821. setSelectionNoUndo(doc, selAfter, sel_dontScroll)
  4822. }
  4823. // Handle the interaction of a change to a document with the editor
  4824. // that this document is part of.
  4825. function makeChangeSingleDocInEditor(cm, change, spans) {
  4826. var doc = cm.doc, display = cm.display, from = change.from, to = change.to
  4827. var recomputeMaxLength = false, checkWidthStart = from.line
  4828. if (!cm.options.lineWrapping) {
  4829. checkWidthStart = lineNo(visualLine(getLine(doc, from.line)))
  4830. doc.iter(checkWidthStart, to.line + 1, function (line) {
  4831. if (line == display.maxLine) {
  4832. recomputeMaxLength = true
  4833. return true
  4834. }
  4835. })
  4836. }
  4837. if (doc.sel.contains(change.from, change.to) > -1)
  4838. { signalCursorActivity(cm) }
  4839. updateDoc(doc, change, spans, estimateHeight(cm))
  4840. if (!cm.options.lineWrapping) {
  4841. doc.iter(checkWidthStart, from.line + change.text.length, function (line) {
  4842. var len = lineLength(line)
  4843. if (len > display.maxLineLength) {
  4844. display.maxLine = line
  4845. display.maxLineLength = len
  4846. display.maxLineChanged = true
  4847. recomputeMaxLength = false
  4848. }
  4849. })
  4850. if (recomputeMaxLength) { cm.curOp.updateMaxLine = true }
  4851. }
  4852. retreatFrontier(doc, from.line)
  4853. startWorker(cm, 400)
  4854. var lendiff = change.text.length - (to.line - from.line) - 1
  4855. // Remember that these lines changed, for updating the display
  4856. if (change.full)
  4857. { regChange(cm) }
  4858. else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change))
  4859. { regLineChange(cm, from.line, "text") }
  4860. else
  4861. { regChange(cm, from.line, to.line + 1, lendiff) }
  4862. var changesHandler = hasHandler(cm, "changes"), changeHandler = hasHandler(cm, "change")
  4863. if (changeHandler || changesHandler) {
  4864. var obj = {
  4865. from: from, to: to,
  4866. text: change.text,
  4867. removed: change.removed,
  4868. origin: change.origin
  4869. }
  4870. if (changeHandler) { signalLater(cm, "change", cm, obj) }
  4871. if (changesHandler) { (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj) }
  4872. }
  4873. cm.display.selForContextMenu = null
  4874. }
  4875. function replaceRange(doc, code, from, to, origin) {
  4876. if (!to) { to = from }
  4877. if (cmp(to, from) < 0) { var assign;
  4878. (assign = [to, from], from = assign[0], to = assign[1], assign) }
  4879. if (typeof code == "string") { code = doc.splitLines(code) }
  4880. makeChange(doc, {from: from, to: to, text: code, origin: origin})
  4881. }
  4882. // Rebasing/resetting history to deal with externally-sourced changes
  4883. function rebaseHistSelSingle(pos, from, to, diff) {
  4884. if (to < pos.line) {
  4885. pos.line += diff
  4886. } else if (from < pos.line) {
  4887. pos.line = from
  4888. pos.ch = 0
  4889. }
  4890. }
  4891. // Tries to rebase an array of history events given a change in the
  4892. // document. If the change touches the same lines as the event, the
  4893. // event, and everything 'behind' it, is discarded. If the change is
  4894. // before the event, the event's positions are updated. Uses a
  4895. // copy-on-write scheme for the positions, to avoid having to
  4896. // reallocate them all on every rebase, but also avoid problems with
  4897. // shared position objects being unsafely updated.
  4898. function rebaseHistArray(array, from, to, diff) {
  4899. for (var i = 0; i < array.length; ++i) {
  4900. var sub = array[i], ok = true
  4901. if (sub.ranges) {
  4902. if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true }
  4903. for (var j = 0; j < sub.ranges.length; j++) {
  4904. rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff)
  4905. rebaseHistSelSingle(sub.ranges[j].head, from, to, diff)
  4906. }
  4907. continue
  4908. }
  4909. for (var j$1 = 0; j$1 < sub.changes.length; ++j$1) {
  4910. var cur = sub.changes[j$1]
  4911. if (to < cur.from.line) {
  4912. cur.from = Pos(cur.from.line + diff, cur.from.ch)
  4913. cur.to = Pos(cur.to.line + diff, cur.to.ch)
  4914. } else if (from <= cur.to.line) {
  4915. ok = false
  4916. break
  4917. }
  4918. }
  4919. if (!ok) {
  4920. array.splice(0, i + 1)
  4921. i = 0
  4922. }
  4923. }
  4924. }
  4925. function rebaseHist(hist, change) {
  4926. var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1
  4927. rebaseHistArray(hist.done, from, to, diff)
  4928. rebaseHistArray(hist.undone, from, to, diff)
  4929. }
  4930. // Utility for applying a change to a line by handle or number,
  4931. // returning the number and optionally registering the line as
  4932. // changed.
  4933. function changeLine(doc, handle, changeType, op) {
  4934. var no = handle, line = handle
  4935. if (typeof handle == "number") { line = getLine(doc, clipLine(doc, handle)) }
  4936. else { no = lineNo(handle) }
  4937. if (no == null) { return null }
  4938. if (op(line, no) && doc.cm) { regLineChange(doc.cm, no, changeType) }
  4939. return line
  4940. }
  4941. // The document is represented as a BTree consisting of leaves, with
  4942. // chunk of lines in them, and branches, with up to ten leaves or
  4943. // other branch nodes below them. The top node is always a branch
  4944. // node, and is the document object itself (meaning it has
  4945. // additional methods and properties).
  4946. //
  4947. // All nodes have parent links. The tree is used both to go from
  4948. // line numbers to line objects, and to go from objects to numbers.
  4949. // It also indexes by height, and is used to convert between height
  4950. // and line object, and to find the total height of the document.
  4951. //
  4952. // See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html
  4953. function LeafChunk(lines) {
  4954. var this$1 = this;
  4955. this.lines = lines
  4956. this.parent = null
  4957. var height = 0
  4958. for (var i = 0; i < lines.length; ++i) {
  4959. lines[i].parent = this$1
  4960. height += lines[i].height
  4961. }
  4962. this.height = height
  4963. }
  4964. LeafChunk.prototype = {
  4965. chunkSize: function chunkSize() { return this.lines.length },
  4966. // Remove the n lines at offset 'at'.
  4967. removeInner: function removeInner(at, n) {
  4968. var this$1 = this;
  4969. for (var i = at, e = at + n; i < e; ++i) {
  4970. var line = this$1.lines[i]
  4971. this$1.height -= line.height
  4972. cleanUpLine(line)
  4973. signalLater(line, "delete")
  4974. }
  4975. this.lines.splice(at, n)
  4976. },
  4977. // Helper used to collapse a small branch into a single leaf.
  4978. collapse: function collapse(lines) {
  4979. lines.push.apply(lines, this.lines)
  4980. },
  4981. // Insert the given array of lines at offset 'at', count them as
  4982. // having the given height.
  4983. insertInner: function insertInner(at, lines, height) {
  4984. var this$1 = this;
  4985. this.height += height
  4986. this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at))
  4987. for (var i = 0; i < lines.length; ++i) { lines[i].parent = this$1 }
  4988. },
  4989. // Used to iterate over a part of the tree.
  4990. iterN: function iterN(at, n, op) {
  4991. var this$1 = this;
  4992. for (var e = at + n; at < e; ++at)
  4993. { if (op(this$1.lines[at])) { return true } }
  4994. }
  4995. }
  4996. function BranchChunk(children) {
  4997. var this$1 = this;
  4998. this.children = children
  4999. var size = 0, height = 0
  5000. for (var i = 0; i < children.length; ++i) {
  5001. var ch = children[i]
  5002. size += ch.chunkSize(); height += ch.height
  5003. ch.parent = this$1
  5004. }
  5005. this.size = size
  5006. this.height = height
  5007. this.parent = null
  5008. }
  5009. BranchChunk.prototype = {
  5010. chunkSize: function chunkSize() { return this.size },
  5011. removeInner: function removeInner(at, n) {
  5012. var this$1 = this;
  5013. this.size -= n
  5014. for (var i = 0; i < this.children.length; ++i) {
  5015. var child = this$1.children[i], sz = child.chunkSize()
  5016. if (at < sz) {
  5017. var rm = Math.min(n, sz - at), oldHeight = child.height
  5018. child.removeInner(at, rm)
  5019. this$1.height -= oldHeight - child.height
  5020. if (sz == rm) { this$1.children.splice(i--, 1); child.parent = null }
  5021. if ((n -= rm) == 0) { break }
  5022. at = 0
  5023. } else { at -= sz }
  5024. }
  5025. // If the result is smaller than 25 lines, ensure that it is a
  5026. // single leaf node.
  5027. if (this.size - n < 25 &&
  5028. (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) {
  5029. var lines = []
  5030. this.collapse(lines)
  5031. this.children = [new LeafChunk(lines)]
  5032. this.children[0].parent = this
  5033. }
  5034. },
  5035. collapse: function collapse(lines) {
  5036. var this$1 = this;
  5037. for (var i = 0; i < this.children.length; ++i) { this$1.children[i].collapse(lines) }
  5038. },
  5039. insertInner: function insertInner(at, lines, height) {
  5040. var this$1 = this;
  5041. this.size += lines.length
  5042. this.height += height
  5043. for (var i = 0; i < this.children.length; ++i) {
  5044. var child = this$1.children[i], sz = child.chunkSize()
  5045. if (at <= sz) {
  5046. child.insertInner(at, lines, height)
  5047. if (child.lines && child.lines.length > 50) {
  5048. // To avoid memory thrashing when child.lines is huge (e.g. first view of a large file), it's never spliced.
  5049. // Instead, small slices are taken. They're taken in order because sequential memory accesses are fastest.
  5050. var remaining = child.lines.length % 25 + 25
  5051. for (var pos = remaining; pos < child.lines.length;) {
  5052. var leaf = new LeafChunk(child.lines.slice(pos, pos += 25))
  5053. child.height -= leaf.height
  5054. this$1.children.splice(++i, 0, leaf)
  5055. leaf.parent = this$1
  5056. }
  5057. child.lines = child.lines.slice(0, remaining)
  5058. this$1.maybeSpill()
  5059. }
  5060. break
  5061. }
  5062. at -= sz
  5063. }
  5064. },
  5065. // When a node has grown, check whether it should be split.
  5066. maybeSpill: function maybeSpill() {
  5067. if (this.children.length <= 10) { return }
  5068. var me = this
  5069. do {
  5070. var spilled = me.children.splice(me.children.length - 5, 5)
  5071. var sibling = new BranchChunk(spilled)
  5072. if (!me.parent) { // Become the parent node
  5073. var copy = new BranchChunk(me.children)
  5074. copy.parent = me
  5075. me.children = [copy, sibling]
  5076. me = copy
  5077. } else {
  5078. me.size -= sibling.size
  5079. me.height -= sibling.height
  5080. var myIndex = indexOf(me.parent.children, me)
  5081. me.parent.children.splice(myIndex + 1, 0, sibling)
  5082. }
  5083. sibling.parent = me.parent
  5084. } while (me.children.length > 10)
  5085. me.parent.maybeSpill()
  5086. },
  5087. iterN: function iterN(at, n, op) {
  5088. var this$1 = this;
  5089. for (var i = 0; i < this.children.length; ++i) {
  5090. var child = this$1.children[i], sz = child.chunkSize()
  5091. if (at < sz) {
  5092. var used = Math.min(n, sz - at)
  5093. if (child.iterN(at, used, op)) { return true }
  5094. if ((n -= used) == 0) { break }
  5095. at = 0
  5096. } else { at -= sz }
  5097. }
  5098. }
  5099. }
  5100. // Line widgets are block elements displayed above or below a line.
  5101. var LineWidget = function(doc, node, options) {
  5102. var this$1 = this;
  5103. if (options) { for (var opt in options) { if (options.hasOwnProperty(opt))
  5104. { this$1[opt] = options[opt] } } }
  5105. this.doc = doc
  5106. this.node = node
  5107. };
  5108. LineWidget.prototype.clear = function () {
  5109. var this$1 = this;
  5110. var cm = this.doc.cm, ws = this.line.widgets, line = this.line, no = lineNo(line)
  5111. if (no == null || !ws) { return }
  5112. for (var i = 0; i < ws.length; ++i) { if (ws[i] == this$1) { ws.splice(i--, 1) } }
  5113. if (!ws.length) { line.widgets = null }
  5114. var height = widgetHeight(this)
  5115. updateLineHeight(line, Math.max(0, line.height - height))
  5116. if (cm) {
  5117. runInOp(cm, function () {
  5118. adjustScrollWhenAboveVisible(cm, line, -height)
  5119. regLineChange(cm, no, "widget")
  5120. })
  5121. signalLater(cm, "lineWidgetCleared", cm, this, no)
  5122. }
  5123. };
  5124. LineWidget.prototype.changed = function () {
  5125. var this$1 = this;
  5126. var oldH = this.height, cm = this.doc.cm, line = this.line
  5127. this.height = null
  5128. var diff = widgetHeight(this) - oldH
  5129. if (!diff) { return }
  5130. if (!lineIsHidden(this.doc, line)) { updateLineHeight(line, line.height + diff) }
  5131. if (cm) {
  5132. runInOp(cm, function () {
  5133. cm.curOp.forceUpdate = true
  5134. adjustScrollWhenAboveVisible(cm, line, diff)
  5135. signalLater(cm, "lineWidgetChanged", cm, this$1, lineNo(line))
  5136. })
  5137. }
  5138. };
  5139. eventMixin(LineWidget)
  5140. function adjustScrollWhenAboveVisible(cm, line, diff) {
  5141. if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop))
  5142. { addToScrollTop(cm, diff) }
  5143. }
  5144. function addLineWidget(doc, handle, node, options) {
  5145. var widget = new LineWidget(doc, node, options)
  5146. var cm = doc.cm
  5147. if (cm && widget.noHScroll) { cm.display.alignWidgets = true }
  5148. changeLine(doc, handle, "widget", function (line) {
  5149. var widgets = line.widgets || (line.widgets = [])
  5150. if (widget.insertAt == null) { widgets.push(widget) }
  5151. else { widgets.splice(Math.min(widgets.length - 1, Math.max(0, widget.insertAt)), 0, widget) }
  5152. widget.line = line
  5153. if (cm && !lineIsHidden(doc, line)) {
  5154. var aboveVisible = heightAtLine(line) < doc.scrollTop
  5155. updateLineHeight(line, line.height + widgetHeight(widget))
  5156. if (aboveVisible) { addToScrollTop(cm, widget.height) }
  5157. cm.curOp.forceUpdate = true
  5158. }
  5159. return true
  5160. })
  5161. if (cm) { signalLater(cm, "lineWidgetAdded", cm, widget, typeof handle == "number" ? handle : lineNo(handle)) }
  5162. return widget
  5163. }
  5164. // TEXTMARKERS
  5165. // Created with markText and setBookmark methods. A TextMarker is a
  5166. // handle that can be used to clear or find a marked position in the
  5167. // document. Line objects hold arrays (markedSpans) containing
  5168. // {from, to, marker} object pointing to such marker objects, and
  5169. // indicating that such a marker is present on that line. Multiple
  5170. // lines may point to the same marker when it spans across lines.
  5171. // The spans will have null for their from/to properties when the
  5172. // marker continues beyond the start/end of the line. Markers have
  5173. // links back to the lines they currently touch.
  5174. // Collapsed markers have unique ids, in order to be able to order
  5175. // them, which is needed for uniquely determining an outer marker
  5176. // when they overlap (they may nest, but not partially overlap).
  5177. var nextMarkerId = 0
  5178. var TextMarker = function(doc, type) {
  5179. this.lines = []
  5180. this.type = type
  5181. this.doc = doc
  5182. this.id = ++nextMarkerId
  5183. };
  5184. // Clear the marker.
  5185. TextMarker.prototype.clear = function () {
  5186. var this$1 = this;
  5187. if (this.explicitlyCleared) { return }
  5188. var cm = this.doc.cm, withOp = cm && !cm.curOp
  5189. if (withOp) { startOperation(cm) }
  5190. if (hasHandler(this, "clear")) {
  5191. var found = this.find()
  5192. if (found) { signalLater(this, "clear", found.from, found.to) }
  5193. }
  5194. var min = null, max = null
  5195. for (var i = 0; i < this.lines.length; ++i) {
  5196. var line = this$1.lines[i]
  5197. var span = getMarkedSpanFor(line.markedSpans, this$1)
  5198. if (cm && !this$1.collapsed) { regLineChange(cm, lineNo(line), "text") }
  5199. else if (cm) {
  5200. if (span.to != null) { max = lineNo(line) }
  5201. if (span.from != null) { min = lineNo(line) }
  5202. }
  5203. line.markedSpans = removeMarkedSpan(line.markedSpans, span)
  5204. if (span.from == null && this$1.collapsed && !lineIsHidden(this$1.doc, line) && cm)
  5205. { updateLineHeight(line, textHeight(cm.display)) }
  5206. }
  5207. if (cm && this.collapsed && !cm.options.lineWrapping) { for (var i$1 = 0; i$1 < this.lines.length; ++i$1) {
  5208. var visual = visualLine(this$1.lines[i$1]), len = lineLength(visual)
  5209. if (len > cm.display.maxLineLength) {
  5210. cm.display.maxLine = visual
  5211. cm.display.maxLineLength = len
  5212. cm.display.maxLineChanged = true
  5213. }
  5214. } }
  5215. if (min != null && cm && this.collapsed) { regChange(cm, min, max + 1) }
  5216. this.lines.length = 0
  5217. this.explicitlyCleared = true
  5218. if (this.atomic && this.doc.cantEdit) {
  5219. this.doc.cantEdit = false
  5220. if (cm) { reCheckSelection(cm.doc) }
  5221. }
  5222. if (cm) { signalLater(cm, "markerCleared", cm, this, min, max) }
  5223. if (withOp) { endOperation(cm) }
  5224. if (this.parent) { this.parent.clear() }
  5225. };
  5226. // Find the position of the marker in the document. Returns a {from,
  5227. // to} object by default. Side can be passed to get a specific side
  5228. // -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the
  5229. // Pos objects returned contain a line object, rather than a line
  5230. // number (used to prevent looking up the same line twice).
  5231. TextMarker.prototype.find = function (side, lineObj) {
  5232. var this$1 = this;
  5233. if (side == null && this.type == "bookmark") { side = 1 }
  5234. var from, to
  5235. for (var i = 0; i < this.lines.length; ++i) {
  5236. var line = this$1.lines[i]
  5237. var span = getMarkedSpanFor(line.markedSpans, this$1)
  5238. if (span.from != null) {
  5239. from = Pos(lineObj ? line : lineNo(line), span.from)
  5240. if (side == -1) { return from }
  5241. }
  5242. if (span.to != null) {
  5243. to = Pos(lineObj ? line : lineNo(line), span.to)
  5244. if (side == 1) { return to }
  5245. }
  5246. }
  5247. return from && {from: from, to: to}
  5248. };
  5249. // Signals that the marker's widget changed, and surrounding layout
  5250. // should be recomputed.
  5251. TextMarker.prototype.changed = function () {
  5252. var this$1 = this;
  5253. var pos = this.find(-1, true), widget = this, cm = this.doc.cm
  5254. if (!pos || !cm) { return }
  5255. runInOp(cm, function () {
  5256. var line = pos.line, lineN = lineNo(pos.line)
  5257. var view = findViewForLine(cm, lineN)
  5258. if (view) {
  5259. clearLineMeasurementCacheFor(view)
  5260. cm.curOp.selectionChanged = cm.curOp.forceUpdate = true
  5261. }
  5262. cm.curOp.updateMaxLine = true
  5263. if (!lineIsHidden(widget.doc, line) && widget.height != null) {
  5264. var oldHeight = widget.height
  5265. widget.height = null
  5266. var dHeight = widgetHeight(widget) - oldHeight
  5267. if (dHeight)
  5268. { updateLineHeight(line, line.height + dHeight) }
  5269. }
  5270. signalLater(cm, "markerChanged", cm, this$1)
  5271. })
  5272. };
  5273. TextMarker.prototype.attachLine = function (line) {
  5274. if (!this.lines.length && this.doc.cm) {
  5275. var op = this.doc.cm.curOp
  5276. if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1)
  5277. { (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this) }
  5278. }
  5279. this.lines.push(line)
  5280. };
  5281. TextMarker.prototype.detachLine = function (line) {
  5282. this.lines.splice(indexOf(this.lines, line), 1)
  5283. if (!this.lines.length && this.doc.cm) {
  5284. var op = this.doc.cm.curOp
  5285. ;(op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this)
  5286. }
  5287. };
  5288. eventMixin(TextMarker)
  5289. // Create a marker, wire it up to the right lines, and
  5290. function markText(doc, from, to, options, type) {
  5291. // Shared markers (across linked documents) are handled separately
  5292. // (markTextShared will call out to this again, once per
  5293. // document).
  5294. if (options && options.shared) { return markTextShared(doc, from, to, options, type) }
  5295. // Ensure we are in an operation.
  5296. if (doc.cm && !doc.cm.curOp) { return operation(doc.cm, markText)(doc, from, to, options, type) }
  5297. var marker = new TextMarker(doc, type), diff = cmp(from, to)
  5298. if (options) { copyObj(options, marker, false) }
  5299. // Don't connect empty markers unless clearWhenEmpty is false
  5300. if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false)
  5301. { return marker }
  5302. if (marker.replacedWith) {
  5303. // Showing up as a widget implies collapsed (widget replaces text)
  5304. marker.collapsed = true
  5305. marker.widgetNode = eltP("span", [marker.replacedWith], "CodeMirror-widget")
  5306. if (!options.handleMouseEvents) { marker.widgetNode.setAttribute("cm-ignore-events", "true") }
  5307. if (options.insertLeft) { marker.widgetNode.insertLeft = true }
  5308. }
  5309. if (marker.collapsed) {
  5310. if (conflictingCollapsedRange(doc, from.line, from, to, marker) ||
  5311. from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker))
  5312. { throw new Error("Inserting collapsed marker partially overlapping an existing one") }
  5313. seeCollapsedSpans()
  5314. }
  5315. if (marker.addToHistory)
  5316. { addChangeToHistory(doc, {from: from, to: to, origin: "markText"}, doc.sel, NaN) }
  5317. var curLine = from.line, cm = doc.cm, updateMaxLine
  5318. doc.iter(curLine, to.line + 1, function (line) {
  5319. if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine)
  5320. { updateMaxLine = true }
  5321. if (marker.collapsed && curLine != from.line) { updateLineHeight(line, 0) }
  5322. addMarkedSpan(line, new MarkedSpan(marker,
  5323. curLine == from.line ? from.ch : null,
  5324. curLine == to.line ? to.ch : null))
  5325. ++curLine
  5326. })
  5327. // lineIsHidden depends on the presence of the spans, so needs a second pass
  5328. if (marker.collapsed) { doc.iter(from.line, to.line + 1, function (line) {
  5329. if (lineIsHidden(doc, line)) { updateLineHeight(line, 0) }
  5330. }) }
  5331. if (marker.clearOnEnter) { on(marker, "beforeCursorEnter", function () { return marker.clear(); }) }
  5332. if (marker.readOnly) {
  5333. seeReadOnlySpans()
  5334. if (doc.history.done.length || doc.history.undone.length)
  5335. { doc.clearHistory() }
  5336. }
  5337. if (marker.collapsed) {
  5338. marker.id = ++nextMarkerId
  5339. marker.atomic = true
  5340. }
  5341. if (cm) {
  5342. // Sync editor state
  5343. if (updateMaxLine) { cm.curOp.updateMaxLine = true }
  5344. if (marker.collapsed)
  5345. { regChange(cm, from.line, to.line + 1) }
  5346. else if (marker.className || marker.title || marker.startStyle || marker.endStyle || marker.css)
  5347. { for (var i = from.line; i <= to.line; i++) { regLineChange(cm, i, "text") } }
  5348. if (marker.atomic) { reCheckSelection(cm.doc) }
  5349. signalLater(cm, "markerAdded", cm, marker)
  5350. }
  5351. return marker
  5352. }
  5353. // SHARED TEXTMARKERS
  5354. // A shared marker spans multiple linked documents. It is
  5355. // implemented as a meta-marker-object controlling multiple normal
  5356. // markers.
  5357. var SharedTextMarker = function(markers, primary) {
  5358. var this$1 = this;
  5359. this.markers = markers
  5360. this.primary = primary
  5361. for (var i = 0; i < markers.length; ++i)
  5362. { markers[i].parent = this$1 }
  5363. };
  5364. SharedTextMarker.prototype.clear = function () {
  5365. var this$1 = this;
  5366. if (this.explicitlyCleared) { return }
  5367. this.explicitlyCleared = true
  5368. for (var i = 0; i < this.markers.length; ++i)
  5369. { this$1.markers[i].clear() }
  5370. signalLater(this, "clear")
  5371. };
  5372. SharedTextMarker.prototype.find = function (side, lineObj) {
  5373. return this.primary.find(side, lineObj)
  5374. };
  5375. eventMixin(SharedTextMarker)
  5376. function markTextShared(doc, from, to, options, type) {
  5377. options = copyObj(options)
  5378. options.shared = false
  5379. var markers = [markText(doc, from, to, options, type)], primary = markers[0]
  5380. var widget = options.widgetNode
  5381. linkedDocs(doc, function (doc) {
  5382. if (widget) { options.widgetNode = widget.cloneNode(true) }
  5383. markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type))
  5384. for (var i = 0; i < doc.linked.length; ++i)
  5385. { if (doc.linked[i].isParent) { return } }
  5386. primary = lst(markers)
  5387. })
  5388. return new SharedTextMarker(markers, primary)
  5389. }
  5390. function findSharedMarkers(doc) {
  5391. return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())), function (m) { return m.parent; })
  5392. }
  5393. function copySharedMarkers(doc, markers) {
  5394. for (var i = 0; i < markers.length; i++) {
  5395. var marker = markers[i], pos = marker.find()
  5396. var mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to)
  5397. if (cmp(mFrom, mTo)) {
  5398. var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type)
  5399. marker.markers.push(subMark)
  5400. subMark.parent = marker
  5401. }
  5402. }
  5403. }
  5404. function detachSharedMarkers(markers) {
  5405. var loop = function ( i ) {
  5406. var marker = markers[i], linked = [marker.primary.doc]
  5407. linkedDocs(marker.primary.doc, function (d) { return linked.push(d); })
  5408. for (var j = 0; j < marker.markers.length; j++) {
  5409. var subMarker = marker.markers[j]
  5410. if (indexOf(linked, subMarker.doc) == -1) {
  5411. subMarker.parent = null
  5412. marker.markers.splice(j--, 1)
  5413. }
  5414. }
  5415. };
  5416. for (var i = 0; i < markers.length; i++) loop( i );
  5417. }
  5418. var nextDocId = 0
  5419. var Doc = function(text, mode, firstLine, lineSep, direction) {
  5420. if (!(this instanceof Doc)) { return new Doc(text, mode, firstLine, lineSep, direction) }
  5421. if (firstLine == null) { firstLine = 0 }
  5422. BranchChunk.call(this, [new LeafChunk([new Line("", null)])])
  5423. this.first = firstLine
  5424. this.scrollTop = this.scrollLeft = 0
  5425. this.cantEdit = false
  5426. this.cleanGeneration = 1
  5427. this.modeFrontier = this.highlightFrontier = firstLine
  5428. var start = Pos(firstLine, 0)
  5429. this.sel = simpleSelection(start)
  5430. this.history = new History(null)
  5431. this.id = ++nextDocId
  5432. this.modeOption = mode
  5433. this.lineSep = lineSep
  5434. this.direction = (direction == "rtl") ? "rtl" : "ltr"
  5435. this.extend = false
  5436. if (typeof text == "string") { text = this.splitLines(text) }
  5437. updateDoc(this, {from: start, to: start, text: text})
  5438. setSelection(this, simpleSelection(start), sel_dontScroll)
  5439. }
  5440. Doc.prototype = createObj(BranchChunk.prototype, {
  5441. constructor: Doc,
  5442. // Iterate over the document. Supports two forms -- with only one
  5443. // argument, it calls that for each line in the document. With
  5444. // three, it iterates over the range given by the first two (with
  5445. // the second being non-inclusive).
  5446. iter: function(from, to, op) {
  5447. if (op) { this.iterN(from - this.first, to - from, op) }
  5448. else { this.iterN(this.first, this.first + this.size, from) }
  5449. },
  5450. // Non-public interface for adding and removing lines.
  5451. insert: function(at, lines) {
  5452. var height = 0
  5453. for (var i = 0; i < lines.length; ++i) { height += lines[i].height }
  5454. this.insertInner(at - this.first, lines, height)
  5455. },
  5456. remove: function(at, n) { this.removeInner(at - this.first, n) },
  5457. // From here, the methods are part of the public interface. Most
  5458. // are also available from CodeMirror (editor) instances.
  5459. getValue: function(lineSep) {
  5460. var lines = getLines(this, this.first, this.first + this.size)
  5461. if (lineSep === false) { return lines }
  5462. return lines.join(lineSep || this.lineSeparator())
  5463. },
  5464. setValue: docMethodOp(function(code) {
  5465. var top = Pos(this.first, 0), last = this.first + this.size - 1
  5466. makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length),
  5467. text: this.splitLines(code), origin: "setValue", full: true}, true)
  5468. if (this.cm) { scrollToCoords(this.cm, 0, 0) }
  5469. setSelection(this, simpleSelection(top), sel_dontScroll)
  5470. }),
  5471. replaceRange: function(code, from, to, origin) {
  5472. from = clipPos(this, from)
  5473. to = to ? clipPos(this, to) : from
  5474. replaceRange(this, code, from, to, origin)
  5475. },
  5476. getRange: function(from, to, lineSep) {
  5477. var lines = getBetween(this, clipPos(this, from), clipPos(this, to))
  5478. if (lineSep === false) { return lines }
  5479. return lines.join(lineSep || this.lineSeparator())
  5480. },
  5481. getLine: function(line) {var l = this.getLineHandle(line); return l && l.text},
  5482. getLineHandle: function(line) {if (isLine(this, line)) { return getLine(this, line) }},
  5483. getLineNumber: function(line) {return lineNo(line)},
  5484. getLineHandleVisualStart: function(line) {
  5485. if (typeof line == "number") { line = getLine(this, line) }
  5486. return visualLine(line)
  5487. },
  5488. lineCount: function() {return this.size},
  5489. firstLine: function() {return this.first},
  5490. lastLine: function() {return this.first + this.size - 1},
  5491. clipPos: function(pos) {return clipPos(this, pos)},
  5492. getCursor: function(start) {
  5493. var range = this.sel.primary(), pos
  5494. if (start == null || start == "head") { pos = range.head }
  5495. else if (start == "anchor") { pos = range.anchor }
  5496. else if (start == "end" || start == "to" || start === false) { pos = range.to() }
  5497. else { pos = range.from() }
  5498. return pos
  5499. },
  5500. listSelections: function() { return this.sel.ranges },
  5501. somethingSelected: function() {return this.sel.somethingSelected()},
  5502. setCursor: docMethodOp(function(line, ch, options) {
  5503. setSimpleSelection(this, clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line), null, options)
  5504. }),
  5505. setSelection: docMethodOp(function(anchor, head, options) {
  5506. setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options)
  5507. }),
  5508. extendSelection: docMethodOp(function(head, other, options) {
  5509. extendSelection(this, clipPos(this, head), other && clipPos(this, other), options)
  5510. }),
  5511. extendSelections: docMethodOp(function(heads, options) {
  5512. extendSelections(this, clipPosArray(this, heads), options)
  5513. }),
  5514. extendSelectionsBy: docMethodOp(function(f, options) {
  5515. var heads = map(this.sel.ranges, f)
  5516. extendSelections(this, clipPosArray(this, heads), options)
  5517. }),
  5518. setSelections: docMethodOp(function(ranges, primary, options) {
  5519. var this$1 = this;
  5520. if (!ranges.length) { return }
  5521. var out = []
  5522. for (var i = 0; i < ranges.length; i++)
  5523. { out[i] = new Range(clipPos(this$1, ranges[i].anchor),
  5524. clipPos(this$1, ranges[i].head)) }
  5525. if (primary == null) { primary = Math.min(ranges.length - 1, this.sel.primIndex) }
  5526. setSelection(this, normalizeSelection(out, primary), options)
  5527. }),
  5528. addSelection: docMethodOp(function(anchor, head, options) {
  5529. var ranges = this.sel.ranges.slice(0)
  5530. ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor)))
  5531. setSelection(this, normalizeSelection(ranges, ranges.length - 1), options)
  5532. }),
  5533. getSelection: function(lineSep) {
  5534. var this$1 = this;
  5535. var ranges = this.sel.ranges, lines
  5536. for (var i = 0; i < ranges.length; i++) {
  5537. var sel = getBetween(this$1, ranges[i].from(), ranges[i].to())
  5538. lines = lines ? lines.concat(sel) : sel
  5539. }
  5540. if (lineSep === false) { return lines }
  5541. else { return lines.join(lineSep || this.lineSeparator()) }
  5542. },
  5543. getSelections: function(lineSep) {
  5544. var this$1 = this;
  5545. var parts = [], ranges = this.sel.ranges
  5546. for (var i = 0; i < ranges.length; i++) {
  5547. var sel = getBetween(this$1, ranges[i].from(), ranges[i].to())
  5548. if (lineSep !== false) { sel = sel.join(lineSep || this$1.lineSeparator()) }
  5549. parts[i] = sel
  5550. }
  5551. return parts
  5552. },
  5553. replaceSelection: function(code, collapse, origin) {
  5554. var dup = []
  5555. for (var i = 0; i < this.sel.ranges.length; i++)
  5556. { dup[i] = code }
  5557. this.replaceSelections(dup, collapse, origin || "+input")
  5558. },
  5559. replaceSelections: docMethodOp(function(code, collapse, origin) {
  5560. var this$1 = this;
  5561. var changes = [], sel = this.sel
  5562. for (var i = 0; i < sel.ranges.length; i++) {
  5563. var range = sel.ranges[i]
  5564. changes[i] = {from: range.from(), to: range.to(), text: this$1.splitLines(code[i]), origin: origin}
  5565. }
  5566. var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse)
  5567. for (var i$1 = changes.length - 1; i$1 >= 0; i$1--)
  5568. { makeChange(this$1, changes[i$1]) }
  5569. if (newSel) { setSelectionReplaceHistory(this, newSel) }
  5570. else if (this.cm) { ensureCursorVisible(this.cm) }
  5571. }),
  5572. undo: docMethodOp(function() {makeChangeFromHistory(this, "undo")}),
  5573. redo: docMethodOp(function() {makeChangeFromHistory(this, "redo")}),
  5574. undoSelection: docMethodOp(function() {makeChangeFromHistory(this, "undo", true)}),
  5575. redoSelection: docMethodOp(function() {makeChangeFromHistory(this, "redo", true)}),
  5576. setExtending: function(val) {this.extend = val},
  5577. getExtending: function() {return this.extend},
  5578. historySize: function() {
  5579. var hist = this.history, done = 0, undone = 0
  5580. for (var i = 0; i < hist.done.length; i++) { if (!hist.done[i].ranges) { ++done } }
  5581. for (var i$1 = 0; i$1 < hist.undone.length; i$1++) { if (!hist.undone[i$1].ranges) { ++undone } }
  5582. return {undo: done, redo: undone}
  5583. },
  5584. clearHistory: function() {this.history = new History(this.history.maxGeneration)},
  5585. markClean: function() {
  5586. this.cleanGeneration = this.changeGeneration(true)
  5587. },
  5588. changeGeneration: function(forceSplit) {
  5589. if (forceSplit)
  5590. { this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null }
  5591. return this.history.generation
  5592. },
  5593. isClean: function (gen) {
  5594. return this.history.generation == (gen || this.cleanGeneration)
  5595. },
  5596. getHistory: function() {
  5597. return {done: copyHistoryArray(this.history.done),
  5598. undone: copyHistoryArray(this.history.undone)}
  5599. },
  5600. setHistory: function(histData) {
  5601. var hist = this.history = new History(this.history.maxGeneration)
  5602. hist.done = copyHistoryArray(histData.done.slice(0), null, true)
  5603. hist.undone = copyHistoryArray(histData.undone.slice(0), null, true)
  5604. },
  5605. setGutterMarker: docMethodOp(function(line, gutterID, value) {
  5606. return changeLine(this, line, "gutter", function (line) {
  5607. var markers = line.gutterMarkers || (line.gutterMarkers = {})
  5608. markers[gutterID] = value
  5609. if (!value && isEmpty(markers)) { line.gutterMarkers = null }
  5610. return true
  5611. })
  5612. }),
  5613. clearGutter: docMethodOp(function(gutterID) {
  5614. var this$1 = this;
  5615. this.iter(function (line) {
  5616. if (line.gutterMarkers && line.gutterMarkers[gutterID]) {
  5617. changeLine(this$1, line, "gutter", function () {
  5618. line.gutterMarkers[gutterID] = null
  5619. if (isEmpty(line.gutterMarkers)) { line.gutterMarkers = null }
  5620. return true
  5621. })
  5622. }
  5623. })
  5624. }),
  5625. lineInfo: function(line) {
  5626. var n
  5627. if (typeof line == "number") {
  5628. if (!isLine(this, line)) { return null }
  5629. n = line
  5630. line = getLine(this, line)
  5631. if (!line) { return null }
  5632. } else {
  5633. n = lineNo(line)
  5634. if (n == null) { return null }
  5635. }
  5636. return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers,
  5637. textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass,
  5638. widgets: line.widgets}
  5639. },
  5640. addLineClass: docMethodOp(function(handle, where, cls) {
  5641. return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) {
  5642. var prop = where == "text" ? "textClass"
  5643. : where == "background" ? "bgClass"
  5644. : where == "gutter" ? "gutterClass" : "wrapClass"
  5645. if (!line[prop]) { line[prop] = cls }
  5646. else if (classTest(cls).test(line[prop])) { return false }
  5647. else { line[prop] += " " + cls }
  5648. return true
  5649. })
  5650. }),
  5651. removeLineClass: docMethodOp(function(handle, where, cls) {
  5652. return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) {
  5653. var prop = where == "text" ? "textClass"
  5654. : where == "background" ? "bgClass"
  5655. : where == "gutter" ? "gutterClass" : "wrapClass"
  5656. var cur = line[prop]
  5657. if (!cur) { return false }
  5658. else if (cls == null) { line[prop] = null }
  5659. else {
  5660. var found = cur.match(classTest(cls))
  5661. if (!found) { return false }
  5662. var end = found.index + found[0].length
  5663. line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null
  5664. }
  5665. return true
  5666. })
  5667. }),
  5668. addLineWidget: docMethodOp(function(handle, node, options) {
  5669. return addLineWidget(this, handle, node, options)
  5670. }),
  5671. removeLineWidget: function(widget) { widget.clear() },
  5672. markText: function(from, to, options) {
  5673. return markText(this, clipPos(this, from), clipPos(this, to), options, options && options.type || "range")
  5674. },
  5675. setBookmark: function(pos, options) {
  5676. var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options),
  5677. insertLeft: options && options.insertLeft,
  5678. clearWhenEmpty: false, shared: options && options.shared,
  5679. handleMouseEvents: options && options.handleMouseEvents}
  5680. pos = clipPos(this, pos)
  5681. return markText(this, pos, pos, realOpts, "bookmark")
  5682. },
  5683. findMarksAt: function(pos) {
  5684. pos = clipPos(this, pos)
  5685. var markers = [], spans = getLine(this, pos.line).markedSpans
  5686. if (spans) { for (var i = 0; i < spans.length; ++i) {
  5687. var span = spans[i]
  5688. if ((span.from == null || span.from <= pos.ch) &&
  5689. (span.to == null || span.to >= pos.ch))
  5690. { markers.push(span.marker.parent || span.marker) }
  5691. } }
  5692. return markers
  5693. },
  5694. findMarks: function(from, to, filter) {
  5695. from = clipPos(this, from); to = clipPos(this, to)
  5696. var found = [], lineNo = from.line
  5697. this.iter(from.line, to.line + 1, function (line) {
  5698. var spans = line.markedSpans
  5699. if (spans) { for (var i = 0; i < spans.length; i++) {
  5700. var span = spans[i]
  5701. if (!(span.to != null && lineNo == from.line && from.ch >= span.to ||
  5702. span.from == null && lineNo != from.line ||
  5703. span.from != null && lineNo == to.line && span.from >= to.ch) &&
  5704. (!filter || filter(span.marker)))
  5705. { found.push(span.marker.parent || span.marker) }
  5706. } }
  5707. ++lineNo
  5708. })
  5709. return found
  5710. },
  5711. getAllMarks: function() {
  5712. var markers = []
  5713. this.iter(function (line) {
  5714. var sps = line.markedSpans
  5715. if (sps) { for (var i = 0; i < sps.length; ++i)
  5716. { if (sps[i].from != null) { markers.push(sps[i].marker) } } }
  5717. })
  5718. return markers
  5719. },
  5720. posFromIndex: function(off) {
  5721. var ch, lineNo = this.first, sepSize = this.lineSeparator().length
  5722. this.iter(function (line) {
  5723. var sz = line.text.length + sepSize
  5724. if (sz > off) { ch = off; return true }
  5725. off -= sz
  5726. ++lineNo
  5727. })
  5728. return clipPos(this, Pos(lineNo, ch))
  5729. },
  5730. indexFromPos: function (coords) {
  5731. coords = clipPos(this, coords)
  5732. var index = coords.ch
  5733. if (coords.line < this.first || coords.ch < 0) { return 0 }
  5734. var sepSize = this.lineSeparator().length
  5735. this.iter(this.first, coords.line, function (line) { // iter aborts when callback returns a truthy value
  5736. index += line.text.length + sepSize
  5737. })
  5738. return index
  5739. },
  5740. copy: function(copyHistory) {
  5741. var doc = new Doc(getLines(this, this.first, this.first + this.size),
  5742. this.modeOption, this.first, this.lineSep, this.direction)
  5743. doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft
  5744. doc.sel = this.sel
  5745. doc.extend = false
  5746. if (copyHistory) {
  5747. doc.history.undoDepth = this.history.undoDepth
  5748. doc.setHistory(this.getHistory())
  5749. }
  5750. return doc
  5751. },
  5752. linkedDoc: function(options) {
  5753. if (!options) { options = {} }
  5754. var from = this.first, to = this.first + this.size
  5755. if (options.from != null && options.from > from) { from = options.from }
  5756. if (options.to != null && options.to < to) { to = options.to }
  5757. var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from, this.lineSep, this.direction)
  5758. if (options.sharedHist) { copy.history = this.history
  5759. ; }(this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist})
  5760. copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}]
  5761. copySharedMarkers(copy, findSharedMarkers(this))
  5762. return copy
  5763. },
  5764. unlinkDoc: function(other) {
  5765. var this$1 = this;
  5766. if (other instanceof CodeMirror) { other = other.doc }
  5767. if (this.linked) { for (var i = 0; i < this.linked.length; ++i) {
  5768. var link = this$1.linked[i]
  5769. if (link.doc != other) { continue }
  5770. this$1.linked.splice(i, 1)
  5771. other.unlinkDoc(this$1)
  5772. detachSharedMarkers(findSharedMarkers(this$1))
  5773. break
  5774. } }
  5775. // If the histories were shared, split them again
  5776. if (other.history == this.history) {
  5777. var splitIds = [other.id]
  5778. linkedDocs(other, function (doc) { return splitIds.push(doc.id); }, true)
  5779. other.history = new History(null)
  5780. other.history.done = copyHistoryArray(this.history.done, splitIds)
  5781. other.history.undone = copyHistoryArray(this.history.undone, splitIds)
  5782. }
  5783. },
  5784. iterLinkedDocs: function(f) {linkedDocs(this, f)},
  5785. getMode: function() {return this.mode},
  5786. getEditor: function() {return this.cm},
  5787. splitLines: function(str) {
  5788. if (this.lineSep) { return str.split(this.lineSep) }
  5789. return splitLinesAuto(str)
  5790. },
  5791. lineSeparator: function() { return this.lineSep || "\n" },
  5792. setDirection: docMethodOp(function (dir) {
  5793. if (dir != "rtl") { dir = "ltr" }
  5794. if (dir == this.direction) { return }
  5795. this.direction = dir
  5796. this.iter(function (line) { return line.order = null; })
  5797. if (this.cm) { directionChanged(this.cm) }
  5798. })
  5799. })
  5800. // Public alias.
  5801. Doc.prototype.eachLine = Doc.prototype.iter
  5802. // Kludge to work around strange IE behavior where it'll sometimes
  5803. // re-fire a series of drag-related events right after the drop (#1551)
  5804. var lastDrop = 0
  5805. function onDrop(e) {
  5806. var cm = this
  5807. clearDragCursor(cm)
  5808. if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e))
  5809. { return }
  5810. e_preventDefault(e)
  5811. if (ie) { lastDrop = +new Date }
  5812. var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files
  5813. if (!pos || cm.isReadOnly()) { return }
  5814. // Might be a file drop, in which case we simply extract the text
  5815. // and insert it.
  5816. if (files && files.length && window.FileReader && window.File) {
  5817. var n = files.length, text = Array(n), read = 0
  5818. var loadFile = function (file, i) {
  5819. if (cm.options.allowDropFileTypes &&
  5820. indexOf(cm.options.allowDropFileTypes, file.type) == -1)
  5821. { return }
  5822. var reader = new FileReader
  5823. reader.onload = operation(cm, function () {
  5824. var content = reader.result
  5825. if (/[\x00-\x08\x0e-\x1f]{2}/.test(content)) { content = "" }
  5826. text[i] = content
  5827. if (++read == n) {
  5828. pos = clipPos(cm.doc, pos)
  5829. var change = {from: pos, to: pos,
  5830. text: cm.doc.splitLines(text.join(cm.doc.lineSeparator())),
  5831. origin: "paste"}
  5832. makeChange(cm.doc, change)
  5833. setSelectionReplaceHistory(cm.doc, simpleSelection(pos, changeEnd(change)))
  5834. }
  5835. })
  5836. reader.readAsText(file)
  5837. }
  5838. for (var i = 0; i < n; ++i) { loadFile(files[i], i) }
  5839. } else { // Normal drop
  5840. // Don't do a replace if the drop happened inside of the selected text.
  5841. if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) {
  5842. cm.state.draggingText(e)
  5843. // Ensure the editor is re-focused
  5844. setTimeout(function () { return cm.display.input.focus(); }, 20)
  5845. return
  5846. }
  5847. try {
  5848. var text$1 = e.dataTransfer.getData("Text")
  5849. if (text$1) {
  5850. var selected
  5851. if (cm.state.draggingText && !cm.state.draggingText.copy)
  5852. { selected = cm.listSelections() }
  5853. setSelectionNoUndo(cm.doc, simpleSelection(pos, pos))
  5854. if (selected) { for (var i$1 = 0; i$1 < selected.length; ++i$1)
  5855. { replaceRange(cm.doc, "", selected[i$1].anchor, selected[i$1].head, "drag") } }
  5856. cm.replaceSelection(text$1, "around", "paste")
  5857. cm.display.input.focus()
  5858. }
  5859. }
  5860. catch(e){}
  5861. }
  5862. }
  5863. function onDragStart(cm, e) {
  5864. if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return }
  5865. if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) { return }
  5866. e.dataTransfer.setData("Text", cm.getSelection())
  5867. e.dataTransfer.effectAllowed = "copyMove"
  5868. // Use dummy image instead of default browsers image.
  5869. // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there.
  5870. if (e.dataTransfer.setDragImage && !safari) {
  5871. var img = elt("img", null, null, "position: fixed; left: 0; top: 0;")
  5872. img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="
  5873. if (presto) {
  5874. img.width = img.height = 1
  5875. cm.display.wrapper.appendChild(img)
  5876. // Force a relayout, or Opera won't use our image for some obscure reason
  5877. img._top = img.offsetTop
  5878. }
  5879. e.dataTransfer.setDragImage(img, 0, 0)
  5880. if (presto) { img.parentNode.removeChild(img) }
  5881. }
  5882. }
  5883. function onDragOver(cm, e) {
  5884. var pos = posFromMouse(cm, e)
  5885. if (!pos) { return }
  5886. var frag = document.createDocumentFragment()
  5887. drawSelectionCursor(cm, pos, frag)
  5888. if (!cm.display.dragCursor) {
  5889. cm.display.dragCursor = elt("div", null, "CodeMirror-cursors CodeMirror-dragcursors")
  5890. cm.display.lineSpace.insertBefore(cm.display.dragCursor, cm.display.cursorDiv)
  5891. }
  5892. removeChildrenAndAdd(cm.display.dragCursor, frag)
  5893. }
  5894. function clearDragCursor(cm) {
  5895. if (cm.display.dragCursor) {
  5896. cm.display.lineSpace.removeChild(cm.display.dragCursor)
  5897. cm.display.dragCursor = null
  5898. }
  5899. }
  5900. // These must be handled carefully, because naively registering a
  5901. // handler for each editor will cause the editors to never be
  5902. // garbage collected.
  5903. function forEachCodeMirror(f) {
  5904. if (!document.getElementsByClassName) { return }
  5905. var byClass = document.getElementsByClassName("CodeMirror")
  5906. for (var i = 0; i < byClass.length; i++) {
  5907. var cm = byClass[i].CodeMirror
  5908. if (cm) { f(cm) }
  5909. }
  5910. }
  5911. var globalsRegistered = false
  5912. function ensureGlobalHandlers() {
  5913. if (globalsRegistered) { return }
  5914. registerGlobalHandlers()
  5915. globalsRegistered = true
  5916. }
  5917. function registerGlobalHandlers() {
  5918. // When the window resizes, we need to refresh active editors.
  5919. var resizeTimer
  5920. on(window, "resize", function () {
  5921. if (resizeTimer == null) { resizeTimer = setTimeout(function () {
  5922. resizeTimer = null
  5923. forEachCodeMirror(onResize)
  5924. }, 100) }
  5925. })
  5926. // When the window loses focus, we want to show the editor as blurred
  5927. on(window, "blur", function () { return forEachCodeMirror(onBlur); })
  5928. }
  5929. // Called when the window resizes
  5930. function onResize(cm) {
  5931. var d = cm.display
  5932. // Might be a text scaling operation, clear size caches.
  5933. d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null
  5934. d.scrollbarsClipped = false
  5935. cm.setSize()
  5936. }
  5937. var keyNames = {
  5938. 3: "Pause", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt",
  5939. 19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End",
  5940. 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert",
  5941. 46: "Delete", 59: ";", 61: "=", 91: "Mod", 92: "Mod", 93: "Mod",
  5942. 106: "*", 107: "=", 109: "-", 110: ".", 111: "/", 127: "Delete", 145: "ScrollLock",
  5943. 173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\",
  5944. 221: "]", 222: "'", 63232: "Up", 63233: "Down", 63234: "Left", 63235: "Right", 63272: "Delete",
  5945. 63273: "Home", 63275: "End", 63276: "PageUp", 63277: "PageDown", 63302: "Insert"
  5946. }
  5947. // Number keys
  5948. for (var i = 0; i < 10; i++) { keyNames[i + 48] = keyNames[i + 96] = String(i) }
  5949. // Alphabetic keys
  5950. for (var i$1 = 65; i$1 <= 90; i$1++) { keyNames[i$1] = String.fromCharCode(i$1) }
  5951. // Function keys
  5952. for (var i$2 = 1; i$2 <= 12; i$2++) { keyNames[i$2 + 111] = keyNames[i$2 + 63235] = "F" + i$2 }
  5953. var keyMap = {}
  5954. keyMap.basic = {
  5955. "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown",
  5956. "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown",
  5957. "Delete": "delCharAfter", "Backspace": "delCharBefore", "Shift-Backspace": "delCharBefore",
  5958. "Tab": "defaultTab", "Shift-Tab": "indentAuto",
  5959. "Enter": "newlineAndIndent", "Insert": "toggleOverwrite",
  5960. "Esc": "singleSelection"
  5961. }
  5962. // Note that the save and find-related commands aren't defined by
  5963. // default. User code or addons can define them. Unknown commands
  5964. // are simply ignored.
  5965. keyMap.pcDefault = {
  5966. "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo",
  5967. "Ctrl-Home": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Up": "goLineUp", "Ctrl-Down": "goLineDown",
  5968. "Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd",
  5969. "Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find",
  5970. "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll",
  5971. "Ctrl-[": "indentLess", "Ctrl-]": "indentMore",
  5972. "Ctrl-U": "undoSelection", "Shift-Ctrl-U": "redoSelection", "Alt-U": "redoSelection",
  5973. "fallthrough": "basic"
  5974. }
  5975. // Very basic readline/emacs-style bindings, which are standard on Mac.
  5976. keyMap.emacsy = {
  5977. "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown",
  5978. "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd",
  5979. "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp", "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore",
  5980. "Alt-D": "delWordAfter", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars",
  5981. "Ctrl-O": "openLine"
  5982. }
  5983. keyMap.macDefault = {
  5984. "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo",
  5985. "Cmd-Home": "goDocStart", "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft",
  5986. "Alt-Right": "goGroupRight", "Cmd-Left": "goLineLeft", "Cmd-Right": "goLineRight", "Alt-Backspace": "delGroupBefore",
  5987. "Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find",
  5988. "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll",
  5989. "Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delWrappedLineLeft", "Cmd-Delete": "delWrappedLineRight",
  5990. "Cmd-U": "undoSelection", "Shift-Cmd-U": "redoSelection", "Ctrl-Up": "goDocStart", "Ctrl-Down": "goDocEnd",
  5991. "fallthrough": ["basic", "emacsy"]
  5992. }
  5993. keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault
  5994. // KEYMAP DISPATCH
  5995. function normalizeKeyName(name) {
  5996. var parts = name.split(/-(?!$)/)
  5997. name = parts[parts.length - 1]
  5998. var alt, ctrl, shift, cmd
  5999. for (var i = 0; i < parts.length - 1; i++) {
  6000. var mod = parts[i]
  6001. if (/^(cmd|meta|m)$/i.test(mod)) { cmd = true }
  6002. else if (/^a(lt)?$/i.test(mod)) { alt = true }
  6003. else if (/^(c|ctrl|control)$/i.test(mod)) { ctrl = true }
  6004. else if (/^s(hift)?$/i.test(mod)) { shift = true }
  6005. else { throw new Error("Unrecognized modifier name: " + mod) }
  6006. }
  6007. if (alt) { name = "Alt-" + name }
  6008. if (ctrl) { name = "Ctrl-" + name }
  6009. if (cmd) { name = "Cmd-" + name }
  6010. if (shift) { name = "Shift-" + name }
  6011. return name
  6012. }
  6013. // This is a kludge to keep keymaps mostly working as raw objects
  6014. // (backwards compatibility) while at the same time support features
  6015. // like normalization and multi-stroke key bindings. It compiles a
  6016. // new normalized keymap, and then updates the old object to reflect
  6017. // this.
  6018. function normalizeKeyMap(keymap) {
  6019. var copy = {}
  6020. for (var keyname in keymap) { if (keymap.hasOwnProperty(keyname)) {
  6021. var value = keymap[keyname]
  6022. if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) { continue }
  6023. if (value == "...") { delete keymap[keyname]; continue }
  6024. var keys = map(keyname.split(" "), normalizeKeyName)
  6025. for (var i = 0; i < keys.length; i++) {
  6026. var val = (void 0), name = (void 0)
  6027. if (i == keys.length - 1) {
  6028. name = keys.join(" ")
  6029. val = value
  6030. } else {
  6031. name = keys.slice(0, i + 1).join(" ")
  6032. val = "..."
  6033. }
  6034. var prev = copy[name]
  6035. if (!prev) { copy[name] = val }
  6036. else if (prev != val) { throw new Error("Inconsistent bindings for " + name) }
  6037. }
  6038. delete keymap[keyname]
  6039. } }
  6040. for (var prop in copy) { keymap[prop] = copy[prop] }
  6041. return keymap
  6042. }
  6043. function lookupKey(key, map, handle, context) {
  6044. map = getKeyMap(map)
  6045. var found = map.call ? map.call(key, context) : map[key]
  6046. if (found === false) { return "nothing" }
  6047. if (found === "...") { return "multi" }
  6048. if (found != null && handle(found)) { return "handled" }
  6049. if (map.fallthrough) {
  6050. if (Object.prototype.toString.call(map.fallthrough) != "[object Array]")
  6051. { return lookupKey(key, map.fallthrough, handle, context) }
  6052. for (var i = 0; i < map.fallthrough.length; i++) {
  6053. var result = lookupKey(key, map.fallthrough[i], handle, context)
  6054. if (result) { return result }
  6055. }
  6056. }
  6057. }
  6058. // Modifier key presses don't count as 'real' key presses for the
  6059. // purpose of keymap fallthrough.
  6060. function isModifierKey(value) {
  6061. var name = typeof value == "string" ? value : keyNames[value.keyCode]
  6062. return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod"
  6063. }
  6064. function addModifierNames(name, event, noShift) {
  6065. var base = name
  6066. if (event.altKey && base != "Alt") { name = "Alt-" + name }
  6067. if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != "Ctrl") { name = "Ctrl-" + name }
  6068. if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != "Cmd") { name = "Cmd-" + name }
  6069. if (!noShift && event.shiftKey && base != "Shift") { name = "Shift-" + name }
  6070. return name
  6071. }
  6072. // Look up the name of a key as indicated by an event object.
  6073. function keyName(event, noShift) {
  6074. if (presto && event.keyCode == 34 && event["char"]) { return false }
  6075. var name = keyNames[event.keyCode]
  6076. if (name == null || event.altGraphKey) { return false }
  6077. // Ctrl-ScrollLock has keyCode 3, same as Ctrl-Pause,
  6078. // so we'll use event.code when available (Chrome 48+, FF 38+, Safari 10.1+)
  6079. if (event.keyCode == 3 && event.code) { name = event.code }
  6080. return addModifierNames(name, event, noShift)
  6081. }
  6082. function getKeyMap(val) {
  6083. return typeof val == "string" ? keyMap[val] : val
  6084. }
  6085. // Helper for deleting text near the selection(s), used to implement
  6086. // backspace, delete, and similar functionality.
  6087. function deleteNearSelection(cm, compute) {
  6088. var ranges = cm.doc.sel.ranges, kill = []
  6089. // Build up a set of ranges to kill first, merging overlapping
  6090. // ranges.
  6091. for (var i = 0; i < ranges.length; i++) {
  6092. var toKill = compute(ranges[i])
  6093. while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) {
  6094. var replaced = kill.pop()
  6095. if (cmp(replaced.from, toKill.from) < 0) {
  6096. toKill.from = replaced.from
  6097. break
  6098. }
  6099. }
  6100. kill.push(toKill)
  6101. }
  6102. // Next, remove those actual ranges.
  6103. runInOp(cm, function () {
  6104. for (var i = kill.length - 1; i >= 0; i--)
  6105. { replaceRange(cm.doc, "", kill[i].from, kill[i].to, "+delete") }
  6106. ensureCursorVisible(cm)
  6107. })
  6108. }
  6109. function moveCharLogically(line, ch, dir) {
  6110. var target = skipExtendingChars(line.text, ch + dir, dir)
  6111. return target < 0 || target > line.text.length ? null : target
  6112. }
  6113. function moveLogically(line, start, dir) {
  6114. var ch = moveCharLogically(line, start.ch, dir)
  6115. return ch == null ? null : new Pos(start.line, ch, dir < 0 ? "after" : "before")
  6116. }
  6117. function endOfLine(visually, cm, lineObj, lineNo, dir) {
  6118. if (visually) {
  6119. var order = getOrder(lineObj, cm.doc.direction)
  6120. if (order) {
  6121. var part = dir < 0 ? lst(order) : order[0]
  6122. var moveInStorageOrder = (dir < 0) == (part.level == 1)
  6123. var sticky = moveInStorageOrder ? "after" : "before"
  6124. var ch
  6125. // With a wrapped rtl chunk (possibly spanning multiple bidi parts),
  6126. // it could be that the last bidi part is not on the last visual line,
  6127. // since visual lines contain content order-consecutive chunks.
  6128. // Thus, in rtl, we are looking for the first (content-order) character
  6129. // in the rtl chunk that is on the last line (that is, the same line
  6130. // as the last (content-order) character).
  6131. if (part.level > 0 || cm.doc.direction == "rtl") {
  6132. var prep = prepareMeasureForLine(cm, lineObj)
  6133. ch = dir < 0 ? lineObj.text.length - 1 : 0
  6134. var targetTop = measureCharPrepared(cm, prep, ch).top
  6135. ch = findFirst(function (ch) { return measureCharPrepared(cm, prep, ch).top == targetTop; }, (dir < 0) == (part.level == 1) ? part.from : part.to - 1, ch)
  6136. if (sticky == "before") { ch = moveCharLogically(lineObj, ch, 1) }
  6137. } else { ch = dir < 0 ? part.to : part.from }
  6138. return new Pos(lineNo, ch, sticky)
  6139. }
  6140. }
  6141. return new Pos(lineNo, dir < 0 ? lineObj.text.length : 0, dir < 0 ? "before" : "after")
  6142. }
  6143. function moveVisually(cm, line, start, dir) {
  6144. var bidi = getOrder(line, cm.doc.direction)
  6145. if (!bidi) { return moveLogically(line, start, dir) }
  6146. if (start.ch >= line.text.length) {
  6147. start.ch = line.text.length
  6148. start.sticky = "before"
  6149. } else if (start.ch <= 0) {
  6150. start.ch = 0
  6151. start.sticky = "after"
  6152. }
  6153. var partPos = getBidiPartAt(bidi, start.ch, start.sticky), part = bidi[partPos]
  6154. if (cm.doc.direction == "ltr" && part.level % 2 == 0 && (dir > 0 ? part.to > start.ch : part.from < start.ch)) {
  6155. // Case 1: We move within an ltr part in an ltr editor. Even with wrapped lines,
  6156. // nothing interesting happens.
  6157. return moveLogically(line, start, dir)
  6158. }
  6159. var mv = function (pos, dir) { return moveCharLogically(line, pos instanceof Pos ? pos.ch : pos, dir); }
  6160. var prep
  6161. var getWrappedLineExtent = function (ch) {
  6162. if (!cm.options.lineWrapping) { return {begin: 0, end: line.text.length} }
  6163. prep = prep || prepareMeasureForLine(cm, line)
  6164. return wrappedLineExtentChar(cm, line, prep, ch)
  6165. }
  6166. var wrappedLineExtent = getWrappedLineExtent(start.sticky == "before" ? mv(start, -1) : start.ch)
  6167. if (cm.doc.direction == "rtl" || part.level == 1) {
  6168. var moveInStorageOrder = (part.level == 1) == (dir < 0)
  6169. var ch = mv(start, moveInStorageOrder ? 1 : -1)
  6170. if (ch != null && (!moveInStorageOrder ? ch >= part.from && ch >= wrappedLineExtent.begin : ch <= part.to && ch <= wrappedLineExtent.end)) {
  6171. // Case 2: We move within an rtl part or in an rtl editor on the same visual line
  6172. var sticky = moveInStorageOrder ? "before" : "after"
  6173. return new Pos(start.line, ch, sticky)
  6174. }
  6175. }
  6176. // Case 3: Could not move within this bidi part in this visual line, so leave
  6177. // the current bidi part
  6178. var searchInVisualLine = function (partPos, dir, wrappedLineExtent) {
  6179. var getRes = function (ch, moveInStorageOrder) { return moveInStorageOrder
  6180. ? new Pos(start.line, mv(ch, 1), "before")
  6181. : new Pos(start.line, ch, "after"); }
  6182. for (; partPos >= 0 && partPos < bidi.length; partPos += dir) {
  6183. var part = bidi[partPos]
  6184. var moveInStorageOrder = (dir > 0) == (part.level != 1)
  6185. var ch = moveInStorageOrder ? wrappedLineExtent.begin : mv(wrappedLineExtent.end, -1)
  6186. if (part.from <= ch && ch < part.to) { return getRes(ch, moveInStorageOrder) }
  6187. ch = moveInStorageOrder ? part.from : mv(part.to, -1)
  6188. if (wrappedLineExtent.begin <= ch && ch < wrappedLineExtent.end) { return getRes(ch, moveInStorageOrder) }
  6189. }
  6190. }
  6191. // Case 3a: Look for other bidi parts on the same visual line
  6192. var res = searchInVisualLine(partPos + dir, dir, wrappedLineExtent)
  6193. if (res) { return res }
  6194. // Case 3b: Look for other bidi parts on the next visual line
  6195. var nextCh = dir > 0 ? wrappedLineExtent.end : mv(wrappedLineExtent.begin, -1)
  6196. if (nextCh != null && !(dir > 0 && nextCh == line.text.length)) {
  6197. res = searchInVisualLine(dir > 0 ? 0 : bidi.length - 1, dir, getWrappedLineExtent(nextCh))
  6198. if (res) { return res }
  6199. }
  6200. // Case 4: Nowhere to move
  6201. return null
  6202. }
  6203. // Commands are parameter-less actions that can be performed on an
  6204. // editor, mostly used for keybindings.
  6205. var commands = {
  6206. selectAll: selectAll,
  6207. singleSelection: function (cm) { return cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll); },
  6208. killLine: function (cm) { return deleteNearSelection(cm, function (range) {
  6209. if (range.empty()) {
  6210. var len = getLine(cm.doc, range.head.line).text.length
  6211. if (range.head.ch == len && range.head.line < cm.lastLine())
  6212. { return {from: range.head, to: Pos(range.head.line + 1, 0)} }
  6213. else
  6214. { return {from: range.head, to: Pos(range.head.line, len)} }
  6215. } else {
  6216. return {from: range.from(), to: range.to()}
  6217. }
  6218. }); },
  6219. deleteLine: function (cm) { return deleteNearSelection(cm, function (range) { return ({
  6220. from: Pos(range.from().line, 0),
  6221. to: clipPos(cm.doc, Pos(range.to().line + 1, 0))
  6222. }); }); },
  6223. delLineLeft: function (cm) { return deleteNearSelection(cm, function (range) { return ({
  6224. from: Pos(range.from().line, 0), to: range.from()
  6225. }); }); },
  6226. delWrappedLineLeft: function (cm) { return deleteNearSelection(cm, function (range) {
  6227. var top = cm.charCoords(range.head, "div").top + 5
  6228. var leftPos = cm.coordsChar({left: 0, top: top}, "div")
  6229. return {from: leftPos, to: range.from()}
  6230. }); },
  6231. delWrappedLineRight: function (cm) { return deleteNearSelection(cm, function (range) {
  6232. var top = cm.charCoords(range.head, "div").top + 5
  6233. var rightPos = cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div")
  6234. return {from: range.from(), to: rightPos }
  6235. }); },
  6236. undo: function (cm) { return cm.undo(); },
  6237. redo: function (cm) { return cm.redo(); },
  6238. undoSelection: function (cm) { return cm.undoSelection(); },
  6239. redoSelection: function (cm) { return cm.redoSelection(); },
  6240. goDocStart: function (cm) { return cm.extendSelection(Pos(cm.firstLine(), 0)); },
  6241. goDocEnd: function (cm) { return cm.extendSelection(Pos(cm.lastLine())); },
  6242. goLineStart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStart(cm, range.head.line); },
  6243. {origin: "+move", bias: 1}
  6244. ); },
  6245. goLineStartSmart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStartSmart(cm, range.head); },
  6246. {origin: "+move", bias: 1}
  6247. ); },
  6248. goLineEnd: function (cm) { return cm.extendSelectionsBy(function (range) { return lineEnd(cm, range.head.line); },
  6249. {origin: "+move", bias: -1}
  6250. ); },
  6251. goLineRight: function (cm) { return cm.extendSelectionsBy(function (range) {
  6252. var top = cm.cursorCoords(range.head, "div").top + 5
  6253. return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div")
  6254. }, sel_move); },
  6255. goLineLeft: function (cm) { return cm.extendSelectionsBy(function (range) {
  6256. var top = cm.cursorCoords(range.head, "div").top + 5
  6257. return cm.coordsChar({left: 0, top: top}, "div")
  6258. }, sel_move); },
  6259. goLineLeftSmart: function (cm) { return cm.extendSelectionsBy(function (range) {
  6260. var top = cm.cursorCoords(range.head, "div").top + 5
  6261. var pos = cm.coordsChar({left: 0, top: top}, "div")
  6262. if (pos.ch < cm.getLine(pos.line).search(/\S/)) { return lineStartSmart(cm, range.head) }
  6263. return pos
  6264. }, sel_move); },
  6265. goLineUp: function (cm) { return cm.moveV(-1, "line"); },
  6266. goLineDown: function (cm) { return cm.moveV(1, "line"); },
  6267. goPageUp: function (cm) { return cm.moveV(-1, "page"); },
  6268. goPageDown: function (cm) { return cm.moveV(1, "page"); },
  6269. goCharLeft: function (cm) { return cm.moveH(-1, "char"); },
  6270. goCharRight: function (cm) { return cm.moveH(1, "char"); },
  6271. goColumnLeft: function (cm) { return cm.moveH(-1, "column"); },
  6272. goColumnRight: function (cm) { return cm.moveH(1, "column"); },
  6273. goWordLeft: function (cm) { return cm.moveH(-1, "word"); },
  6274. goGroupRight: function (cm) { return cm.moveH(1, "group"); },
  6275. goGroupLeft: function (cm) { return cm.moveH(-1, "group"); },
  6276. goWordRight: function (cm) { return cm.moveH(1, "word"); },
  6277. delCharBefore: function (cm) { return cm.deleteH(-1, "char"); },
  6278. delCharAfter: function (cm) { return cm.deleteH(1, "char"); },
  6279. delWordBefore: function (cm) { return cm.deleteH(-1, "word"); },
  6280. delWordAfter: function (cm) { return cm.deleteH(1, "word"); },
  6281. delGroupBefore: function (cm) { return cm.deleteH(-1, "group"); },
  6282. delGroupAfter: function (cm) { return cm.deleteH(1, "group"); },
  6283. indentAuto: function (cm) { return cm.indentSelection("smart"); },
  6284. indentMore: function (cm) { return cm.indentSelection("add"); },
  6285. indentLess: function (cm) { return cm.indentSelection("subtract"); },
  6286. insertTab: function (cm) { return cm.replaceSelection("\t"); },
  6287. insertSoftTab: function (cm) {
  6288. var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize
  6289. for (var i = 0; i < ranges.length; i++) {
  6290. var pos = ranges[i].from()
  6291. var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize)
  6292. spaces.push(spaceStr(tabSize - col % tabSize))
  6293. }
  6294. cm.replaceSelections(spaces)
  6295. },
  6296. defaultTab: function (cm) {
  6297. if (cm.somethingSelected()) { cm.indentSelection("add") }
  6298. else { cm.execCommand("insertTab") }
  6299. },
  6300. // Swap the two chars left and right of each selection's head.
  6301. // Move cursor behind the two swapped characters afterwards.
  6302. //
  6303. // Doesn't consider line feeds a character.
  6304. // Doesn't scan more than one line above to find a character.
  6305. // Doesn't do anything on an empty line.
  6306. // Doesn't do anything with non-empty selections.
  6307. transposeChars: function (cm) { return runInOp(cm, function () {
  6308. var ranges = cm.listSelections(), newSel = []
  6309. for (var i = 0; i < ranges.length; i++) {
  6310. if (!ranges[i].empty()) { continue }
  6311. var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text
  6312. if (line) {
  6313. if (cur.ch == line.length) { cur = new Pos(cur.line, cur.ch - 1) }
  6314. if (cur.ch > 0) {
  6315. cur = new Pos(cur.line, cur.ch + 1)
  6316. cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2),
  6317. Pos(cur.line, cur.ch - 2), cur, "+transpose")
  6318. } else if (cur.line > cm.doc.first) {
  6319. var prev = getLine(cm.doc, cur.line - 1).text
  6320. if (prev) {
  6321. cur = new Pos(cur.line, 1)
  6322. cm.replaceRange(line.charAt(0) + cm.doc.lineSeparator() +
  6323. prev.charAt(prev.length - 1),
  6324. Pos(cur.line - 1, prev.length - 1), cur, "+transpose")
  6325. }
  6326. }
  6327. }
  6328. newSel.push(new Range(cur, cur))
  6329. }
  6330. cm.setSelections(newSel)
  6331. }); },
  6332. newlineAndIndent: function (cm) { return runInOp(cm, function () {
  6333. var sels = cm.listSelections()
  6334. for (var i = sels.length - 1; i >= 0; i--)
  6335. { cm.replaceRange(cm.doc.lineSeparator(), sels[i].anchor, sels[i].head, "+input") }
  6336. sels = cm.listSelections()
  6337. for (var i$1 = 0; i$1 < sels.length; i$1++)
  6338. { cm.indentLine(sels[i$1].from().line, null, true) }
  6339. ensureCursorVisible(cm)
  6340. }); },
  6341. openLine: function (cm) { return cm.replaceSelection("\n", "start"); },
  6342. toggleOverwrite: function (cm) { return cm.toggleOverwrite(); }
  6343. }
  6344. function lineStart(cm, lineN) {
  6345. var line = getLine(cm.doc, lineN)
  6346. var visual = visualLine(line)
  6347. if (visual != line) { lineN = lineNo(visual) }
  6348. return endOfLine(true, cm, visual, lineN, 1)
  6349. }
  6350. function lineEnd(cm, lineN) {
  6351. var line = getLine(cm.doc, lineN)
  6352. var visual = visualLineEnd(line)
  6353. if (visual != line) { lineN = lineNo(visual) }
  6354. return endOfLine(true, cm, line, lineN, -1)
  6355. }
  6356. function lineStartSmart(cm, pos) {
  6357. var start = lineStart(cm, pos.line)
  6358. var line = getLine(cm.doc, start.line)
  6359. var order = getOrder(line, cm.doc.direction)
  6360. if (!order || order[0].level == 0) {
  6361. var firstNonWS = Math.max(0, line.text.search(/\S/))
  6362. var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch
  6363. return Pos(start.line, inWS ? 0 : firstNonWS, start.sticky)
  6364. }
  6365. return start
  6366. }
  6367. // Run a handler that was bound to a key.
  6368. function doHandleBinding(cm, bound, dropShift) {
  6369. if (typeof bound == "string") {
  6370. bound = commands[bound]
  6371. if (!bound) { return false }
  6372. }
  6373. // Ensure previous input has been read, so that the handler sees a
  6374. // consistent view of the document
  6375. cm.display.input.ensurePolled()
  6376. var prevShift = cm.display.shift, done = false
  6377. try {
  6378. if (cm.isReadOnly()) { cm.state.suppressEdits = true }
  6379. if (dropShift) { cm.display.shift = false }
  6380. done = bound(cm) != Pass
  6381. } finally {
  6382. cm.display.shift = prevShift
  6383. cm.state.suppressEdits = false
  6384. }
  6385. return done
  6386. }
  6387. function lookupKeyForEditor(cm, name, handle) {
  6388. for (var i = 0; i < cm.state.keyMaps.length; i++) {
  6389. var result = lookupKey(name, cm.state.keyMaps[i], handle, cm)
  6390. if (result) { return result }
  6391. }
  6392. return (cm.options.extraKeys && lookupKey(name, cm.options.extraKeys, handle, cm))
  6393. || lookupKey(name, cm.options.keyMap, handle, cm)
  6394. }
  6395. // Note that, despite the name, this function is also used to check
  6396. // for bound mouse clicks.
  6397. var stopSeq = new Delayed
  6398. function dispatchKey(cm, name, e, handle) {
  6399. var seq = cm.state.keySeq
  6400. if (seq) {
  6401. if (isModifierKey(name)) { return "handled" }
  6402. if (/\'$/.test(name))
  6403. { cm.state.keySeq = null }
  6404. else
  6405. { stopSeq.set(50, function () {
  6406. if (cm.state.keySeq == seq) {
  6407. cm.state.keySeq = null
  6408. cm.display.input.reset()
  6409. }
  6410. }) }
  6411. if (dispatchKeyInner(cm, seq + " " + name, e, handle)) { return true }
  6412. }
  6413. return dispatchKeyInner(cm, name, e, handle)
  6414. }
  6415. function dispatchKeyInner(cm, name, e, handle) {
  6416. var result = lookupKeyForEditor(cm, name, handle)
  6417. if (result == "multi")
  6418. { cm.state.keySeq = name }
  6419. if (result == "handled")
  6420. { signalLater(cm, "keyHandled", cm, name, e) }
  6421. if (result == "handled" || result == "multi") {
  6422. e_preventDefault(e)
  6423. restartBlink(cm)
  6424. }
  6425. return !!result
  6426. }
  6427. // Handle a key from the keydown event.
  6428. function handleKeyBinding(cm, e) {
  6429. var name = keyName(e, true)
  6430. if (!name) { return false }
  6431. if (e.shiftKey && !cm.state.keySeq) {
  6432. // First try to resolve full name (including 'Shift-'). Failing
  6433. // that, see if there is a cursor-motion command (starting with
  6434. // 'go') bound to the keyname without 'Shift-'.
  6435. return dispatchKey(cm, "Shift-" + name, e, function (b) { return doHandleBinding(cm, b, true); })
  6436. || dispatchKey(cm, name, e, function (b) {
  6437. if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion)
  6438. { return doHandleBinding(cm, b) }
  6439. })
  6440. } else {
  6441. return dispatchKey(cm, name, e, function (b) { return doHandleBinding(cm, b); })
  6442. }
  6443. }
  6444. // Handle a key from the keypress event
  6445. function handleCharBinding(cm, e, ch) {
  6446. return dispatchKey(cm, "'" + ch + "'", e, function (b) { return doHandleBinding(cm, b, true); })
  6447. }
  6448. var lastStoppedKey = null
  6449. function onKeyDown(e) {
  6450. var cm = this
  6451. cm.curOp.focus = activeElt()
  6452. if (signalDOMEvent(cm, e)) { return }
  6453. // IE does strange things with escape.
  6454. if (ie && ie_version < 11 && e.keyCode == 27) { e.returnValue = false }
  6455. var code = e.keyCode
  6456. cm.display.shift = code == 16 || e.shiftKey
  6457. var handled = handleKeyBinding(cm, e)
  6458. if (presto) {
  6459. lastStoppedKey = handled ? code : null
  6460. // Opera has no cut event... we try to at least catch the key combo
  6461. if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey))
  6462. { cm.replaceSelection("", null, "cut") }
  6463. }
  6464. // Turn mouse into crosshair when Alt is held on Mac.
  6465. if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className))
  6466. { showCrossHair(cm) }
  6467. }
  6468. function showCrossHair(cm) {
  6469. var lineDiv = cm.display.lineDiv
  6470. addClass(lineDiv, "CodeMirror-crosshair")
  6471. function up(e) {
  6472. if (e.keyCode == 18 || !e.altKey) {
  6473. rmClass(lineDiv, "CodeMirror-crosshair")
  6474. off(document, "keyup", up)
  6475. off(document, "mouseover", up)
  6476. }
  6477. }
  6478. on(document, "keyup", up)
  6479. on(document, "mouseover", up)
  6480. }
  6481. function onKeyUp(e) {
  6482. if (e.keyCode == 16) { this.doc.sel.shift = false }
  6483. signalDOMEvent(this, e)
  6484. }
  6485. function onKeyPress(e) {
  6486. var cm = this
  6487. if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) { return }
  6488. var keyCode = e.keyCode, charCode = e.charCode
  6489. if (presto && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return}
  6490. if ((presto && (!e.which || e.which < 10)) && handleKeyBinding(cm, e)) { return }
  6491. var ch = String.fromCharCode(charCode == null ? keyCode : charCode)
  6492. // Some browsers fire keypress events for backspace
  6493. if (ch == "\x08") { return }
  6494. if (handleCharBinding(cm, e, ch)) { return }
  6495. cm.display.input.onKeyPress(e)
  6496. }
  6497. var DOUBLECLICK_DELAY = 400
  6498. var PastClick = function(time, pos, button) {
  6499. this.time = time
  6500. this.pos = pos
  6501. this.button = button
  6502. };
  6503. PastClick.prototype.compare = function (time, pos, button) {
  6504. return this.time + DOUBLECLICK_DELAY > time &&
  6505. cmp(pos, this.pos) == 0 && button == this.button
  6506. };
  6507. var lastClick;
  6508. var lastDoubleClick;
  6509. function clickRepeat(pos, button) {
  6510. var now = +new Date
  6511. if (lastDoubleClick && lastDoubleClick.compare(now, pos, button)) {
  6512. lastClick = lastDoubleClick = null
  6513. return "triple"
  6514. } else if (lastClick && lastClick.compare(now, pos, button)) {
  6515. lastDoubleClick = new PastClick(now, pos, button)
  6516. lastClick = null
  6517. return "double"
  6518. } else {
  6519. lastClick = new PastClick(now, pos, button)
  6520. lastDoubleClick = null
  6521. return "single"
  6522. }
  6523. }
  6524. // A mouse down can be a single click, double click, triple click,
  6525. // start of selection drag, start of text drag, new cursor
  6526. // (ctrl-click), rectangle drag (alt-drag), or xwin
  6527. // middle-click-paste. Or it might be a click on something we should
  6528. // not interfere with, such as a scrollbar or widget.
  6529. function onMouseDown(e) {
  6530. var cm = this, display = cm.display
  6531. if (signalDOMEvent(cm, e) || display.activeTouch && display.input.supportsTouch()) { return }
  6532. display.input.ensurePolled()
  6533. display.shift = e.shiftKey
  6534. if (eventInWidget(display, e)) {
  6535. if (!webkit) {
  6536. // Briefly turn off draggability, to allow widgets to do
  6537. // normal dragging things.
  6538. display.scroller.draggable = false
  6539. setTimeout(function () { return display.scroller.draggable = true; }, 100)
  6540. }
  6541. return
  6542. }
  6543. var button = e_button(e)
  6544. if (button == 3 && captureRightClick ? contextMenuInGutter(cm, e) : clickInGutter(cm, e)) { return }
  6545. var pos = posFromMouse(cm, e), repeat = pos ? clickRepeat(pos, button) : "single"
  6546. window.focus()
  6547. // #3261: make sure, that we're not starting a second selection
  6548. if (button == 1 && cm.state.selectingText)
  6549. { cm.state.selectingText(e) }
  6550. if (pos && handleMappedButton(cm, button, pos, repeat, e)) { return }
  6551. if (button == 1) {
  6552. if (pos) { leftButtonDown(cm, pos, repeat, e) }
  6553. else if (e_target(e) == display.scroller) { e_preventDefault(e) }
  6554. } else if (button == 2) {
  6555. if (pos) { extendSelection(cm.doc, pos) }
  6556. setTimeout(function () { return display.input.focus(); }, 20)
  6557. } else if (button == 3) {
  6558. if (captureRightClick) { onContextMenu(cm, e) }
  6559. else { delayBlurEvent(cm) }
  6560. }
  6561. }
  6562. function handleMappedButton(cm, button, pos, repeat, event) {
  6563. var name = "Click"
  6564. if (repeat == "double") { name = "Double" + name }
  6565. else if (repeat == "triple") { name = "Triple" + name }
  6566. name = (button == 1 ? "Left" : button == 2 ? "Middle" : "Right") + name
  6567. return dispatchKey(cm, addModifierNames(name, event), event, function (bound) {
  6568. if (typeof bound == "string") { bound = commands[bound] }
  6569. if (!bound) { return false }
  6570. var done = false
  6571. try {
  6572. if (cm.isReadOnly()) { cm.state.suppressEdits = true }
  6573. done = bound(cm, pos) != Pass
  6574. } finally {
  6575. cm.state.suppressEdits = false
  6576. }
  6577. return done
  6578. })
  6579. }
  6580. function configureMouse(cm, repeat, event) {
  6581. var option = cm.getOption("configureMouse")
  6582. var value = option ? option(cm, repeat, event) : {}
  6583. if (value.unit == null) {
  6584. var rect = chromeOS ? event.shiftKey && event.metaKey : event.altKey
  6585. value.unit = rect ? "rectangle" : repeat == "single" ? "char" : repeat == "double" ? "word" : "line"
  6586. }
  6587. if (value.extend == null || cm.doc.extend) { value.extend = cm.doc.extend || event.shiftKey }
  6588. if (value.addNew == null) { value.addNew = mac ? event.metaKey : event.ctrlKey }
  6589. if (value.moveOnDrag == null) { value.moveOnDrag = !(mac ? event.altKey : event.ctrlKey) }
  6590. return value
  6591. }
  6592. function leftButtonDown(cm, pos, repeat, event) {
  6593. if (ie) { setTimeout(bind(ensureFocus, cm), 0) }
  6594. else { cm.curOp.focus = activeElt() }
  6595. var behavior = configureMouse(cm, repeat, event)
  6596. var sel = cm.doc.sel, contained
  6597. if (cm.options.dragDrop && dragAndDrop && !cm.isReadOnly() &&
  6598. repeat == "single" && (contained = sel.contains(pos)) > -1 &&
  6599. (cmp((contained = sel.ranges[contained]).from(), pos) < 0 || pos.xRel > 0) &&
  6600. (cmp(contained.to(), pos) > 0 || pos.xRel < 0))
  6601. { leftButtonStartDrag(cm, event, pos, behavior) }
  6602. else
  6603. { leftButtonSelect(cm, event, pos, behavior) }
  6604. }
  6605. // Start a text drag. When it ends, see if any dragging actually
  6606. // happen, and treat as a click if it didn't.
  6607. function leftButtonStartDrag(cm, event, pos, behavior) {
  6608. var display = cm.display, moved = false
  6609. var dragEnd = operation(cm, function (e) {
  6610. if (webkit) { display.scroller.draggable = false }
  6611. cm.state.draggingText = false
  6612. off(display.wrapper.ownerDocument, "mouseup", dragEnd)
  6613. off(display.wrapper.ownerDocument, "mousemove", mouseMove)
  6614. off(display.scroller, "dragstart", dragStart)
  6615. off(display.scroller, "drop", dragEnd)
  6616. if (!moved) {
  6617. e_preventDefault(e)
  6618. if (!behavior.addNew)
  6619. { extendSelection(cm.doc, pos, null, null, behavior.extend) }
  6620. // Work around unexplainable focus problem in IE9 (#2127) and Chrome (#3081)
  6621. if (webkit || ie && ie_version == 9)
  6622. { setTimeout(function () {display.wrapper.ownerDocument.body.focus(); display.input.focus()}, 20) }
  6623. else
  6624. { display.input.focus() }
  6625. }
  6626. })
  6627. var mouseMove = function(e2) {
  6628. moved = moved || Math.abs(event.clientX - e2.clientX) + Math.abs(event.clientY - e2.clientY) >= 10
  6629. }
  6630. var dragStart = function () { return moved = true; }
  6631. // Let the drag handler handle this.
  6632. if (webkit) { display.scroller.draggable = true }
  6633. cm.state.draggingText = dragEnd
  6634. dragEnd.copy = !behavior.moveOnDrag
  6635. // IE's approach to draggable
  6636. if (display.scroller.dragDrop) { display.scroller.dragDrop() }
  6637. on(display.wrapper.ownerDocument, "mouseup", dragEnd)
  6638. on(display.wrapper.ownerDocument, "mousemove", mouseMove)
  6639. on(display.scroller, "dragstart", dragStart)
  6640. on(display.scroller, "drop", dragEnd)
  6641. delayBlurEvent(cm)
  6642. setTimeout(function () { return display.input.focus(); }, 20)
  6643. }
  6644. function rangeForUnit(cm, pos, unit) {
  6645. if (unit == "char") { return new Range(pos, pos) }
  6646. if (unit == "word") { return cm.findWordAt(pos) }
  6647. if (unit == "line") { return new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))) }
  6648. var result = unit(cm, pos)
  6649. return new Range(result.from, result.to)
  6650. }
  6651. // Normal selection, as opposed to text dragging.
  6652. function leftButtonSelect(cm, event, start, behavior) {
  6653. var display = cm.display, doc = cm.doc
  6654. e_preventDefault(event)
  6655. var ourRange, ourIndex, startSel = doc.sel, ranges = startSel.ranges
  6656. if (behavior.addNew && !behavior.extend) {
  6657. ourIndex = doc.sel.contains(start)
  6658. if (ourIndex > -1)
  6659. { ourRange = ranges[ourIndex] }
  6660. else
  6661. { ourRange = new Range(start, start) }
  6662. } else {
  6663. ourRange = doc.sel.primary()
  6664. ourIndex = doc.sel.primIndex
  6665. }
  6666. if (behavior.unit == "rectangle") {
  6667. if (!behavior.addNew) { ourRange = new Range(start, start) }
  6668. start = posFromMouse(cm, event, true, true)
  6669. ourIndex = -1
  6670. } else {
  6671. var range = rangeForUnit(cm, start, behavior.unit)
  6672. if (behavior.extend)
  6673. { ourRange = extendRange(ourRange, range.anchor, range.head, behavior.extend) }
  6674. else
  6675. { ourRange = range }
  6676. }
  6677. if (!behavior.addNew) {
  6678. ourIndex = 0
  6679. setSelection(doc, new Selection([ourRange], 0), sel_mouse)
  6680. startSel = doc.sel
  6681. } else if (ourIndex == -1) {
  6682. ourIndex = ranges.length
  6683. setSelection(doc, normalizeSelection(ranges.concat([ourRange]), ourIndex),
  6684. {scroll: false, origin: "*mouse"})
  6685. } else if (ranges.length > 1 && ranges[ourIndex].empty() && behavior.unit == "char" && !behavior.extend) {
  6686. setSelection(doc, normalizeSelection(ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0),
  6687. {scroll: false, origin: "*mouse"})
  6688. startSel = doc.sel
  6689. } else {
  6690. replaceOneSelection(doc, ourIndex, ourRange, sel_mouse)
  6691. }
  6692. var lastPos = start
  6693. function extendTo(pos) {
  6694. if (cmp(lastPos, pos) == 0) { return }
  6695. lastPos = pos
  6696. if (behavior.unit == "rectangle") {
  6697. var ranges = [], tabSize = cm.options.tabSize
  6698. var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize)
  6699. var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize)
  6700. var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol)
  6701. for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line));
  6702. line <= end; line++) {
  6703. var text = getLine(doc, line).text, leftPos = findColumn(text, left, tabSize)
  6704. if (left == right)
  6705. { ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos))) }
  6706. else if (text.length > leftPos)
  6707. { ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize)))) }
  6708. }
  6709. if (!ranges.length) { ranges.push(new Range(start, start)) }
  6710. setSelection(doc, normalizeSelection(startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex),
  6711. {origin: "*mouse", scroll: false})
  6712. cm.scrollIntoView(pos)
  6713. } else {
  6714. var oldRange = ourRange
  6715. var range = rangeForUnit(cm, pos, behavior.unit)
  6716. var anchor = oldRange.anchor, head
  6717. if (cmp(range.anchor, anchor) > 0) {
  6718. head = range.head
  6719. anchor = minPos(oldRange.from(), range.anchor)
  6720. } else {
  6721. head = range.anchor
  6722. anchor = maxPos(oldRange.to(), range.head)
  6723. }
  6724. var ranges$1 = startSel.ranges.slice(0)
  6725. ranges$1[ourIndex] = bidiSimplify(cm, new Range(clipPos(doc, anchor), head))
  6726. setSelection(doc, normalizeSelection(ranges$1, ourIndex), sel_mouse)
  6727. }
  6728. }
  6729. var editorSize = display.wrapper.getBoundingClientRect()
  6730. // Used to ensure timeout re-tries don't fire when another extend
  6731. // happened in the meantime (clearTimeout isn't reliable -- at
  6732. // least on Chrome, the timeouts still happen even when cleared,
  6733. // if the clear happens after their scheduled firing time).
  6734. var counter = 0
  6735. function extend(e) {
  6736. var curCount = ++counter
  6737. var cur = posFromMouse(cm, e, true, behavior.unit == "rectangle")
  6738. if (!cur) { return }
  6739. if (cmp(cur, lastPos) != 0) {
  6740. cm.curOp.focus = activeElt()
  6741. extendTo(cur)
  6742. var visible = visibleLines(display, doc)
  6743. if (cur.line >= visible.to || cur.line < visible.from)
  6744. { setTimeout(operation(cm, function () {if (counter == curCount) { extend(e) }}), 150) }
  6745. } else {
  6746. var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0
  6747. if (outside) { setTimeout(operation(cm, function () {
  6748. if (counter != curCount) { return }
  6749. display.scroller.scrollTop += outside
  6750. extend(e)
  6751. }), 50) }
  6752. }
  6753. }
  6754. function done(e) {
  6755. cm.state.selectingText = false
  6756. counter = Infinity
  6757. e_preventDefault(e)
  6758. display.input.focus()
  6759. off(display.wrapper.ownerDocument, "mousemove", move)
  6760. off(display.wrapper.ownerDocument, "mouseup", up)
  6761. doc.history.lastSelOrigin = null
  6762. }
  6763. var move = operation(cm, function (e) {
  6764. if (e.buttons === 0 || !e_button(e)) { done(e) }
  6765. else { extend(e) }
  6766. })
  6767. var up = operation(cm, done)
  6768. cm.state.selectingText = up
  6769. on(display.wrapper.ownerDocument, "mousemove", move)
  6770. on(display.wrapper.ownerDocument, "mouseup", up)
  6771. }
  6772. // Used when mouse-selecting to adjust the anchor to the proper side
  6773. // of a bidi jump depending on the visual position of the head.
  6774. function bidiSimplify(cm, range) {
  6775. var anchor = range.anchor;
  6776. var head = range.head;
  6777. var anchorLine = getLine(cm.doc, anchor.line)
  6778. if (cmp(anchor, head) == 0 && anchor.sticky == head.sticky) { return range }
  6779. var order = getOrder(anchorLine)
  6780. if (!order) { return range }
  6781. var index = getBidiPartAt(order, anchor.ch, anchor.sticky), part = order[index]
  6782. if (part.from != anchor.ch && part.to != anchor.ch) { return range }
  6783. var boundary = index + ((part.from == anchor.ch) == (part.level != 1) ? 0 : 1)
  6784. if (boundary == 0 || boundary == order.length) { return range }
  6785. // Compute the relative visual position of the head compared to the
  6786. // anchor (<0 is to the left, >0 to the right)
  6787. var leftSide
  6788. if (head.line != anchor.line) {
  6789. leftSide = (head.line - anchor.line) * (cm.doc.direction == "ltr" ? 1 : -1) > 0
  6790. } else {
  6791. var headIndex = getBidiPartAt(order, head.ch, head.sticky)
  6792. var dir = headIndex - index || (head.ch - anchor.ch) * (part.level == 1 ? -1 : 1)
  6793. if (headIndex == boundary - 1 || headIndex == boundary)
  6794. { leftSide = dir < 0 }
  6795. else
  6796. { leftSide = dir > 0 }
  6797. }
  6798. var usePart = order[boundary + (leftSide ? -1 : 0)]
  6799. var from = leftSide == (usePart.level == 1)
  6800. var ch = from ? usePart.from : usePart.to, sticky = from ? "after" : "before"
  6801. return anchor.ch == ch && anchor.sticky == sticky ? range : new Range(new Pos(anchor.line, ch, sticky), head)
  6802. }
  6803. // Determines whether an event happened in the gutter, and fires the
  6804. // handlers for the corresponding event.
  6805. function gutterEvent(cm, e, type, prevent) {
  6806. var mX, mY
  6807. if (e.touches) {
  6808. mX = e.touches[0].clientX
  6809. mY = e.touches[0].clientY
  6810. } else {
  6811. try { mX = e.clientX; mY = e.clientY }
  6812. catch(e) { return false }
  6813. }
  6814. if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) { return false }
  6815. if (prevent) { e_preventDefault(e) }
  6816. var display = cm.display
  6817. var lineBox = display.lineDiv.getBoundingClientRect()
  6818. if (mY > lineBox.bottom || !hasHandler(cm, type)) { return e_defaultPrevented(e) }
  6819. mY -= lineBox.top - display.viewOffset
  6820. for (var i = 0; i < cm.options.gutters.length; ++i) {
  6821. var g = display.gutters.childNodes[i]
  6822. if (g && g.getBoundingClientRect().right >= mX) {
  6823. var line = lineAtHeight(cm.doc, mY)
  6824. var gutter = cm.options.gutters[i]
  6825. signal(cm, type, cm, line, gutter, e)
  6826. return e_defaultPrevented(e)
  6827. }
  6828. }
  6829. }
  6830. function clickInGutter(cm, e) {
  6831. return gutterEvent(cm, e, "gutterClick", true)
  6832. }
  6833. // CONTEXT MENU HANDLING
  6834. // To make the context menu work, we need to briefly unhide the
  6835. // textarea (making it as unobtrusive as possible) to let the
  6836. // right-click take effect on it.
  6837. function onContextMenu(cm, e) {
  6838. if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) { return }
  6839. if (signalDOMEvent(cm, e, "contextmenu")) { return }
  6840. cm.display.input.onContextMenu(e)
  6841. }
  6842. function contextMenuInGutter(cm, e) {
  6843. if (!hasHandler(cm, "gutterContextMenu")) { return false }
  6844. return gutterEvent(cm, e, "gutterContextMenu", false)
  6845. }
  6846. function themeChanged(cm) {
  6847. cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") +
  6848. cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-")
  6849. clearCaches(cm)
  6850. }
  6851. var Init = {toString: function(){return "CodeMirror.Init"}}
  6852. var defaults = {}
  6853. var optionHandlers = {}
  6854. function defineOptions(CodeMirror) {
  6855. var optionHandlers = CodeMirror.optionHandlers
  6856. function option(name, deflt, handle, notOnInit) {
  6857. CodeMirror.defaults[name] = deflt
  6858. if (handle) { optionHandlers[name] =
  6859. notOnInit ? function (cm, val, old) {if (old != Init) { handle(cm, val, old) }} : handle }
  6860. }
  6861. CodeMirror.defineOption = option
  6862. // Passed to option handlers when there is no old value.
  6863. CodeMirror.Init = Init
  6864. // These two are, on init, called from the constructor because they
  6865. // have to be initialized before the editor can start at all.
  6866. option("value", "", function (cm, val) { return cm.setValue(val); }, true)
  6867. option("mode", null, function (cm, val) {
  6868. cm.doc.modeOption = val
  6869. loadMode(cm)
  6870. }, true)
  6871. option("indentUnit", 2, loadMode, true)
  6872. option("indentWithTabs", false)
  6873. option("smartIndent", true)
  6874. option("tabSize", 4, function (cm) {
  6875. resetModeState(cm)
  6876. clearCaches(cm)
  6877. regChange(cm)
  6878. }, true)
  6879. option("lineSeparator", null, function (cm, val) {
  6880. cm.doc.lineSep = val
  6881. if (!val) { return }
  6882. var newBreaks = [], lineNo = cm.doc.first
  6883. cm.doc.iter(function (line) {
  6884. for (var pos = 0;;) {
  6885. var found = line.text.indexOf(val, pos)
  6886. if (found == -1) { break }
  6887. pos = found + val.length
  6888. newBreaks.push(Pos(lineNo, found))
  6889. }
  6890. lineNo++
  6891. })
  6892. for (var i = newBreaks.length - 1; i >= 0; i--)
  6893. { replaceRange(cm.doc, val, newBreaks[i], Pos(newBreaks[i].line, newBreaks[i].ch + val.length)) }
  6894. })
  6895. option("specialChars", /[\u0000-\u001f\u007f-\u009f\u00ad\u061c\u200b-\u200f\u2028\u2029\ufeff]/g, function (cm, val, old) {
  6896. cm.state.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g")
  6897. if (old != Init) { cm.refresh() }
  6898. })
  6899. option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function (cm) { return cm.refresh(); }, true)
  6900. option("electricChars", true)
  6901. option("inputStyle", mobile ? "contenteditable" : "textarea", function () {
  6902. throw new Error("inputStyle can not (yet) be changed in a running editor") // FIXME
  6903. }, true)
  6904. option("spellcheck", false, function (cm, val) { return cm.getInputField().spellcheck = val; }, true)
  6905. option("rtlMoveVisually", !windows)
  6906. option("wholeLineUpdateBefore", true)
  6907. option("theme", "default", function (cm) {
  6908. themeChanged(cm)
  6909. guttersChanged(cm)
  6910. }, true)
  6911. option("keyMap", "default", function (cm, val, old) {
  6912. var next = getKeyMap(val)
  6913. var prev = old != Init && getKeyMap(old)
  6914. if (prev && prev.detach) { prev.detach(cm, next) }
  6915. if (next.attach) { next.attach(cm, prev || null) }
  6916. })
  6917. option("extraKeys", null)
  6918. option("configureMouse", null)
  6919. option("lineWrapping", false, wrappingChanged, true)
  6920. option("gutters", [], function (cm) {
  6921. setGuttersForLineNumbers(cm.options)
  6922. guttersChanged(cm)
  6923. }, true)
  6924. option("fixedGutter", true, function (cm, val) {
  6925. cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0"
  6926. cm.refresh()
  6927. }, true)
  6928. option("coverGutterNextToScrollbar", false, function (cm) { return updateScrollbars(cm); }, true)
  6929. option("scrollbarStyle", "native", function (cm) {
  6930. initScrollbars(cm)
  6931. updateScrollbars(cm)
  6932. cm.display.scrollbars.setScrollTop(cm.doc.scrollTop)
  6933. cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft)
  6934. }, true)
  6935. option("lineNumbers", false, function (cm) {
  6936. setGuttersForLineNumbers(cm.options)
  6937. guttersChanged(cm)
  6938. }, true)
  6939. option("firstLineNumber", 1, guttersChanged, true)
  6940. option("lineNumberFormatter", function (integer) { return integer; }, guttersChanged, true)
  6941. option("showCursorWhenSelecting", false, updateSelection, true)
  6942. option("resetSelectionOnContextMenu", true)
  6943. option("lineWiseCopyCut", true)
  6944. option("pasteLinesPerSelection", true)
  6945. option("readOnly", false, function (cm, val) {
  6946. if (val == "nocursor") {
  6947. onBlur(cm)
  6948. cm.display.input.blur()
  6949. }
  6950. cm.display.input.readOnlyChanged(val)
  6951. })
  6952. option("disableInput", false, function (cm, val) {if (!val) { cm.display.input.reset() }}, true)
  6953. option("dragDrop", true, dragDropChanged)
  6954. option("allowDropFileTypes", null)
  6955. option("cursorBlinkRate", 530)
  6956. option("cursorScrollMargin", 0)
  6957. option("cursorHeight", 1, updateSelection, true)
  6958. option("singleCursorHeightPerLine", true, updateSelection, true)
  6959. option("workTime", 100)
  6960. option("workDelay", 100)
  6961. option("flattenSpans", true, resetModeState, true)
  6962. option("addModeClass", false, resetModeState, true)
  6963. option("pollInterval", 100)
  6964. option("undoDepth", 200, function (cm, val) { return cm.doc.history.undoDepth = val; })
  6965. option("historyEventDelay", 1250)
  6966. option("viewportMargin", 10, function (cm) { return cm.refresh(); }, true)
  6967. option("maxHighlightLength", 10000, resetModeState, true)
  6968. option("moveInputWithCursor", true, function (cm, val) {
  6969. if (!val) { cm.display.input.resetPosition() }
  6970. })
  6971. option("tabindex", null, function (cm, val) { return cm.display.input.getField().tabIndex = val || ""; })
  6972. option("autofocus", null)
  6973. option("direction", "ltr", function (cm, val) { return cm.doc.setDirection(val); }, true)
  6974. option("phrases", null)
  6975. }
  6976. function guttersChanged(cm) {
  6977. updateGutters(cm)
  6978. regChange(cm)
  6979. alignHorizontally(cm)
  6980. }
  6981. function dragDropChanged(cm, value, old) {
  6982. var wasOn = old && old != Init
  6983. if (!value != !wasOn) {
  6984. var funcs = cm.display.dragFunctions
  6985. var toggle = value ? on : off
  6986. toggle(cm.display.scroller, "dragstart", funcs.start)
  6987. toggle(cm.display.scroller, "dragenter", funcs.enter)
  6988. toggle(cm.display.scroller, "dragover", funcs.over)
  6989. toggle(cm.display.scroller, "dragleave", funcs.leave)
  6990. toggle(cm.display.scroller, "drop", funcs.drop)
  6991. }
  6992. }
  6993. function wrappingChanged(cm) {
  6994. if (cm.options.lineWrapping) {
  6995. addClass(cm.display.wrapper, "CodeMirror-wrap")
  6996. cm.display.sizer.style.minWidth = ""
  6997. cm.display.sizerWidth = null
  6998. } else {
  6999. rmClass(cm.display.wrapper, "CodeMirror-wrap")
  7000. findMaxLine(cm)
  7001. }
  7002. estimateLineHeights(cm)
  7003. regChange(cm)
  7004. clearCaches(cm)
  7005. setTimeout(function () { return updateScrollbars(cm); }, 100)
  7006. }
  7007. // A CodeMirror instance represents an editor. This is the object
  7008. // that user code is usually dealing with.
  7009. function CodeMirror(place, options) {
  7010. var this$1 = this;
  7011. if (!(this instanceof CodeMirror)) { return new CodeMirror(place, options) }
  7012. this.options = options = options ? copyObj(options) : {}
  7013. // Determine effective options based on given values and defaults.
  7014. copyObj(defaults, options, false)
  7015. setGuttersForLineNumbers(options)
  7016. var doc = options.value
  7017. if (typeof doc == "string") { doc = new Doc(doc, options.mode, null, options.lineSeparator, options.direction) }
  7018. else if (options.mode) { doc.modeOption = options.mode }
  7019. this.doc = doc
  7020. var input = new CodeMirror.inputStyles[options.inputStyle](this)
  7021. var display = this.display = new Display(place, doc, input)
  7022. display.wrapper.CodeMirror = this
  7023. updateGutters(this)
  7024. themeChanged(this)
  7025. if (options.lineWrapping)
  7026. { this.display.wrapper.className += " CodeMirror-wrap" }
  7027. initScrollbars(this)
  7028. this.state = {
  7029. keyMaps: [], // stores maps added by addKeyMap
  7030. overlays: [], // highlighting overlays, as added by addOverlay
  7031. modeGen: 0, // bumped when mode/overlay changes, used to invalidate highlighting info
  7032. overwrite: false,
  7033. delayingBlurEvent: false,
  7034. focused: false,
  7035. suppressEdits: false, // used to disable editing during key handlers when in readOnly mode
  7036. pasteIncoming: false, cutIncoming: false, // help recognize paste/cut edits in input.poll
  7037. selectingText: false,
  7038. draggingText: false,
  7039. highlight: new Delayed(), // stores highlight worker timeout
  7040. keySeq: null, // Unfinished key sequence
  7041. specialChars: null
  7042. }
  7043. if (options.autofocus && !mobile) { display.input.focus() }
  7044. // Override magic textarea content restore that IE sometimes does
  7045. // on our hidden textarea on reload
  7046. if (ie && ie_version < 11) { setTimeout(function () { return this$1.display.input.reset(true); }, 20) }
  7047. registerEventHandlers(this)
  7048. ensureGlobalHandlers()
  7049. startOperation(this)
  7050. this.curOp.forceUpdate = true
  7051. attachDoc(this, doc)
  7052. if ((options.autofocus && !mobile) || this.hasFocus())
  7053. { setTimeout(bind(onFocus, this), 20) }
  7054. else
  7055. { onBlur(this) }
  7056. for (var opt in optionHandlers) { if (optionHandlers.hasOwnProperty(opt))
  7057. { optionHandlers[opt](this$1, options[opt], Init) } }
  7058. maybeUpdateLineNumberWidth(this)
  7059. if (options.finishInit) { options.finishInit(this) }
  7060. for (var i = 0; i < initHooks.length; ++i) { initHooks[i](this$1) }
  7061. endOperation(this)
  7062. // Suppress optimizelegibility in Webkit, since it breaks text
  7063. // measuring on line wrapping boundaries.
  7064. if (webkit && options.lineWrapping &&
  7065. getComputedStyle(display.lineDiv).textRendering == "optimizelegibility")
  7066. { display.lineDiv.style.textRendering = "auto" }
  7067. }
  7068. // The default configuration options.
  7069. CodeMirror.defaults = defaults
  7070. // Functions to run when options are changed.
  7071. CodeMirror.optionHandlers = optionHandlers
  7072. // Attach the necessary event handlers when initializing the editor
  7073. function registerEventHandlers(cm) {
  7074. var d = cm.display
  7075. on(d.scroller, "mousedown", operation(cm, onMouseDown))
  7076. // Older IE's will not fire a second mousedown for a double click
  7077. if (ie && ie_version < 11)
  7078. { on(d.scroller, "dblclick", operation(cm, function (e) {
  7079. if (signalDOMEvent(cm, e)) { return }
  7080. var pos = posFromMouse(cm, e)
  7081. if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) { return }
  7082. e_preventDefault(e)
  7083. var word = cm.findWordAt(pos)
  7084. extendSelection(cm.doc, word.anchor, word.head)
  7085. })) }
  7086. else
  7087. { on(d.scroller, "dblclick", function (e) { return signalDOMEvent(cm, e) || e_preventDefault(e); }) }
  7088. // Some browsers fire contextmenu *after* opening the menu, at
  7089. // which point we can't mess with it anymore. Context menu is
  7090. // handled in onMouseDown for these browsers.
  7091. if (!captureRightClick) { on(d.scroller, "contextmenu", function (e) { return onContextMenu(cm, e); }) }
  7092. // Used to suppress mouse event handling when a touch happens
  7093. var touchFinished, prevTouch = {end: 0}
  7094. function finishTouch() {
  7095. if (d.activeTouch) {
  7096. touchFinished = setTimeout(function () { return d.activeTouch = null; }, 1000)
  7097. prevTouch = d.activeTouch
  7098. prevTouch.end = +new Date
  7099. }
  7100. }
  7101. function isMouseLikeTouchEvent(e) {
  7102. if (e.touches.length != 1) { return false }
  7103. var touch = e.touches[0]
  7104. return touch.radiusX <= 1 && touch.radiusY <= 1
  7105. }
  7106. function farAway(touch, other) {
  7107. if (other.left == null) { return true }
  7108. var dx = other.left - touch.left, dy = other.top - touch.top
  7109. return dx * dx + dy * dy > 20 * 20
  7110. }
  7111. on(d.scroller, "touchstart", function (e) {
  7112. if (!signalDOMEvent(cm, e) && !isMouseLikeTouchEvent(e) && !clickInGutter(cm, e)) {
  7113. d.input.ensurePolled()
  7114. clearTimeout(touchFinished)
  7115. var now = +new Date
  7116. d.activeTouch = {start: now, moved: false,
  7117. prev: now - prevTouch.end <= 300 ? prevTouch : null}
  7118. if (e.touches.length == 1) {
  7119. d.activeTouch.left = e.touches[0].pageX
  7120. d.activeTouch.top = e.touches[0].pageY
  7121. }
  7122. }
  7123. })
  7124. on(d.scroller, "touchmove", function () {
  7125. if (d.activeTouch) { d.activeTouch.moved = true }
  7126. })
  7127. on(d.scroller, "touchend", function (e) {
  7128. var touch = d.activeTouch
  7129. if (touch && !eventInWidget(d, e) && touch.left != null &&
  7130. !touch.moved && new Date - touch.start < 300) {
  7131. var pos = cm.coordsChar(d.activeTouch, "page"), range
  7132. if (!touch.prev || farAway(touch, touch.prev)) // Single tap
  7133. { range = new Range(pos, pos) }
  7134. else if (!touch.prev.prev || farAway(touch, touch.prev.prev)) // Double tap
  7135. { range = cm.findWordAt(pos) }
  7136. else // Triple tap
  7137. { range = new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))) }
  7138. cm.setSelection(range.anchor, range.head)
  7139. cm.focus()
  7140. e_preventDefault(e)
  7141. }
  7142. finishTouch()
  7143. })
  7144. on(d.scroller, "touchcancel", finishTouch)
  7145. // Sync scrolling between fake scrollbars and real scrollable
  7146. // area, ensure viewport is updated when scrolling.
  7147. on(d.scroller, "scroll", function () {
  7148. if (d.scroller.clientHeight) {
  7149. updateScrollTop(cm, d.scroller.scrollTop)
  7150. setScrollLeft(cm, d.scroller.scrollLeft, true)
  7151. signal(cm, "scroll", cm)
  7152. }
  7153. })
  7154. // Listen to wheel events in order to try and update the viewport on time.
  7155. on(d.scroller, "mousewheel", function (e) { return onScrollWheel(cm, e); })
  7156. on(d.scroller, "DOMMouseScroll", function (e) { return onScrollWheel(cm, e); })
  7157. // Prevent wrapper from ever scrolling
  7158. on(d.wrapper, "scroll", function () { return d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; })
  7159. d.dragFunctions = {
  7160. enter: function (e) {if (!signalDOMEvent(cm, e)) { e_stop(e) }},
  7161. over: function (e) {if (!signalDOMEvent(cm, e)) { onDragOver(cm, e); e_stop(e) }},
  7162. start: function (e) { return onDragStart(cm, e); },
  7163. drop: operation(cm, onDrop),
  7164. leave: function (e) {if (!signalDOMEvent(cm, e)) { clearDragCursor(cm) }}
  7165. }
  7166. var inp = d.input.getField()
  7167. on(inp, "keyup", function (e) { return onKeyUp.call(cm, e); })
  7168. on(inp, "keydown", operation(cm, onKeyDown))
  7169. on(inp, "keypress", operation(cm, onKeyPress))
  7170. on(inp, "focus", function (e) { return onFocus(cm, e); })
  7171. on(inp, "blur", function (e) { return onBlur(cm, e); })
  7172. }
  7173. var initHooks = []
  7174. CodeMirror.defineInitHook = function (f) { return initHooks.push(f); }
  7175. // Indent the given line. The how parameter can be "smart",
  7176. // "add"/null, "subtract", or "prev". When aggressive is false
  7177. // (typically set to true for forced single-line indents), empty
  7178. // lines are not indented, and places where the mode returns Pass
  7179. // are left alone.
  7180. function indentLine(cm, n, how, aggressive) {
  7181. var doc = cm.doc, state
  7182. if (how == null) { how = "add" }
  7183. if (how == "smart") {
  7184. // Fall back to "prev" when the mode doesn't have an indentation
  7185. // method.
  7186. if (!doc.mode.indent) { how = "prev" }
  7187. else { state = getContextBefore(cm, n).state }
  7188. }
  7189. var tabSize = cm.options.tabSize
  7190. var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize)
  7191. if (line.stateAfter) { line.stateAfter = null }
  7192. var curSpaceString = line.text.match(/^\s*/)[0], indentation
  7193. if (!aggressive && !/\S/.test(line.text)) {
  7194. indentation = 0
  7195. how = "not"
  7196. } else if (how == "smart") {
  7197. indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text)
  7198. if (indentation == Pass || indentation > 150) {
  7199. if (!aggressive) { return }
  7200. how = "prev"
  7201. }
  7202. }
  7203. if (how == "prev") {
  7204. if (n > doc.first) { indentation = countColumn(getLine(doc, n-1).text, null, tabSize) }
  7205. else { indentation = 0 }
  7206. } else if (how == "add") {
  7207. indentation = curSpace + cm.options.indentUnit
  7208. } else if (how == "subtract") {
  7209. indentation = curSpace - cm.options.indentUnit
  7210. } else if (typeof how == "number") {
  7211. indentation = curSpace + how
  7212. }
  7213. indentation = Math.max(0, indentation)
  7214. var indentString = "", pos = 0
  7215. if (cm.options.indentWithTabs)
  7216. { for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t"} }
  7217. if (pos < indentation) { indentString += spaceStr(indentation - pos) }
  7218. if (indentString != curSpaceString) {
  7219. replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input")
  7220. line.stateAfter = null
  7221. return true
  7222. } else {
  7223. // Ensure that, if the cursor was in the whitespace at the start
  7224. // of the line, it is moved to the end of that space.
  7225. for (var i$1 = 0; i$1 < doc.sel.ranges.length; i$1++) {
  7226. var range = doc.sel.ranges[i$1]
  7227. if (range.head.line == n && range.head.ch < curSpaceString.length) {
  7228. var pos$1 = Pos(n, curSpaceString.length)
  7229. replaceOneSelection(doc, i$1, new Range(pos$1, pos$1))
  7230. break
  7231. }
  7232. }
  7233. }
  7234. }
  7235. // This will be set to a {lineWise: bool, text: [string]} object, so
  7236. // that, when pasting, we know what kind of selections the copied
  7237. // text was made out of.
  7238. var lastCopied = null
  7239. function setLastCopied(newLastCopied) {
  7240. lastCopied = newLastCopied
  7241. }
  7242. function applyTextInput(cm, inserted, deleted, sel, origin) {
  7243. var doc = cm.doc
  7244. cm.display.shift = false
  7245. if (!sel) { sel = doc.sel }
  7246. var paste = cm.state.pasteIncoming || origin == "paste"
  7247. var textLines = splitLinesAuto(inserted), multiPaste = null
  7248. // When pasting N lines into N selections, insert one line per selection
  7249. if (paste && sel.ranges.length > 1) {
  7250. if (lastCopied && lastCopied.text.join("\n") == inserted) {
  7251. if (sel.ranges.length % lastCopied.text.length == 0) {
  7252. multiPaste = []
  7253. for (var i = 0; i < lastCopied.text.length; i++)
  7254. { multiPaste.push(doc.splitLines(lastCopied.text[i])) }
  7255. }
  7256. } else if (textLines.length == sel.ranges.length && cm.options.pasteLinesPerSelection) {
  7257. multiPaste = map(textLines, function (l) { return [l]; })
  7258. }
  7259. }
  7260. var updateInput
  7261. // Normal behavior is to insert the new text into every selection
  7262. for (var i$1 = sel.ranges.length - 1; i$1 >= 0; i$1--) {
  7263. var range = sel.ranges[i$1]
  7264. var from = range.from(), to = range.to()
  7265. if (range.empty()) {
  7266. if (deleted && deleted > 0) // Handle deletion
  7267. { from = Pos(from.line, from.ch - deleted) }
  7268. else if (cm.state.overwrite && !paste) // Handle overwrite
  7269. { to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length)) }
  7270. else if (lastCopied && lastCopied.lineWise && lastCopied.text.join("\n") == inserted)
  7271. { from = to = Pos(from.line, 0) }
  7272. }
  7273. updateInput = cm.curOp.updateInput
  7274. var changeEvent = {from: from, to: to, text: multiPaste ? multiPaste[i$1 % multiPaste.length] : textLines,
  7275. origin: origin || (paste ? "paste" : cm.state.cutIncoming ? "cut" : "+input")}
  7276. makeChange(cm.doc, changeEvent)
  7277. signalLater(cm, "inputRead", cm, changeEvent)
  7278. }
  7279. if (inserted && !paste)
  7280. { triggerElectric(cm, inserted) }
  7281. ensureCursorVisible(cm)
  7282. cm.curOp.updateInput = updateInput
  7283. cm.curOp.typing = true
  7284. cm.state.pasteIncoming = cm.state.cutIncoming = false
  7285. }
  7286. function handlePaste(e, cm) {
  7287. var pasted = e.clipboardData && e.clipboardData.getData("Text")
  7288. if (pasted) {
  7289. e.preventDefault()
  7290. if (!cm.isReadOnly() && !cm.options.disableInput)
  7291. { runInOp(cm, function () { return applyTextInput(cm, pasted, 0, null, "paste"); }) }
  7292. return true
  7293. }
  7294. }
  7295. function triggerElectric(cm, inserted) {
  7296. // When an 'electric' character is inserted, immediately trigger a reindent
  7297. if (!cm.options.electricChars || !cm.options.smartIndent) { return }
  7298. var sel = cm.doc.sel
  7299. for (var i = sel.ranges.length - 1; i >= 0; i--) {
  7300. var range = sel.ranges[i]
  7301. if (range.head.ch > 100 || (i && sel.ranges[i - 1].head.line == range.head.line)) { continue }
  7302. var mode = cm.getModeAt(range.head)
  7303. var indented = false
  7304. if (mode.electricChars) {
  7305. for (var j = 0; j < mode.electricChars.length; j++)
  7306. { if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) {
  7307. indented = indentLine(cm, range.head.line, "smart")
  7308. break
  7309. } }
  7310. } else if (mode.electricInput) {
  7311. if (mode.electricInput.test(getLine(cm.doc, range.head.line).text.slice(0, range.head.ch)))
  7312. { indented = indentLine(cm, range.head.line, "smart") }
  7313. }
  7314. if (indented) { signalLater(cm, "electricInput", cm, range.head.line) }
  7315. }
  7316. }
  7317. function copyableRanges(cm) {
  7318. var text = [], ranges = []
  7319. for (var i = 0; i < cm.doc.sel.ranges.length; i++) {
  7320. var line = cm.doc.sel.ranges[i].head.line
  7321. var lineRange = {anchor: Pos(line, 0), head: Pos(line + 1, 0)}
  7322. ranges.push(lineRange)
  7323. text.push(cm.getRange(lineRange.anchor, lineRange.head))
  7324. }
  7325. return {text: text, ranges: ranges}
  7326. }
  7327. function disableBrowserMagic(field, spellcheck) {
  7328. field.setAttribute("autocorrect", "off")
  7329. field.setAttribute("autocapitalize", "off")
  7330. field.setAttribute("spellcheck", !!spellcheck)
  7331. }
  7332. function hiddenTextarea() {
  7333. var te = elt("textarea", null, null, "position: absolute; bottom: -1em; padding: 0; width: 1px; height: 1em; outline: none")
  7334. var div = elt("div", [te], null, "overflow: hidden; position: relative; width: 3px; height: 0px;")
  7335. // The textarea is kept positioned near the cursor to prevent the
  7336. // fact that it'll be scrolled into view on input from scrolling
  7337. // our fake cursor out of view. On webkit, when wrap=off, paste is
  7338. // very slow. So make the area wide instead.
  7339. if (webkit) { te.style.width = "1000px" }
  7340. else { te.setAttribute("wrap", "off") }
  7341. // If border: 0; -- iOS fails to open keyboard (issue #1287)
  7342. if (ios) { te.style.border = "1px solid black" }
  7343. disableBrowserMagic(te)
  7344. return div
  7345. }
  7346. // The publicly visible API. Note that methodOp(f) means
  7347. // 'wrap f in an operation, performed on its `this` parameter'.
  7348. // This is not the complete set of editor methods. Most of the
  7349. // methods defined on the Doc type are also injected into
  7350. // CodeMirror.prototype, for backwards compatibility and
  7351. // convenience.
  7352. function addEditorMethods(CodeMirror) {
  7353. var optionHandlers = CodeMirror.optionHandlers
  7354. var helpers = CodeMirror.helpers = {}
  7355. CodeMirror.prototype = {
  7356. constructor: CodeMirror,
  7357. focus: function(){window.focus(); this.display.input.focus()},
  7358. setOption: function(option, value) {
  7359. var options = this.options, old = options[option]
  7360. if (options[option] == value && option != "mode") { return }
  7361. options[option] = value
  7362. if (optionHandlers.hasOwnProperty(option))
  7363. { operation(this, optionHandlers[option])(this, value, old) }
  7364. signal(this, "optionChange", this, option)
  7365. },
  7366. getOption: function(option) {return this.options[option]},
  7367. getDoc: function() {return this.doc},
  7368. addKeyMap: function(map, bottom) {
  7369. this.state.keyMaps[bottom ? "push" : "unshift"](getKeyMap(map))
  7370. },
  7371. removeKeyMap: function(map) {
  7372. var maps = this.state.keyMaps
  7373. for (var i = 0; i < maps.length; ++i)
  7374. { if (maps[i] == map || maps[i].name == map) {
  7375. maps.splice(i, 1)
  7376. return true
  7377. } }
  7378. },
  7379. addOverlay: methodOp(function(spec, options) {
  7380. var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec)
  7381. if (mode.startState) { throw new Error("Overlays may not be stateful.") }
  7382. insertSorted(this.state.overlays,
  7383. {mode: mode, modeSpec: spec, opaque: options && options.opaque,
  7384. priority: (options && options.priority) || 0},
  7385. function (overlay) { return overlay.priority; })
  7386. this.state.modeGen++
  7387. regChange(this)
  7388. }),
  7389. removeOverlay: methodOp(function(spec) {
  7390. var this$1 = this;
  7391. var overlays = this.state.overlays
  7392. for (var i = 0; i < overlays.length; ++i) {
  7393. var cur = overlays[i].modeSpec
  7394. if (cur == spec || typeof spec == "string" && cur.name == spec) {
  7395. overlays.splice(i, 1)
  7396. this$1.state.modeGen++
  7397. regChange(this$1)
  7398. return
  7399. }
  7400. }
  7401. }),
  7402. indentLine: methodOp(function(n, dir, aggressive) {
  7403. if (typeof dir != "string" && typeof dir != "number") {
  7404. if (dir == null) { dir = this.options.smartIndent ? "smart" : "prev" }
  7405. else { dir = dir ? "add" : "subtract" }
  7406. }
  7407. if (isLine(this.doc, n)) { indentLine(this, n, dir, aggressive) }
  7408. }),
  7409. indentSelection: methodOp(function(how) {
  7410. var this$1 = this;
  7411. var ranges = this.doc.sel.ranges, end = -1
  7412. for (var i = 0; i < ranges.length; i++) {
  7413. var range = ranges[i]
  7414. if (!range.empty()) {
  7415. var from = range.from(), to = range.to()
  7416. var start = Math.max(end, from.line)
  7417. end = Math.min(this$1.lastLine(), to.line - (to.ch ? 0 : 1)) + 1
  7418. for (var j = start; j < end; ++j)
  7419. { indentLine(this$1, j, how) }
  7420. var newRanges = this$1.doc.sel.ranges
  7421. if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i].from().ch > 0)
  7422. { replaceOneSelection(this$1.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll) }
  7423. } else if (range.head.line > end) {
  7424. indentLine(this$1, range.head.line, how, true)
  7425. end = range.head.line
  7426. if (i == this$1.doc.sel.primIndex) { ensureCursorVisible(this$1) }
  7427. }
  7428. }
  7429. }),
  7430. // Fetch the parser token for a given character. Useful for hacks
  7431. // that want to inspect the mode state (say, for completion).
  7432. getTokenAt: function(pos, precise) {
  7433. return takeToken(this, pos, precise)
  7434. },
  7435. getLineTokens: function(line, precise) {
  7436. return takeToken(this, Pos(line), precise, true)
  7437. },
  7438. getTokenTypeAt: function(pos) {
  7439. pos = clipPos(this.doc, pos)
  7440. var styles = getLineStyles(this, getLine(this.doc, pos.line))
  7441. var before = 0, after = (styles.length - 1) / 2, ch = pos.ch
  7442. var type
  7443. if (ch == 0) { type = styles[2] }
  7444. else { for (;;) {
  7445. var mid = (before + after) >> 1
  7446. if ((mid ? styles[mid * 2 - 1] : 0) >= ch) { after = mid }
  7447. else if (styles[mid * 2 + 1] < ch) { before = mid + 1 }
  7448. else { type = styles[mid * 2 + 2]; break }
  7449. } }
  7450. var cut = type ? type.indexOf("overlay ") : -1
  7451. return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1)
  7452. },
  7453. getModeAt: function(pos) {
  7454. var mode = this.doc.mode
  7455. if (!mode.innerMode) { return mode }
  7456. return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode
  7457. },
  7458. getHelper: function(pos, type) {
  7459. return this.getHelpers(pos, type)[0]
  7460. },
  7461. getHelpers: function(pos, type) {
  7462. var this$1 = this;
  7463. var found = []
  7464. if (!helpers.hasOwnProperty(type)) { return found }
  7465. var help = helpers[type], mode = this.getModeAt(pos)
  7466. if (typeof mode[type] == "string") {
  7467. if (help[mode[type]]) { found.push(help[mode[type]]) }
  7468. } else if (mode[type]) {
  7469. for (var i = 0; i < mode[type].length; i++) {
  7470. var val = help[mode[type][i]]
  7471. if (val) { found.push(val) }
  7472. }
  7473. } else if (mode.helperType && help[mode.helperType]) {
  7474. found.push(help[mode.helperType])
  7475. } else if (help[mode.name]) {
  7476. found.push(help[mode.name])
  7477. }
  7478. for (var i$1 = 0; i$1 < help._global.length; i$1++) {
  7479. var cur = help._global[i$1]
  7480. if (cur.pred(mode, this$1) && indexOf(found, cur.val) == -1)
  7481. { found.push(cur.val) }
  7482. }
  7483. return found
  7484. },
  7485. getStateAfter: function(line, precise) {
  7486. var doc = this.doc
  7487. line = clipLine(doc, line == null ? doc.first + doc.size - 1: line)
  7488. return getContextBefore(this, line + 1, precise).state
  7489. },
  7490. cursorCoords: function(start, mode) {
  7491. var pos, range = this.doc.sel.primary()
  7492. if (start == null) { pos = range.head }
  7493. else if (typeof start == "object") { pos = clipPos(this.doc, start) }
  7494. else { pos = start ? range.from() : range.to() }
  7495. return cursorCoords(this, pos, mode || "page")
  7496. },
  7497. charCoords: function(pos, mode) {
  7498. return charCoords(this, clipPos(this.doc, pos), mode || "page")
  7499. },
  7500. coordsChar: function(coords, mode) {
  7501. coords = fromCoordSystem(this, coords, mode || "page")
  7502. return coordsChar(this, coords.left, coords.top)
  7503. },
  7504. lineAtHeight: function(height, mode) {
  7505. height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top
  7506. return lineAtHeight(this.doc, height + this.display.viewOffset)
  7507. },
  7508. heightAtLine: function(line, mode, includeWidgets) {
  7509. var end = false, lineObj
  7510. if (typeof line == "number") {
  7511. var last = this.doc.first + this.doc.size - 1
  7512. if (line < this.doc.first) { line = this.doc.first }
  7513. else if (line > last) { line = last; end = true }
  7514. lineObj = getLine(this.doc, line)
  7515. } else {
  7516. lineObj = line
  7517. }
  7518. return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || "page", includeWidgets || end).top +
  7519. (end ? this.doc.height - heightAtLine(lineObj) : 0)
  7520. },
  7521. defaultTextHeight: function() { return textHeight(this.display) },
  7522. defaultCharWidth: function() { return charWidth(this.display) },
  7523. getViewport: function() { return {from: this.display.viewFrom, to: this.display.viewTo}},
  7524. addWidget: function(pos, node, scroll, vert, horiz) {
  7525. var display = this.display
  7526. pos = cursorCoords(this, clipPos(this.doc, pos))
  7527. var top = pos.bottom, left = pos.left
  7528. node.style.position = "absolute"
  7529. node.setAttribute("cm-ignore-events", "true")
  7530. this.display.input.setUneditable(node)
  7531. display.sizer.appendChild(node)
  7532. if (vert == "over") {
  7533. top = pos.top
  7534. } else if (vert == "above" || vert == "near") {
  7535. var vspace = Math.max(display.wrapper.clientHeight, this.doc.height),
  7536. hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth)
  7537. // Default to positioning above (if specified and possible); otherwise default to positioning below
  7538. if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight)
  7539. { top = pos.top - node.offsetHeight }
  7540. else if (pos.bottom + node.offsetHeight <= vspace)
  7541. { top = pos.bottom }
  7542. if (left + node.offsetWidth > hspace)
  7543. { left = hspace - node.offsetWidth }
  7544. }
  7545. node.style.top = top + "px"
  7546. node.style.left = node.style.right = ""
  7547. if (horiz == "right") {
  7548. left = display.sizer.clientWidth - node.offsetWidth
  7549. node.style.right = "0px"
  7550. } else {
  7551. if (horiz == "left") { left = 0 }
  7552. else if (horiz == "middle") { left = (display.sizer.clientWidth - node.offsetWidth) / 2 }
  7553. node.style.left = left + "px"
  7554. }
  7555. if (scroll)
  7556. { scrollIntoView(this, {left: left, top: top, right: left + node.offsetWidth, bottom: top + node.offsetHeight}) }
  7557. },
  7558. triggerOnKeyDown: methodOp(onKeyDown),
  7559. triggerOnKeyPress: methodOp(onKeyPress),
  7560. triggerOnKeyUp: onKeyUp,
  7561. triggerOnMouseDown: methodOp(onMouseDown),
  7562. execCommand: function(cmd) {
  7563. if (commands.hasOwnProperty(cmd))
  7564. { return commands[cmd].call(null, this) }
  7565. },
  7566. triggerElectric: methodOp(function(text) { triggerElectric(this, text) }),
  7567. findPosH: function(from, amount, unit, visually) {
  7568. var this$1 = this;
  7569. var dir = 1
  7570. if (amount < 0) { dir = -1; amount = -amount }
  7571. var cur = clipPos(this.doc, from)
  7572. for (var i = 0; i < amount; ++i) {
  7573. cur = findPosH(this$1.doc, cur, dir, unit, visually)
  7574. if (cur.hitSide) { break }
  7575. }
  7576. return cur
  7577. },
  7578. moveH: methodOp(function(dir, unit) {
  7579. var this$1 = this;
  7580. this.extendSelectionsBy(function (range) {
  7581. if (this$1.display.shift || this$1.doc.extend || range.empty())
  7582. { return findPosH(this$1.doc, range.head, dir, unit, this$1.options.rtlMoveVisually) }
  7583. else
  7584. { return dir < 0 ? range.from() : range.to() }
  7585. }, sel_move)
  7586. }),
  7587. deleteH: methodOp(function(dir, unit) {
  7588. var sel = this.doc.sel, doc = this.doc
  7589. if (sel.somethingSelected())
  7590. { doc.replaceSelection("", null, "+delete") }
  7591. else
  7592. { deleteNearSelection(this, function (range) {
  7593. var other = findPosH(doc, range.head, dir, unit, false)
  7594. return dir < 0 ? {from: other, to: range.head} : {from: range.head, to: other}
  7595. }) }
  7596. }),
  7597. findPosV: function(from, amount, unit, goalColumn) {
  7598. var this$1 = this;
  7599. var dir = 1, x = goalColumn
  7600. if (amount < 0) { dir = -1; amount = -amount }
  7601. var cur = clipPos(this.doc, from)
  7602. for (var i = 0; i < amount; ++i) {
  7603. var coords = cursorCoords(this$1, cur, "div")
  7604. if (x == null) { x = coords.left }
  7605. else { coords.left = x }
  7606. cur = findPosV(this$1, coords, dir, unit)
  7607. if (cur.hitSide) { break }
  7608. }
  7609. return cur
  7610. },
  7611. moveV: methodOp(function(dir, unit) {
  7612. var this$1 = this;
  7613. var doc = this.doc, goals = []
  7614. var collapse = !this.display.shift && !doc.extend && doc.sel.somethingSelected()
  7615. doc.extendSelectionsBy(function (range) {
  7616. if (collapse)
  7617. { return dir < 0 ? range.from() : range.to() }
  7618. var headPos = cursorCoords(this$1, range.head, "div")
  7619. if (range.goalColumn != null) { headPos.left = range.goalColumn }
  7620. goals.push(headPos.left)
  7621. var pos = findPosV(this$1, headPos, dir, unit)
  7622. if (unit == "page" && range == doc.sel.primary())
  7623. { addToScrollTop(this$1, charCoords(this$1, pos, "div").top - headPos.top) }
  7624. return pos
  7625. }, sel_move)
  7626. if (goals.length) { for (var i = 0; i < doc.sel.ranges.length; i++)
  7627. { doc.sel.ranges[i].goalColumn = goals[i] } }
  7628. }),
  7629. // Find the word at the given position (as returned by coordsChar).
  7630. findWordAt: function(pos) {
  7631. var doc = this.doc, line = getLine(doc, pos.line).text
  7632. var start = pos.ch, end = pos.ch
  7633. if (line) {
  7634. var helper = this.getHelper(pos, "wordChars")
  7635. if ((pos.sticky == "before" || end == line.length) && start) { --start; } else { ++end }
  7636. var startChar = line.charAt(start)
  7637. var check = isWordChar(startChar, helper)
  7638. ? function (ch) { return isWordChar(ch, helper); }
  7639. : /\s/.test(startChar) ? function (ch) { return /\s/.test(ch); }
  7640. : function (ch) { return (!/\s/.test(ch) && !isWordChar(ch)); }
  7641. while (start > 0 && check(line.charAt(start - 1))) { --start }
  7642. while (end < line.length && check(line.charAt(end))) { ++end }
  7643. }
  7644. return new Range(Pos(pos.line, start), Pos(pos.line, end))
  7645. },
  7646. toggleOverwrite: function(value) {
  7647. if (value != null && value == this.state.overwrite) { return }
  7648. if (this.state.overwrite = !this.state.overwrite)
  7649. { addClass(this.display.cursorDiv, "CodeMirror-overwrite") }
  7650. else
  7651. { rmClass(this.display.cursorDiv, "CodeMirror-overwrite") }
  7652. signal(this, "overwriteToggle", this, this.state.overwrite)
  7653. },
  7654. hasFocus: function() { return this.display.input.getField() == activeElt() },
  7655. isReadOnly: function() { return !!(this.options.readOnly || this.doc.cantEdit) },
  7656. scrollTo: methodOp(function (x, y) { scrollToCoords(this, x, y) }),
  7657. getScrollInfo: function() {
  7658. var scroller = this.display.scroller
  7659. return {left: scroller.scrollLeft, top: scroller.scrollTop,
  7660. height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight,
  7661. width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth,
  7662. clientHeight: displayHeight(this), clientWidth: displayWidth(this)}
  7663. },
  7664. scrollIntoView: methodOp(function(range, margin) {
  7665. if (range == null) {
  7666. range = {from: this.doc.sel.primary().head, to: null}
  7667. if (margin == null) { margin = this.options.cursorScrollMargin }
  7668. } else if (typeof range == "number") {
  7669. range = {from: Pos(range, 0), to: null}
  7670. } else if (range.from == null) {
  7671. range = {from: range, to: null}
  7672. }
  7673. if (!range.to) { range.to = range.from }
  7674. range.margin = margin || 0
  7675. if (range.from.line != null) {
  7676. scrollToRange(this, range)
  7677. } else {
  7678. scrollToCoordsRange(this, range.from, range.to, range.margin)
  7679. }
  7680. }),
  7681. setSize: methodOp(function(width, height) {
  7682. var this$1 = this;
  7683. var interpret = function (val) { return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val; }
  7684. if (width != null) { this.display.wrapper.style.width = interpret(width) }
  7685. if (height != null) { this.display.wrapper.style.height = interpret(height) }
  7686. if (this.options.lineWrapping) { clearLineMeasurementCache(this) }
  7687. var lineNo = this.display.viewFrom
  7688. this.doc.iter(lineNo, this.display.viewTo, function (line) {
  7689. if (line.widgets) { for (var i = 0; i < line.widgets.length; i++)
  7690. { if (line.widgets[i].noHScroll) { regLineChange(this$1, lineNo, "widget"); break } } }
  7691. ++lineNo
  7692. })
  7693. this.curOp.forceUpdate = true
  7694. signal(this, "refresh", this)
  7695. }),
  7696. operation: function(f){return runInOp(this, f)},
  7697. startOperation: function(){return startOperation(this)},
  7698. endOperation: function(){return endOperation(this)},
  7699. refresh: methodOp(function() {
  7700. var oldHeight = this.display.cachedTextHeight
  7701. regChange(this)
  7702. this.curOp.forceUpdate = true
  7703. clearCaches(this)
  7704. scrollToCoords(this, this.doc.scrollLeft, this.doc.scrollTop)
  7705. updateGutterSpace(this)
  7706. if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5)
  7707. { estimateLineHeights(this) }
  7708. signal(this, "refresh", this)
  7709. }),
  7710. swapDoc: methodOp(function(doc) {
  7711. var old = this.doc
  7712. old.cm = null
  7713. attachDoc(this, doc)
  7714. clearCaches(this)
  7715. this.display.input.reset()
  7716. scrollToCoords(this, doc.scrollLeft, doc.scrollTop)
  7717. this.curOp.forceScroll = true
  7718. signalLater(this, "swapDoc", this, old)
  7719. return old
  7720. }),
  7721. phrase: function(phraseText) {
  7722. var phrases = this.options.phrases
  7723. return phrases && Object.prototype.hasOwnProperty.call(phrases, phraseText) ? phrases[phraseText] : phraseText
  7724. },
  7725. getInputField: function(){return this.display.input.getField()},
  7726. getWrapperElement: function(){return this.display.wrapper},
  7727. getScrollerElement: function(){return this.display.scroller},
  7728. getGutterElement: function(){return this.display.gutters}
  7729. }
  7730. eventMixin(CodeMirror)
  7731. CodeMirror.registerHelper = function(type, name, value) {
  7732. if (!helpers.hasOwnProperty(type)) { helpers[type] = CodeMirror[type] = {_global: []} }
  7733. helpers[type][name] = value
  7734. }
  7735. CodeMirror.registerGlobalHelper = function(type, name, predicate, value) {
  7736. CodeMirror.registerHelper(type, name, value)
  7737. helpers[type]._global.push({pred: predicate, val: value})
  7738. }
  7739. }
  7740. // Used for horizontal relative motion. Dir is -1 or 1 (left or
  7741. // right), unit can be "char", "column" (like char, but doesn't
  7742. // cross line boundaries), "word" (across next word), or "group" (to
  7743. // the start of next group of word or non-word-non-whitespace
  7744. // chars). The visually param controls whether, in right-to-left
  7745. // text, direction 1 means to move towards the next index in the
  7746. // string, or towards the character to the right of the current
  7747. // position. The resulting position will have a hitSide=true
  7748. // property if it reached the end of the document.
  7749. function findPosH(doc, pos, dir, unit, visually) {
  7750. var oldPos = pos
  7751. var origDir = dir
  7752. var lineObj = getLine(doc, pos.line)
  7753. function findNextLine() {
  7754. var l = pos.line + dir
  7755. if (l < doc.first || l >= doc.first + doc.size) { return false }
  7756. pos = new Pos(l, pos.ch, pos.sticky)
  7757. return lineObj = getLine(doc, l)
  7758. }
  7759. function moveOnce(boundToLine) {
  7760. var next
  7761. if (visually) {
  7762. next = moveVisually(doc.cm, lineObj, pos, dir)
  7763. } else {
  7764. next = moveLogically(lineObj, pos, dir)
  7765. }
  7766. if (next == null) {
  7767. if (!boundToLine && findNextLine())
  7768. { pos = endOfLine(visually, doc.cm, lineObj, pos.line, dir) }
  7769. else
  7770. { return false }
  7771. } else {
  7772. pos = next
  7773. }
  7774. return true
  7775. }
  7776. if (unit == "char") {
  7777. moveOnce()
  7778. } else if (unit == "column") {
  7779. moveOnce(true)
  7780. } else if (unit == "word" || unit == "group") {
  7781. var sawType = null, group = unit == "group"
  7782. var helper = doc.cm && doc.cm.getHelper(pos, "wordChars")
  7783. for (var first = true;; first = false) {
  7784. if (dir < 0 && !moveOnce(!first)) { break }
  7785. var cur = lineObj.text.charAt(pos.ch) || "\n"
  7786. var type = isWordChar(cur, helper) ? "w"
  7787. : group && cur == "\n" ? "n"
  7788. : !group || /\s/.test(cur) ? null
  7789. : "p"
  7790. if (group && !first && !type) { type = "s" }
  7791. if (sawType && sawType != type) {
  7792. if (dir < 0) {dir = 1; moveOnce(); pos.sticky = "after"}
  7793. break
  7794. }
  7795. if (type) { sawType = type }
  7796. if (dir > 0 && !moveOnce(!first)) { break }
  7797. }
  7798. }
  7799. var result = skipAtomic(doc, pos, oldPos, origDir, true)
  7800. if (equalCursorPos(oldPos, result)) { result.hitSide = true }
  7801. return result
  7802. }
  7803. // For relative vertical movement. Dir may be -1 or 1. Unit can be
  7804. // "page" or "line". The resulting position will have a hitSide=true
  7805. // property if it reached the end of the document.
  7806. function findPosV(cm, pos, dir, unit) {
  7807. var doc = cm.doc, x = pos.left, y
  7808. if (unit == "page") {
  7809. var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight)
  7810. var moveAmount = Math.max(pageSize - .5 * textHeight(cm.display), 3)
  7811. y = (dir > 0 ? pos.bottom : pos.top) + dir * moveAmount
  7812. } else if (unit == "line") {
  7813. y = dir > 0 ? pos.bottom + 3 : pos.top - 3
  7814. }
  7815. var target
  7816. for (;;) {
  7817. target = coordsChar(cm, x, y)
  7818. if (!target.outside) { break }
  7819. if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break }
  7820. y += dir * 5
  7821. }
  7822. return target
  7823. }
  7824. // CONTENTEDITABLE INPUT STYLE
  7825. var ContentEditableInput = function(cm) {
  7826. this.cm = cm
  7827. this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null
  7828. this.polling = new Delayed()
  7829. this.composing = null
  7830. this.gracePeriod = false
  7831. this.readDOMTimeout = null
  7832. };
  7833. ContentEditableInput.prototype.init = function (display) {
  7834. var this$1 = this;
  7835. var input = this, cm = input.cm
  7836. var div = input.div = display.lineDiv
  7837. disableBrowserMagic(div, cm.options.spellcheck)
  7838. on(div, "paste", function (e) {
  7839. if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { return }
  7840. // IE doesn't fire input events, so we schedule a read for the pasted content in this way
  7841. if (ie_version <= 11) { setTimeout(operation(cm, function () { return this$1.updateFromDOM(); }), 20) }
  7842. })
  7843. on(div, "compositionstart", function (e) {
  7844. this$1.composing = {data: e.data, done: false}
  7845. })
  7846. on(div, "compositionupdate", function (e) {
  7847. if (!this$1.composing) { this$1.composing = {data: e.data, done: false} }
  7848. })
  7849. on(div, "compositionend", function (e) {
  7850. if (this$1.composing) {
  7851. if (e.data != this$1.composing.data) { this$1.readFromDOMSoon() }
  7852. this$1.composing.done = true
  7853. }
  7854. })
  7855. on(div, "touchstart", function () { return input.forceCompositionEnd(); })
  7856. on(div, "input", function () {
  7857. if (!this$1.composing) { this$1.readFromDOMSoon() }
  7858. })
  7859. function onCopyCut(e) {
  7860. if (signalDOMEvent(cm, e)) { return }
  7861. if (cm.somethingSelected()) {
  7862. setLastCopied({lineWise: false, text: cm.getSelections()})
  7863. if (e.type == "cut") { cm.replaceSelection("", null, "cut") }
  7864. } else if (!cm.options.lineWiseCopyCut) {
  7865. return
  7866. } else {
  7867. var ranges = copyableRanges(cm)
  7868. setLastCopied({lineWise: true, text: ranges.text})
  7869. if (e.type == "cut") {
  7870. cm.operation(function () {
  7871. cm.setSelections(ranges.ranges, 0, sel_dontScroll)
  7872. cm.replaceSelection("", null, "cut")
  7873. })
  7874. }
  7875. }
  7876. if (e.clipboardData) {
  7877. e.clipboardData.clearData()
  7878. var content = lastCopied.text.join("\n")
  7879. // iOS exposes the clipboard API, but seems to discard content inserted into it
  7880. e.clipboardData.setData("Text", content)
  7881. if (e.clipboardData.getData("Text") == content) {
  7882. e.preventDefault()
  7883. return
  7884. }
  7885. }
  7886. // Old-fashioned briefly-focus-a-textarea hack
  7887. var kludge = hiddenTextarea(), te = kludge.firstChild
  7888. cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild)
  7889. te.value = lastCopied.text.join("\n")
  7890. var hadFocus = document.activeElement
  7891. selectInput(te)
  7892. setTimeout(function () {
  7893. cm.display.lineSpace.removeChild(kludge)
  7894. hadFocus.focus()
  7895. if (hadFocus == div) { input.showPrimarySelection() }
  7896. }, 50)
  7897. }
  7898. on(div, "copy", onCopyCut)
  7899. on(div, "cut", onCopyCut)
  7900. };
  7901. ContentEditableInput.prototype.prepareSelection = function () {
  7902. var result = prepareSelection(this.cm, false)
  7903. result.focus = this.cm.state.focused
  7904. return result
  7905. };
  7906. ContentEditableInput.prototype.showSelection = function (info, takeFocus) {
  7907. if (!info || !this.cm.display.view.length) { return }
  7908. if (info.focus || takeFocus) { this.showPrimarySelection() }
  7909. this.showMultipleSelections(info)
  7910. };
  7911. ContentEditableInput.prototype.getSelection = function () {
  7912. return this.cm.display.wrapper.ownerDocument.getSelection()
  7913. };
  7914. ContentEditableInput.prototype.showPrimarySelection = function () {
  7915. var sel = this.getSelection(), cm = this.cm, prim = cm.doc.sel.primary()
  7916. var from = prim.from(), to = prim.to()
  7917. if (cm.display.viewTo == cm.display.viewFrom || from.line >= cm.display.viewTo || to.line < cm.display.viewFrom) {
  7918. sel.removeAllRanges()
  7919. return
  7920. }
  7921. var curAnchor = domToPos(cm, sel.anchorNode, sel.anchorOffset)
  7922. var curFocus = domToPos(cm, sel.focusNode, sel.focusOffset)
  7923. if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad &&
  7924. cmp(minPos(curAnchor, curFocus), from) == 0 &&
  7925. cmp(maxPos(curAnchor, curFocus), to) == 0)
  7926. { return }
  7927. var view = cm.display.view
  7928. var start = (from.line >= cm.display.viewFrom && posToDOM(cm, from)) ||
  7929. {node: view[0].measure.map[2], offset: 0}
  7930. var end = to.line < cm.display.viewTo && posToDOM(cm, to)
  7931. if (!end) {
  7932. var measure = view[view.length - 1].measure
  7933. var map = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map
  7934. end = {node: map[map.length - 1], offset: map[map.length - 2] - map[map.length - 3]}
  7935. }
  7936. if (!start || !end) {
  7937. sel.removeAllRanges()
  7938. return
  7939. }
  7940. var old = sel.rangeCount && sel.getRangeAt(0), rng
  7941. try { rng = range(start.node, start.offset, end.offset, end.node) }
  7942. catch(e) {} // Our model of the DOM might be outdated, in which case the range we try to set can be impossible
  7943. if (rng) {
  7944. if (!gecko && cm.state.focused) {
  7945. sel.collapse(start.node, start.offset)
  7946. if (!rng.collapsed) {
  7947. sel.removeAllRanges()
  7948. sel.addRange(rng)
  7949. }
  7950. } else {
  7951. sel.removeAllRanges()
  7952. sel.addRange(rng)
  7953. }
  7954. if (old && sel.anchorNode == null) { sel.addRange(old) }
  7955. else if (gecko) { this.startGracePeriod() }
  7956. }
  7957. this.rememberSelection()
  7958. };
  7959. ContentEditableInput.prototype.startGracePeriod = function () {
  7960. var this$1 = this;
  7961. clearTimeout(this.gracePeriod)
  7962. this.gracePeriod = setTimeout(function () {
  7963. this$1.gracePeriod = false
  7964. if (this$1.selectionChanged())
  7965. { this$1.cm.operation(function () { return this$1.cm.curOp.selectionChanged = true; }) }
  7966. }, 20)
  7967. };
  7968. ContentEditableInput.prototype.showMultipleSelections = function (info) {
  7969. removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors)
  7970. removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection)
  7971. };
  7972. ContentEditableInput.prototype.rememberSelection = function () {
  7973. var sel = this.getSelection()
  7974. this.lastAnchorNode = sel.anchorNode; this.lastAnchorOffset = sel.anchorOffset
  7975. this.lastFocusNode = sel.focusNode; this.lastFocusOffset = sel.focusOffset
  7976. };
  7977. ContentEditableInput.prototype.selectionInEditor = function () {
  7978. var sel = this.getSelection()
  7979. if (!sel.rangeCount) { return false }
  7980. var node = sel.getRangeAt(0).commonAncestorContainer
  7981. return contains(this.div, node)
  7982. };
  7983. ContentEditableInput.prototype.focus = function () {
  7984. if (this.cm.options.readOnly != "nocursor") {
  7985. if (!this.selectionInEditor())
  7986. { this.showSelection(this.prepareSelection(), true) }
  7987. this.div.focus()
  7988. }
  7989. };
  7990. ContentEditableInput.prototype.blur = function () { this.div.blur() };
  7991. ContentEditableInput.prototype.getField = function () { return this.div };
  7992. ContentEditableInput.prototype.supportsTouch = function () { return true };
  7993. ContentEditableInput.prototype.receivedFocus = function () {
  7994. var input = this
  7995. if (this.selectionInEditor())
  7996. { this.pollSelection() }
  7997. else
  7998. { runInOp(this.cm, function () { return input.cm.curOp.selectionChanged = true; }) }
  7999. function poll() {
  8000. if (input.cm.state.focused) {
  8001. input.pollSelection()
  8002. input.polling.set(input.cm.options.pollInterval, poll)
  8003. }
  8004. }
  8005. this.polling.set(this.cm.options.pollInterval, poll)
  8006. };
  8007. ContentEditableInput.prototype.selectionChanged = function () {
  8008. var sel = this.getSelection()
  8009. return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset ||
  8010. sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset
  8011. };
  8012. ContentEditableInput.prototype.pollSelection = function () {
  8013. if (this.readDOMTimeout != null || this.gracePeriod || !this.selectionChanged()) { return }
  8014. var sel = this.getSelection(), cm = this.cm
  8015. // On Android Chrome (version 56, at least), backspacing into an
  8016. // uneditable block element will put the cursor in that element,
  8017. // and then, because it's not editable, hide the virtual keyboard.
  8018. // Because Android doesn't allow us to actually detect backspace
  8019. // presses in a sane way, this code checks for when that happens
  8020. // and simulates a backspace press in this case.
  8021. if (android && chrome && this.cm.options.gutters.length && isInGutter(sel.anchorNode)) {
  8022. this.cm.triggerOnKeyDown({type: "keydown", keyCode: 8, preventDefault: Math.abs})
  8023. this.blur()
  8024. this.focus()
  8025. return
  8026. }
  8027. if (this.composing) { return }
  8028. this.rememberSelection()
  8029. var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset)
  8030. var head = domToPos(cm, sel.focusNode, sel.focusOffset)
  8031. if (anchor && head) { runInOp(cm, function () {
  8032. setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll)
  8033. if (anchor.bad || head.bad) { cm.curOp.selectionChanged = true }
  8034. }) }
  8035. };
  8036. ContentEditableInput.prototype.pollContent = function () {
  8037. if (this.readDOMTimeout != null) {
  8038. clearTimeout(this.readDOMTimeout)
  8039. this.readDOMTimeout = null
  8040. }
  8041. var cm = this.cm, display = cm.display, sel = cm.doc.sel.primary()
  8042. var from = sel.from(), to = sel.to()
  8043. if (from.ch == 0 && from.line > cm.firstLine())
  8044. { from = Pos(from.line - 1, getLine(cm.doc, from.line - 1).length) }
  8045. if (to.ch == getLine(cm.doc, to.line).text.length && to.line < cm.lastLine())
  8046. { to = Pos(to.line + 1, 0) }
  8047. if (from.line < display.viewFrom || to.line > display.viewTo - 1) { return false }
  8048. var fromIndex, fromLine, fromNode
  8049. if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) {
  8050. fromLine = lineNo(display.view[0].line)
  8051. fromNode = display.view[0].node
  8052. } else {
  8053. fromLine = lineNo(display.view[fromIndex].line)
  8054. fromNode = display.view[fromIndex - 1].node.nextSibling
  8055. }
  8056. var toIndex = findViewIndex(cm, to.line)
  8057. var toLine, toNode
  8058. if (toIndex == display.view.length - 1) {
  8059. toLine = display.viewTo - 1
  8060. toNode = display.lineDiv.lastChild
  8061. } else {
  8062. toLine = lineNo(display.view[toIndex + 1].line) - 1
  8063. toNode = display.view[toIndex + 1].node.previousSibling
  8064. }
  8065. if (!fromNode) { return false }
  8066. var newText = cm.doc.splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine))
  8067. var oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length))
  8068. while (newText.length > 1 && oldText.length > 1) {
  8069. if (lst(newText) == lst(oldText)) { newText.pop(); oldText.pop(); toLine-- }
  8070. else if (newText[0] == oldText[0]) { newText.shift(); oldText.shift(); fromLine++ }
  8071. else { break }
  8072. }
  8073. var cutFront = 0, cutEnd = 0
  8074. var newTop = newText[0], oldTop = oldText[0], maxCutFront = Math.min(newTop.length, oldTop.length)
  8075. while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront))
  8076. { ++cutFront }
  8077. var newBot = lst(newText), oldBot = lst(oldText)
  8078. var maxCutEnd = Math.min(newBot.length - (newText.length == 1 ? cutFront : 0),
  8079. oldBot.length - (oldText.length == 1 ? cutFront : 0))
  8080. while (cutEnd < maxCutEnd &&
  8081. newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1))
  8082. { ++cutEnd }
  8083. // Try to move start of change to start of selection if ambiguous
  8084. if (newText.length == 1 && oldText.length == 1 && fromLine == from.line) {
  8085. while (cutFront && cutFront > from.ch &&
  8086. newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) {
  8087. cutFront--
  8088. cutEnd++
  8089. }
  8090. }
  8091. newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd).replace(/^\u200b+/, "")
  8092. newText[0] = newText[0].slice(cutFront).replace(/\u200b+$/, "")
  8093. var chFrom = Pos(fromLine, cutFront)
  8094. var chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0)
  8095. if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) {
  8096. replaceRange(cm.doc, newText, chFrom, chTo, "+input")
  8097. return true
  8098. }
  8099. };
  8100. ContentEditableInput.prototype.ensurePolled = function () {
  8101. this.forceCompositionEnd()
  8102. };
  8103. ContentEditableInput.prototype.reset = function () {
  8104. this.forceCompositionEnd()
  8105. };
  8106. ContentEditableInput.prototype.forceCompositionEnd = function () {
  8107. if (!this.composing) { return }
  8108. clearTimeout(this.readDOMTimeout)
  8109. this.composing = null
  8110. this.updateFromDOM()
  8111. this.div.blur()
  8112. this.div.focus()
  8113. };
  8114. ContentEditableInput.prototype.readFromDOMSoon = function () {
  8115. var this$1 = this;
  8116. if (this.readDOMTimeout != null) { return }
  8117. this.readDOMTimeout = setTimeout(function () {
  8118. this$1.readDOMTimeout = null
  8119. if (this$1.composing) {
  8120. if (this$1.composing.done) { this$1.composing = null }
  8121. else { return }
  8122. }
  8123. this$1.updateFromDOM()
  8124. }, 80)
  8125. };
  8126. ContentEditableInput.prototype.updateFromDOM = function () {
  8127. var this$1 = this;
  8128. if (this.cm.isReadOnly() || !this.pollContent())
  8129. { runInOp(this.cm, function () { return regChange(this$1.cm); }) }
  8130. };
  8131. ContentEditableInput.prototype.setUneditable = function (node) {
  8132. node.contentEditable = "false"
  8133. };
  8134. ContentEditableInput.prototype.onKeyPress = function (e) {
  8135. if (e.charCode == 0 || this.composing) { return }
  8136. e.preventDefault()
  8137. if (!this.cm.isReadOnly())
  8138. { operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0) }
  8139. };
  8140. ContentEditableInput.prototype.readOnlyChanged = function (val) {
  8141. this.div.contentEditable = String(val != "nocursor")
  8142. };
  8143. ContentEditableInput.prototype.onContextMenu = function () {};
  8144. ContentEditableInput.prototype.resetPosition = function () {};
  8145. ContentEditableInput.prototype.needsContentAttribute = true
  8146. function posToDOM(cm, pos) {
  8147. var view = findViewForLine(cm, pos.line)
  8148. if (!view || view.hidden) { return null }
  8149. var line = getLine(cm.doc, pos.line)
  8150. var info = mapFromLineView(view, line, pos.line)
  8151. var order = getOrder(line, cm.doc.direction), side = "left"
  8152. if (order) {
  8153. var partPos = getBidiPartAt(order, pos.ch)
  8154. side = partPos % 2 ? "right" : "left"
  8155. }
  8156. var result = nodeAndOffsetInLineMap(info.map, pos.ch, side)
  8157. result.offset = result.collapse == "right" ? result.end : result.start
  8158. return result
  8159. }
  8160. function isInGutter(node) {
  8161. for (var scan = node; scan; scan = scan.parentNode)
  8162. { if (/CodeMirror-gutter-wrapper/.test(scan.className)) { return true } }
  8163. return false
  8164. }
  8165. function badPos(pos, bad) { if (bad) { pos.bad = true; } return pos }
  8166. function domTextBetween(cm, from, to, fromLine, toLine) {
  8167. var text = "", closing = false, lineSep = cm.doc.lineSeparator(), extraLinebreak = false
  8168. function recognizeMarker(id) { return function (marker) { return marker.id == id; } }
  8169. function close() {
  8170. if (closing) {
  8171. text += lineSep
  8172. if (extraLinebreak) { text += lineSep }
  8173. closing = extraLinebreak = false
  8174. }
  8175. }
  8176. function addText(str) {
  8177. if (str) {
  8178. close()
  8179. text += str
  8180. }
  8181. }
  8182. function walk(node) {
  8183. if (node.nodeType == 1) {
  8184. var cmText = node.getAttribute("cm-text")
  8185. if (cmText) {
  8186. addText(cmText)
  8187. return
  8188. }
  8189. var markerID = node.getAttribute("cm-marker"), range
  8190. if (markerID) {
  8191. var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID))
  8192. if (found.length && (range = found[0].find(0)))
  8193. { addText(getBetween(cm.doc, range.from, range.to).join(lineSep)) }
  8194. return
  8195. }
  8196. if (node.getAttribute("contenteditable") == "false") { return }
  8197. var isBlock = /^(pre|div|p|li|table|br)$/i.test(node.nodeName)
  8198. if (!/^br$/i.test(node.nodeName) && node.textContent.length == 0) { return }
  8199. if (isBlock) { close() }
  8200. for (var i = 0; i < node.childNodes.length; i++)
  8201. { walk(node.childNodes[i]) }
  8202. if (/^(pre|p)$/i.test(node.nodeName)) { extraLinebreak = true }
  8203. if (isBlock) { closing = true }
  8204. } else if (node.nodeType == 3) {
  8205. addText(node.nodeValue.replace(/\u200b/g, "").replace(/\u00a0/g, " "))
  8206. }
  8207. }
  8208. for (;;) {
  8209. walk(from)
  8210. if (from == to) { break }
  8211. from = from.nextSibling
  8212. extraLinebreak = false
  8213. }
  8214. return text
  8215. }
  8216. function domToPos(cm, node, offset) {
  8217. var lineNode
  8218. if (node == cm.display.lineDiv) {
  8219. lineNode = cm.display.lineDiv.childNodes[offset]
  8220. if (!lineNode) { return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true) }
  8221. node = null; offset = 0
  8222. } else {
  8223. for (lineNode = node;; lineNode = lineNode.parentNode) {
  8224. if (!lineNode || lineNode == cm.display.lineDiv) { return null }
  8225. if (lineNode.parentNode && lineNode.parentNode == cm.display.lineDiv) { break }
  8226. }
  8227. }
  8228. for (var i = 0; i < cm.display.view.length; i++) {
  8229. var lineView = cm.display.view[i]
  8230. if (lineView.node == lineNode)
  8231. { return locateNodeInLineView(lineView, node, offset) }
  8232. }
  8233. }
  8234. function locateNodeInLineView(lineView, node, offset) {
  8235. var wrapper = lineView.text.firstChild, bad = false
  8236. if (!node || !contains(wrapper, node)) { return badPos(Pos(lineNo(lineView.line), 0), true) }
  8237. if (node == wrapper) {
  8238. bad = true
  8239. node = wrapper.childNodes[offset]
  8240. offset = 0
  8241. if (!node) {
  8242. var line = lineView.rest ? lst(lineView.rest) : lineView.line
  8243. return badPos(Pos(lineNo(line), line.text.length), bad)
  8244. }
  8245. }
  8246. var textNode = node.nodeType == 3 ? node : null, topNode = node
  8247. if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) {
  8248. textNode = node.firstChild
  8249. if (offset) { offset = textNode.nodeValue.length }
  8250. }
  8251. while (topNode.parentNode != wrapper) { topNode = topNode.parentNode }
  8252. var measure = lineView.measure, maps = measure.maps
  8253. function find(textNode, topNode, offset) {
  8254. for (var i = -1; i < (maps ? maps.length : 0); i++) {
  8255. var map = i < 0 ? measure.map : maps[i]
  8256. for (var j = 0; j < map.length; j += 3) {
  8257. var curNode = map[j + 2]
  8258. if (curNode == textNode || curNode == topNode) {
  8259. var line = lineNo(i < 0 ? lineView.line : lineView.rest[i])
  8260. var ch = map[j] + offset
  8261. if (offset < 0 || curNode != textNode) { ch = map[j + (offset ? 1 : 0)] }
  8262. return Pos(line, ch)
  8263. }
  8264. }
  8265. }
  8266. }
  8267. var found = find(textNode, topNode, offset)
  8268. if (found) { return badPos(found, bad) }
  8269. // FIXME this is all really shaky. might handle the few cases it needs to handle, but likely to cause problems
  8270. for (var after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) {
  8271. found = find(after, after.firstChild, 0)
  8272. if (found)
  8273. { return badPos(Pos(found.line, found.ch - dist), bad) }
  8274. else
  8275. { dist += after.textContent.length }
  8276. }
  8277. for (var before = topNode.previousSibling, dist$1 = offset; before; before = before.previousSibling) {
  8278. found = find(before, before.firstChild, -1)
  8279. if (found)
  8280. { return badPos(Pos(found.line, found.ch + dist$1), bad) }
  8281. else
  8282. { dist$1 += before.textContent.length }
  8283. }
  8284. }
  8285. // TEXTAREA INPUT STYLE
  8286. var TextareaInput = function(cm) {
  8287. this.cm = cm
  8288. // See input.poll and input.reset
  8289. this.prevInput = ""
  8290. // Flag that indicates whether we expect input to appear real soon
  8291. // now (after some event like 'keypress' or 'input') and are
  8292. // polling intensively.
  8293. this.pollingFast = false
  8294. // Self-resetting timeout for the poller
  8295. this.polling = new Delayed()
  8296. // Used to work around IE issue with selection being forgotten when focus moves away from textarea
  8297. this.hasSelection = false
  8298. this.composing = null
  8299. };
  8300. TextareaInput.prototype.init = function (display) {
  8301. var this$1 = this;
  8302. var input = this, cm = this.cm
  8303. this.createField(display)
  8304. var te = this.textarea
  8305. display.wrapper.insertBefore(this.wrapper, display.wrapper.firstChild)
  8306. // Needed to hide big blue blinking cursor on Mobile Safari (doesn't seem to work in iOS 8 anymore)
  8307. if (ios) { te.style.width = "0px" }
  8308. on(te, "input", function () {
  8309. if (ie && ie_version >= 9 && this$1.hasSelection) { this$1.hasSelection = null }
  8310. input.poll()
  8311. })
  8312. on(te, "paste", function (e) {
  8313. if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { return }
  8314. cm.state.pasteIncoming = true
  8315. input.fastPoll()
  8316. })
  8317. function prepareCopyCut(e) {
  8318. if (signalDOMEvent(cm, e)) { return }
  8319. if (cm.somethingSelected()) {
  8320. setLastCopied({lineWise: false, text: cm.getSelections()})
  8321. } else if (!cm.options.lineWiseCopyCut) {
  8322. return
  8323. } else {
  8324. var ranges = copyableRanges(cm)
  8325. setLastCopied({lineWise: true, text: ranges.text})
  8326. if (e.type == "cut") {
  8327. cm.setSelections(ranges.ranges, null, sel_dontScroll)
  8328. } else {
  8329. input.prevInput = ""
  8330. te.value = ranges.text.join("\n")
  8331. selectInput(te)
  8332. }
  8333. }
  8334. if (e.type == "cut") { cm.state.cutIncoming = true }
  8335. }
  8336. on(te, "cut", prepareCopyCut)
  8337. on(te, "copy", prepareCopyCut)
  8338. on(display.scroller, "paste", function (e) {
  8339. if (eventInWidget(display, e) || signalDOMEvent(cm, e)) { return }
  8340. cm.state.pasteIncoming = true
  8341. input.focus()
  8342. })
  8343. // Prevent normal selection in the editor (we handle our own)
  8344. on(display.lineSpace, "selectstart", function (e) {
  8345. if (!eventInWidget(display, e)) { e_preventDefault(e) }
  8346. })
  8347. on(te, "compositionstart", function () {
  8348. var start = cm.getCursor("from")
  8349. if (input.composing) { input.composing.range.clear() }
  8350. input.composing = {
  8351. start: start,
  8352. range: cm.markText(start, cm.getCursor("to"), {className: "CodeMirror-composing"})
  8353. }
  8354. })
  8355. on(te, "compositionend", function () {
  8356. if (input.composing) {
  8357. input.poll()
  8358. input.composing.range.clear()
  8359. input.composing = null
  8360. }
  8361. })
  8362. };
  8363. TextareaInput.prototype.createField = function (_display) {
  8364. // Wraps and hides input textarea
  8365. this.wrapper = hiddenTextarea()
  8366. // The semihidden textarea that is focused when the editor is
  8367. // focused, and receives input.
  8368. this.textarea = this.wrapper.firstChild
  8369. };
  8370. TextareaInput.prototype.prepareSelection = function () {
  8371. // Redraw the selection and/or cursor
  8372. var cm = this.cm, display = cm.display, doc = cm.doc
  8373. var result = prepareSelection(cm)
  8374. // Move the hidden textarea near the cursor to prevent scrolling artifacts
  8375. if (cm.options.moveInputWithCursor) {
  8376. var headPos = cursorCoords(cm, doc.sel.primary().head, "div")
  8377. var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect()
  8378. result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10,
  8379. headPos.top + lineOff.top - wrapOff.top))
  8380. result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10,
  8381. headPos.left + lineOff.left - wrapOff.left))
  8382. }
  8383. return result
  8384. };
  8385. TextareaInput.prototype.showSelection = function (drawn) {
  8386. var cm = this.cm, display = cm.display
  8387. removeChildrenAndAdd(display.cursorDiv, drawn.cursors)
  8388. removeChildrenAndAdd(display.selectionDiv, drawn.selection)
  8389. if (drawn.teTop != null) {
  8390. this.wrapper.style.top = drawn.teTop + "px"
  8391. this.wrapper.style.left = drawn.teLeft + "px"
  8392. }
  8393. };
  8394. // Reset the input to correspond to the selection (or to be empty,
  8395. // when not typing and nothing is selected)
  8396. TextareaInput.prototype.reset = function (typing) {
  8397. if (this.contextMenuPending || this.composing) { return }
  8398. var cm = this.cm
  8399. if (cm.somethingSelected()) {
  8400. this.prevInput = ""
  8401. var content = cm.getSelection()
  8402. this.textarea.value = content
  8403. if (cm.state.focused) { selectInput(this.textarea) }
  8404. if (ie && ie_version >= 9) { this.hasSelection = content }
  8405. } else if (!typing) {
  8406. this.prevInput = this.textarea.value = ""
  8407. if (ie && ie_version >= 9) { this.hasSelection = null }
  8408. }
  8409. };
  8410. TextareaInput.prototype.getField = function () { return this.textarea };
  8411. TextareaInput.prototype.supportsTouch = function () { return false };
  8412. TextareaInput.prototype.focus = function () {
  8413. if (this.cm.options.readOnly != "nocursor" && (!mobile || activeElt() != this.textarea)) {
  8414. try { this.textarea.focus() }
  8415. catch (e) {} // IE8 will throw if the textarea is display: none or not in DOM
  8416. }
  8417. };
  8418. TextareaInput.prototype.blur = function () { this.textarea.blur() };
  8419. TextareaInput.prototype.resetPosition = function () {
  8420. this.wrapper.style.top = this.wrapper.style.left = 0
  8421. };
  8422. TextareaInput.prototype.receivedFocus = function () { this.slowPoll() };
  8423. // Poll for input changes, using the normal rate of polling. This
  8424. // runs as long as the editor is focused.
  8425. TextareaInput.prototype.slowPoll = function () {
  8426. var this$1 = this;
  8427. if (this.pollingFast) { return }
  8428. this.polling.set(this.cm.options.pollInterval, function () {
  8429. this$1.poll()
  8430. if (this$1.cm.state.focused) { this$1.slowPoll() }
  8431. })
  8432. };
  8433. // When an event has just come in that is likely to add or change
  8434. // something in the input textarea, we poll faster, to ensure that
  8435. // the change appears on the screen quickly.
  8436. TextareaInput.prototype.fastPoll = function () {
  8437. var missed = false, input = this
  8438. input.pollingFast = true
  8439. function p() {
  8440. var changed = input.poll()
  8441. if (!changed && !missed) {missed = true; input.polling.set(60, p)}
  8442. else {input.pollingFast = false; input.slowPoll()}
  8443. }
  8444. input.polling.set(20, p)
  8445. };
  8446. // Read input from the textarea, and update the document to match.
  8447. // When something is selected, it is present in the textarea, and
  8448. // selected (unless it is huge, in which case a placeholder is
  8449. // used). When nothing is selected, the cursor sits after previously
  8450. // seen text (can be empty), which is stored in prevInput (we must
  8451. // not reset the textarea when typing, because that breaks IME).
  8452. TextareaInput.prototype.poll = function () {
  8453. var this$1 = this;
  8454. var cm = this.cm, input = this.textarea, prevInput = this.prevInput
  8455. // Since this is called a *lot*, try to bail out as cheaply as
  8456. // possible when it is clear that nothing happened. hasSelection
  8457. // will be the case when there is a lot of text in the textarea,
  8458. // in which case reading its value would be expensive.
  8459. if (this.contextMenuPending || !cm.state.focused ||
  8460. (hasSelection(input) && !prevInput && !this.composing) ||
  8461. cm.isReadOnly() || cm.options.disableInput || cm.state.keySeq)
  8462. { return false }
  8463. var text = input.value
  8464. // If nothing changed, bail.
  8465. if (text == prevInput && !cm.somethingSelected()) { return false }
  8466. // Work around nonsensical selection resetting in IE9/10, and
  8467. // inexplicable appearance of private area unicode characters on
  8468. // some key combos in Mac (#2689).
  8469. if (ie && ie_version >= 9 && this.hasSelection === text ||
  8470. mac && /[\uf700-\uf7ff]/.test(text)) {
  8471. cm.display.input.reset()
  8472. return false
  8473. }
  8474. if (cm.doc.sel == cm.display.selForContextMenu) {
  8475. var first = text.charCodeAt(0)
  8476. if (first == 0x200b && !prevInput) { prevInput = "\u200b" }
  8477. if (first == 0x21da) { this.reset(); return this.cm.execCommand("undo") }
  8478. }
  8479. // Find the part of the input that is actually new
  8480. var same = 0, l = Math.min(prevInput.length, text.length)
  8481. while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) { ++same }
  8482. runInOp(cm, function () {
  8483. applyTextInput(cm, text.slice(same), prevInput.length - same,
  8484. null, this$1.composing ? "*compose" : null)
  8485. // Don't leave long text in the textarea, since it makes further polling slow
  8486. if (text.length > 1000 || text.indexOf("\n") > -1) { input.value = this$1.prevInput = "" }
  8487. else { this$1.prevInput = text }
  8488. if (this$1.composing) {
  8489. this$1.composing.range.clear()
  8490. this$1.composing.range = cm.markText(this$1.composing.start, cm.getCursor("to"),
  8491. {className: "CodeMirror-composing"})
  8492. }
  8493. })
  8494. return true
  8495. };
  8496. TextareaInput.prototype.ensurePolled = function () {
  8497. if (this.pollingFast && this.poll()) { this.pollingFast = false }
  8498. };
  8499. TextareaInput.prototype.onKeyPress = function () {
  8500. if (ie && ie_version >= 9) { this.hasSelection = null }
  8501. this.fastPoll()
  8502. };
  8503. TextareaInput.prototype.onContextMenu = function (e) {
  8504. var input = this, cm = input.cm, display = cm.display, te = input.textarea
  8505. var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop
  8506. if (!pos || presto) { return } // Opera is difficult.
  8507. // Reset the current text selection only if the click is done outside of the selection
  8508. // and 'resetSelectionOnContextMenu' option is true.
  8509. var reset = cm.options.resetSelectionOnContextMenu
  8510. if (reset && cm.doc.sel.contains(pos) == -1)
  8511. { operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll) }
  8512. var oldCSS = te.style.cssText, oldWrapperCSS = input.wrapper.style.cssText
  8513. input.wrapper.style.cssText = "position: absolute"
  8514. var wrapperBox = input.wrapper.getBoundingClientRect()
  8515. 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);"
  8516. var oldScrollY
  8517. if (webkit) { oldScrollY = window.scrollY } // Work around Chrome issue (#2712)
  8518. display.input.focus()
  8519. if (webkit) { window.scrollTo(null, oldScrollY) }
  8520. display.input.reset()
  8521. // Adds "Select all" to context menu in FF
  8522. if (!cm.somethingSelected()) { te.value = input.prevInput = " " }
  8523. input.contextMenuPending = true
  8524. display.selForContextMenu = cm.doc.sel
  8525. clearTimeout(display.detectingSelectAll)
  8526. // Select-all will be greyed out if there's nothing to select, so
  8527. // this adds a zero-width space so that we can later check whether
  8528. // it got selected.
  8529. function prepareSelectAllHack() {
  8530. if (te.selectionStart != null) {
  8531. var selected = cm.somethingSelected()
  8532. var extval = "\u200b" + (selected ? te.value : "")
  8533. te.value = "\u21da" // Used to catch context-menu undo
  8534. te.value = extval
  8535. input.prevInput = selected ? "" : "\u200b"
  8536. te.selectionStart = 1; te.selectionEnd = extval.length
  8537. // Re-set this, in case some other handler touched the
  8538. // selection in the meantime.
  8539. display.selForContextMenu = cm.doc.sel
  8540. }
  8541. }
  8542. function rehide() {
  8543. input.contextMenuPending = false
  8544. input.wrapper.style.cssText = oldWrapperCSS
  8545. te.style.cssText = oldCSS
  8546. if (ie && ie_version < 9) { display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos) }
  8547. // Try to detect the user choosing select-all
  8548. if (te.selectionStart != null) {
  8549. if (!ie || (ie && ie_version < 9)) { prepareSelectAllHack() }
  8550. var i = 0, poll = function () {
  8551. if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0 &&
  8552. te.selectionEnd > 0 && input.prevInput == "\u200b") {
  8553. operation(cm, selectAll)(cm)
  8554. } else if (i++ < 10) {
  8555. display.detectingSelectAll = setTimeout(poll, 500)
  8556. } else {
  8557. display.selForContextMenu = null
  8558. display.input.reset()
  8559. }
  8560. }
  8561. display.detectingSelectAll = setTimeout(poll, 200)
  8562. }
  8563. }
  8564. if (ie && ie_version >= 9) { prepareSelectAllHack() }
  8565. if (captureRightClick) {
  8566. e_stop(e)
  8567. var mouseup = function () {
  8568. off(window, "mouseup", mouseup)
  8569. setTimeout(rehide, 20)
  8570. }
  8571. on(window, "mouseup", mouseup)
  8572. } else {
  8573. setTimeout(rehide, 50)
  8574. }
  8575. };
  8576. TextareaInput.prototype.readOnlyChanged = function (val) {
  8577. if (!val) { this.reset() }
  8578. this.textarea.disabled = val == "nocursor"
  8579. };
  8580. TextareaInput.prototype.setUneditable = function () {};
  8581. TextareaInput.prototype.needsContentAttribute = false
  8582. function fromTextArea(textarea, options) {
  8583. options = options ? copyObj(options) : {}
  8584. options.value = textarea.value
  8585. if (!options.tabindex && textarea.tabIndex)
  8586. { options.tabindex = textarea.tabIndex }
  8587. if (!options.placeholder && textarea.placeholder)
  8588. { options.placeholder = textarea.placeholder }
  8589. // Set autofocus to true if this textarea is focused, or if it has
  8590. // autofocus and no other element is focused.
  8591. if (options.autofocus == null) {
  8592. var hasFocus = activeElt()
  8593. options.autofocus = hasFocus == textarea ||
  8594. textarea.getAttribute("autofocus") != null && hasFocus == document.body
  8595. }
  8596. function save() {textarea.value = cm.getValue()}
  8597. var realSubmit
  8598. if (textarea.form) {
  8599. on(textarea.form, "submit", save)
  8600. // Deplorable hack to make the submit method do the right thing.
  8601. if (!options.leaveSubmitMethodAlone) {
  8602. var form = textarea.form
  8603. realSubmit = form.submit
  8604. try {
  8605. var wrappedSubmit = form.submit = function () {
  8606. save()
  8607. form.submit = realSubmit
  8608. form.submit()
  8609. form.submit = wrappedSubmit
  8610. }
  8611. } catch(e) {}
  8612. }
  8613. }
  8614. options.finishInit = function (cm) {
  8615. cm.save = save
  8616. cm.getTextArea = function () { return textarea; }
  8617. cm.toTextArea = function () {
  8618. cm.toTextArea = isNaN // Prevent this from being ran twice
  8619. save()
  8620. textarea.parentNode.removeChild(cm.getWrapperElement())
  8621. textarea.style.display = ""
  8622. if (textarea.form) {
  8623. off(textarea.form, "submit", save)
  8624. if (typeof textarea.form.submit == "function")
  8625. { textarea.form.submit = realSubmit }
  8626. }
  8627. }
  8628. }
  8629. textarea.style.display = "none"
  8630. var cm = CodeMirror(function (node) { return textarea.parentNode.insertBefore(node, textarea.nextSibling); },
  8631. options)
  8632. return cm
  8633. }
  8634. function addLegacyProps(CodeMirror) {
  8635. CodeMirror.off = off
  8636. CodeMirror.on = on
  8637. CodeMirror.wheelEventPixels = wheelEventPixels
  8638. CodeMirror.Doc = Doc
  8639. CodeMirror.splitLines = splitLinesAuto
  8640. CodeMirror.countColumn = countColumn
  8641. CodeMirror.findColumn = findColumn
  8642. CodeMirror.isWordChar = isWordCharBasic
  8643. CodeMirror.Pass = Pass
  8644. CodeMirror.signal = signal
  8645. CodeMirror.Line = Line
  8646. CodeMirror.changeEnd = changeEnd
  8647. CodeMirror.scrollbarModel = scrollbarModel
  8648. CodeMirror.Pos = Pos
  8649. CodeMirror.cmpPos = cmp
  8650. CodeMirror.modes = modes
  8651. CodeMirror.mimeModes = mimeModes
  8652. CodeMirror.resolveMode = resolveMode
  8653. CodeMirror.getMode = getMode
  8654. CodeMirror.modeExtensions = modeExtensions
  8655. CodeMirror.extendMode = extendMode
  8656. CodeMirror.copyState = copyState
  8657. CodeMirror.startState = startState
  8658. CodeMirror.innerMode = innerMode
  8659. CodeMirror.commands = commands
  8660. CodeMirror.keyMap = keyMap
  8661. CodeMirror.keyName = keyName
  8662. CodeMirror.isModifierKey = isModifierKey
  8663. CodeMirror.lookupKey = lookupKey
  8664. CodeMirror.normalizeKeyMap = normalizeKeyMap
  8665. CodeMirror.StringStream = StringStream
  8666. CodeMirror.SharedTextMarker = SharedTextMarker
  8667. CodeMirror.TextMarker = TextMarker
  8668. CodeMirror.LineWidget = LineWidget
  8669. CodeMirror.e_preventDefault = e_preventDefault
  8670. CodeMirror.e_stopPropagation = e_stopPropagation
  8671. CodeMirror.e_stop = e_stop
  8672. CodeMirror.addClass = addClass
  8673. CodeMirror.contains = contains
  8674. CodeMirror.rmClass = rmClass
  8675. CodeMirror.keyNames = keyNames
  8676. }
  8677. // EDITOR CONSTRUCTOR
  8678. defineOptions(CodeMirror)
  8679. addEditorMethods(CodeMirror)
  8680. // Set up methods on CodeMirror's prototype to redirect to the editor's document.
  8681. var dontDelegate = "iter insert remove copy getEditor constructor".split(" ")
  8682. for (var prop in Doc.prototype) { if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0)
  8683. { CodeMirror.prototype[prop] = (function(method) {
  8684. return function() {return method.apply(this.doc, arguments)}
  8685. })(Doc.prototype[prop]) } }
  8686. eventMixin(Doc)
  8687. // INPUT HANDLING
  8688. CodeMirror.inputStyles = {"textarea": TextareaInput, "contenteditable": ContentEditableInput}
  8689. // MODE DEFINITION AND QUERYING
  8690. // Extra arguments are stored as the mode's dependencies, which is
  8691. // used by (legacy) mechanisms like loadmode.js to automatically
  8692. // load a mode. (Preferred mechanism is the require/define calls.)
  8693. CodeMirror.defineMode = function(name/*, mode, …*/) {
  8694. if (!CodeMirror.defaults.mode && name != "null") { CodeMirror.defaults.mode = name }
  8695. defineMode.apply(this, arguments)
  8696. }
  8697. CodeMirror.defineMIME = defineMIME
  8698. // Minimal default mode.
  8699. CodeMirror.defineMode("null", function () { return ({token: function (stream) { return stream.skipToEnd(); }}); })
  8700. CodeMirror.defineMIME("text/plain", "null")
  8701. // EXTENSIONS
  8702. CodeMirror.defineExtension = function (name, func) {
  8703. CodeMirror.prototype[name] = func
  8704. }
  8705. CodeMirror.defineDocExtension = function (name, func) {
  8706. Doc.prototype[name] = func
  8707. }
  8708. CodeMirror.fromTextArea = fromTextArea
  8709. addLegacyProps(CodeMirror)
  8710. CodeMirror.version = "5.40.2"
  8711. return CodeMirror;
  8712. })));