codemirror.js 359 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654
  1. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  2. // Distributed under an MIT license: http://codemirror.net/LICENSE
  3. // This is CodeMirror (http://codemirror.net), a code editor
  4. // implemented in JavaScript on top of the browser's DOM.
  5. //
  6. // You can find some technical background for some of the code below
  7. // at http://marijnhaverbeke.nl/blog/#cm-internals .
  8. (function (global, factory) {
  9. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  10. typeof define === 'function' && define.amd ? define(factory) :
  11. (global.CodeMirror = factory());
  12. }(this, (function () { 'use strict';
  13. // Kludges for bugs and behavior differences that can't be feature
  14. // detected are enabled based on userAgent etc sniffing.
  15. var userAgent = navigator.userAgent
  16. var platform = navigator.platform
  17. var gecko = /gecko\/\d/i.test(userAgent)
  18. var ie_upto10 = /MSIE \d/.test(userAgent)
  19. var ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(userAgent)
  20. var edge = /Edge\/(\d+)/.exec(userAgent)
  21. var ie = ie_upto10 || ie_11up || edge
  22. var ie_version = ie && (ie_upto10 ? document.documentMode || 6 : +(edge || ie_11up)[1])
  23. var webkit = !edge && /WebKit\//.test(userAgent)
  24. var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(userAgent)
  25. var chrome = !edge && /Chrome\//.test(userAgent)
  26. var presto = /Opera\//.test(userAgent)
  27. var safari = /Apple Computer/.test(navigator.vendor)
  28. var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(userAgent)
  29. var phantom = /PhantomJS/.test(userAgent)
  30. var ios = !edge && /AppleWebKit/.test(userAgent) && /Mobile\/\w+/.test(userAgent)
  31. var android = /Android/.test(userAgent)
  32. // This is woefully incomplete. Suggestions for alternative methods welcome.
  33. var mobile = ios || android || /webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(userAgent)
  34. var mac = ios || /Mac/.test(platform)
  35. var chromeOS = /\bCrOS\b/.test(userAgent)
  36. var windows = /win/i.test(platform)
  37. var presto_version = presto && userAgent.match(/Version\/(\d*\.\d*)/)
  38. if (presto_version) { presto_version = Number(presto_version[1]) }
  39. if (presto_version && presto_version >= 15) { presto = false; webkit = true }
  40. // Some browsers use the wrong event properties to signal cmd/ctrl on OS X
  41. var flipCtrlCmd = mac && (qtwebkit || presto && (presto_version == null || presto_version < 12.11))
  42. var captureRightClick = gecko || (ie && ie_version >= 9)
  43. function classTest(cls) { return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*") }
  44. var rmClass = function(node, cls) {
  45. var current = node.className
  46. var match = classTest(cls).exec(current)
  47. if (match) {
  48. var after = current.slice(match.index + match[0].length)
  49. node.className = current.slice(0, match.index) + (after ? match[1] + after : "")
  50. }
  51. }
  52. function removeChildren(e) {
  53. for (var count = e.childNodes.length; count > 0; --count)
  54. { e.removeChild(e.firstChild) }
  55. return e
  56. }
  57. function removeChildrenAndAdd(parent, e) {
  58. return removeChildren(parent).appendChild(e)
  59. }
  60. function elt(tag, content, className, style) {
  61. var e = document.createElement(tag)
  62. if (className) { e.className = className }
  63. if (style) { e.style.cssText = style }
  64. if (typeof content == "string") { e.appendChild(document.createTextNode(content)) }
  65. else if (content) { for (var i = 0; i < content.length; ++i) { e.appendChild(content[i]) } }
  66. return e
  67. }
  68. // wrapper for elt, which removes the elt from the accessibility tree
  69. function eltP(tag, content, className, style) {
  70. var e = elt(tag, content, className, style)
  71. e.setAttribute("role", "presentation")
  72. return e
  73. }
  74. var range
  75. if (document.createRange) { range = function(node, start, end, endNode) {
  76. var r = document.createRange()
  77. r.setEnd(endNode || node, end)
  78. r.setStart(node, start)
  79. return r
  80. } }
  81. else { range = function(node, start, end) {
  82. var r = document.body.createTextRange()
  83. try { r.moveToElementText(node.parentNode) }
  84. catch(e) { return r }
  85. r.collapse(true)
  86. r.moveEnd("character", end)
  87. r.moveStart("character", start)
  88. return r
  89. } }
  90. function contains(parent, child) {
  91. if (child.nodeType == 3) // Android browser always returns false when child is a textnode
  92. { child = child.parentNode }
  93. if (parent.contains)
  94. { return parent.contains(child) }
  95. do {
  96. if (child.nodeType == 11) { child = child.host }
  97. if (child == parent) { return true }
  98. } while (child = child.parentNode)
  99. }
  100. function activeElt() {
  101. // IE and Edge may throw an "Unspecified Error" when accessing document.activeElement.
  102. // IE < 10 will throw when accessed while the page is loading or in an iframe.
  103. // IE > 9 and Edge will throw when accessed in an iframe if document.body is unavailable.
  104. var activeElement
  105. try {
  106. activeElement = document.activeElement
  107. } catch(e) {
  108. activeElement = document.body || null
  109. }
  110. while (activeElement && activeElement.shadowRoot && activeElement.shadowRoot.activeElement)
  111. { activeElement = activeElement.shadowRoot.activeElement }
  112. return activeElement
  113. }
  114. function addClass(node, cls) {
  115. var current = node.className
  116. if (!classTest(cls).test(current)) { node.className += (current ? " " : "") + cls }
  117. }
  118. function joinClasses(a, b) {
  119. var as = a.split(" ")
  120. for (var i = 0; i < as.length; i++)
  121. { if (as[i] && !classTest(as[i]).test(b)) { b += " " + as[i] } }
  122. return b
  123. }
  124. var selectInput = function(node) { node.select() }
  125. if (ios) // Mobile Safari apparently has a bug where select() is broken.
  126. { selectInput = function(node) { node.selectionStart = 0; node.selectionEnd = node.value.length } }
  127. else if (ie) // Suppress mysterious IE10 errors
  128. { selectInput = function(node) { try { node.select() } catch(_e) {} } }
  129. function bind(f) {
  130. var args = Array.prototype.slice.call(arguments, 1)
  131. return function(){return f.apply(null, args)}
  132. }
  133. function copyObj(obj, target, overwrite) {
  134. if (!target) { target = {} }
  135. for (var prop in obj)
  136. { if (obj.hasOwnProperty(prop) && (overwrite !== false || !target.hasOwnProperty(prop)))
  137. { target[prop] = obj[prop] } }
  138. return target
  139. }
  140. // Counts the column offset in a string, taking tabs into account.
  141. // Used mostly to find indentation.
  142. function countColumn(string, end, tabSize, startIndex, startValue) {
  143. if (end == null) {
  144. end = string.search(/[^\s\u00a0]/)
  145. if (end == -1) { end = string.length }
  146. }
  147. for (var i = startIndex || 0, n = startValue || 0;;) {
  148. var nextTab = string.indexOf("\t", i)
  149. if (nextTab < 0 || nextTab >= end)
  150. { return n + (end - i) }
  151. n += nextTab - i
  152. n += tabSize - (n % tabSize)
  153. i = nextTab + 1
  154. }
  155. }
  156. var Delayed = function() {this.id = null};
  157. Delayed.prototype.set = function (ms, f) {
  158. clearTimeout(this.id)
  159. this.id = setTimeout(f, ms)
  160. };
  161. function indexOf(array, elt) {
  162. for (var i = 0; i < array.length; ++i)
  163. { if (array[i] == elt) { return i } }
  164. return -1
  165. }
  166. // Number of pixels added to scroller and sizer to hide scrollbar
  167. var scrollerGap = 30
  168. // Returned or thrown by various protocols to signal 'I'm not
  169. // handling this'.
  170. var Pass = {toString: function(){return "CodeMirror.Pass"}}
  171. // Reused option objects for setSelection & friends
  172. var sel_dontScroll = {scroll: false};
  173. var sel_mouse = {origin: "*mouse"};
  174. var sel_move = {origin: "+move"};
  175. // The inverse of countColumn -- find the offset that corresponds to
  176. // a particular column.
  177. function findColumn(string, goal, tabSize) {
  178. for (var pos = 0, col = 0;;) {
  179. var nextTab = string.indexOf("\t", pos)
  180. if (nextTab == -1) { nextTab = string.length }
  181. var skipped = nextTab - pos
  182. if (nextTab == string.length || col + skipped >= goal)
  183. { return pos + Math.min(skipped, goal - col) }
  184. col += nextTab - pos
  185. col += tabSize - (col % tabSize)
  186. pos = nextTab + 1
  187. if (col >= goal) { return pos }
  188. }
  189. }
  190. var spaceStrs = [""]
  191. function spaceStr(n) {
  192. while (spaceStrs.length <= n)
  193. { spaceStrs.push(lst(spaceStrs) + " ") }
  194. return spaceStrs[n]
  195. }
  196. function lst(arr) { return arr[arr.length-1] }
  197. function map(array, f) {
  198. var out = []
  199. for (var i = 0; i < array.length; i++) { out[i] = f(array[i], i) }
  200. return out
  201. }
  202. function insertSorted(array, value, score) {
  203. var pos = 0, priority = score(value)
  204. while (pos < array.length && score(array[pos]) <= priority) { pos++ }
  205. array.splice(pos, 0, value)
  206. }
  207. function nothing() {}
  208. function createObj(base, props) {
  209. var inst
  210. if (Object.create) {
  211. inst = Object.create(base)
  212. } else {
  213. nothing.prototype = base
  214. inst = new nothing()
  215. }
  216. if (props) { copyObj(props, inst) }
  217. return inst
  218. }
  219. var nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/
  220. function isWordCharBasic(ch) {
  221. return /\w/.test(ch) || ch > "\x80" &&
  222. (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch))
  223. }
  224. function isWordChar(ch, helper) {
  225. if (!helper) { return isWordCharBasic(ch) }
  226. if (helper.source.indexOf("\\w") > -1 && isWordCharBasic(ch)) { return true }
  227. return helper.test(ch)
  228. }
  229. function isEmpty(obj) {
  230. for (var n in obj) { if (obj.hasOwnProperty(n) && obj[n]) { return false } }
  231. return true
  232. }
  233. // Extending unicode characters. A series of a non-extending char +
  234. // any number of extending chars is treated as a single unit as far
  235. // as editing and measuring is concerned. This is not fully correct,
  236. // since some scripts/fonts/browsers also treat other configurations
  237. // of code points as a group.
  238. var extendingChars = /[\u0300-\u036f\u0483-\u0489\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u065e\u0670\u06d6-\u06dc\u06de-\u06e4\u06e7\u06e8\u06ea-\u06ed\u0711\u0730-\u074a\u07a6-\u07b0\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0900-\u0902\u093c\u0941-\u0948\u094d\u0951-\u0955\u0962\u0963\u0981\u09bc\u09be\u09c1-\u09c4\u09cd\u09d7\u09e2\u09e3\u0a01\u0a02\u0a3c\u0a41\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a70\u0a71\u0a75\u0a81\u0a82\u0abc\u0ac1-\u0ac5\u0ac7\u0ac8\u0acd\u0ae2\u0ae3\u0b01\u0b3c\u0b3e\u0b3f\u0b41-\u0b44\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b82\u0bbe\u0bc0\u0bcd\u0bd7\u0c3e-\u0c40\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0cbc\u0cbf\u0cc2\u0cc6\u0ccc\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0d3e\u0d41-\u0d44\u0d4d\u0d57\u0d62\u0d63\u0dca\u0dcf\u0dd2-\u0dd4\u0dd6\u0ddf\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0f18\u0f19\u0f35\u0f37\u0f39\u0f71-\u0f7e\u0f80-\u0f84\u0f86\u0f87\u0f90-\u0f97\u0f99-\u0fbc\u0fc6\u102d-\u1030\u1032-\u1037\u1039\u103a\u103d\u103e\u1058\u1059\u105e-\u1060\u1071-\u1074\u1082\u1085\u1086\u108d\u109d\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b7-\u17bd\u17c6\u17c9-\u17d3\u17dd\u180b-\u180d\u18a9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193b\u1a17\u1a18\u1a56\u1a58-\u1a5e\u1a60\u1a62\u1a65-\u1a6c\u1a73-\u1a7c\u1a7f\u1b00-\u1b03\u1b34\u1b36-\u1b3a\u1b3c\u1b42\u1b6b-\u1b73\u1b80\u1b81\u1ba2-\u1ba5\u1ba8\u1ba9\u1c2c-\u1c33\u1c36\u1c37\u1cd0-\u1cd2\u1cd4-\u1ce0\u1ce2-\u1ce8\u1ced\u1dc0-\u1de6\u1dfd-\u1dff\u200c\u200d\u20d0-\u20f0\u2cef-\u2cf1\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua66f-\ua672\ua67c\ua67d\ua6f0\ua6f1\ua802\ua806\ua80b\ua825\ua826\ua8c4\ua8e0-\ua8f1\ua926-\ua92d\ua947-\ua951\ua980-\ua982\ua9b3\ua9b6-\ua9b9\ua9bc\uaa29-\uaa2e\uaa31\uaa32\uaa35\uaa36\uaa43\uaa4c\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uabe5\uabe8\uabed\udc00-\udfff\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\uff9e\uff9f]/
  239. function isExtendingChar(ch) { return ch.charCodeAt(0) >= 768 && extendingChars.test(ch) }
  240. // Returns a number from the range [`0`; `str.length`] unless `pos` is outside that range.
  241. function skipExtendingChars(str, pos, dir) {
  242. while ((dir < 0 ? pos > 0 : pos < str.length) && isExtendingChar(str.charAt(pos))) { pos += dir }
  243. return pos
  244. }
  245. // Returns the value from the range [`from`; `to`] that satisfies
  246. // `pred` and is closest to `from`. Assumes that at least `to`
  247. // satisfies `pred`. Supports `from` being greater than `to`.
  248. function findFirst(pred, from, to) {
  249. // At any point we are certain `to` satisfies `pred`, don't know
  250. // whether `from` does.
  251. var dir = from > to ? -1 : 1
  252. for (;;) {
  253. if (from == to) { return from }
  254. var midF = (from + to) / 2, mid = dir < 0 ? Math.ceil(midF) : Math.floor(midF)
  255. if (mid == from) { return pred(mid) ? from : to }
  256. if (pred(mid)) { to = mid }
  257. else { from = mid + dir }
  258. }
  259. }
  260. // The display handles the DOM integration, both for input reading
  261. // and content drawing. It holds references to DOM nodes and
  262. // display-related state.
  263. function Display(place, doc, input) {
  264. var d = this
  265. this.input = input
  266. // Covers bottom-right square when both scrollbars are present.
  267. d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler")
  268. d.scrollbarFiller.setAttribute("cm-not-content", "true")
  269. // Covers bottom of gutter when coverGutterNextToScrollbar is on
  270. // and h scrollbar is present.
  271. d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler")
  272. d.gutterFiller.setAttribute("cm-not-content", "true")
  273. // Will contain the actual code, positioned to cover the viewport.
  274. d.lineDiv = eltP("div", null, "CodeMirror-code")
  275. // Elements are added to these to represent selection and cursors.
  276. d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1")
  277. d.cursorDiv = elt("div", null, "CodeMirror-cursors")
  278. // A visibility: hidden element used to find the size of things.
  279. d.measure = elt("div", null, "CodeMirror-measure")
  280. // When lines outside of the viewport are measured, they are drawn in this.
  281. d.lineMeasure = elt("div", null, "CodeMirror-measure")
  282. // Wraps everything that needs to exist inside the vertically-padded coordinate system
  283. d.lineSpace = eltP("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv],
  284. null, "position: relative; outline: none")
  285. var lines = eltP("div", [d.lineSpace], "CodeMirror-lines")
  286. // Moved around its parent to cover visible view.
  287. d.mover = elt("div", [lines], null, "position: relative")
  288. // Set to the height of the document, allowing scrolling.
  289. d.sizer = elt("div", [d.mover], "CodeMirror-sizer")
  290. d.sizerWidth = null
  291. // Behavior of elts with overflow: auto and padding is
  292. // inconsistent across browsers. This is used to ensure the
  293. // scrollable area is big enough.
  294. d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerGap + "px; width: 1px;")
  295. // Will contain the gutters, if any.
  296. d.gutters = elt("div", null, "CodeMirror-gutters")
  297. d.lineGutter = null
  298. // Actual scrollable element.
  299. d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll")
  300. d.scroller.setAttribute("tabIndex", "-1")
  301. // The element in which the editor lives.
  302. d.wrapper = elt("div", [d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror")
  303. // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported)
  304. if (ie && ie_version < 8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0 }
  305. if (!webkit && !(gecko && mobile)) { d.scroller.draggable = true }
  306. if (place) {
  307. if (place.appendChild) { place.appendChild(d.wrapper) }
  308. else { place(d.wrapper) }
  309. }
  310. // Current rendered range (may be bigger than the view window).
  311. d.viewFrom = d.viewTo = doc.first
  312. d.reportedViewFrom = d.reportedViewTo = doc.first
  313. // Information about the rendered lines.
  314. d.view = []
  315. d.renderedView = null
  316. // Holds info about a single rendered line when it was rendered
  317. // for measurement, while not in view.
  318. d.externalMeasured = null
  319. // Empty space (in pixels) above the view
  320. d.viewOffset = 0
  321. d.lastWrapHeight = d.lastWrapWidth = 0
  322. d.updateLineNumbers = null
  323. d.nativeBarWidth = d.barHeight = d.barWidth = 0
  324. d.scrollbarsClipped = false
  325. // Used to only resize the line number gutter when necessary (when
  326. // the amount of lines crosses a boundary that makes its width change)
  327. d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null
  328. // Set to true when a non-horizontal-scrolling line widget is
  329. // added. As an optimization, line widget aligning is skipped when
  330. // this is false.
  331. d.alignWidgets = false
  332. d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null
  333. // Tracks the maximum line length so that the horizontal scrollbar
  334. // can be kept static when scrolling.
  335. d.maxLine = null
  336. d.maxLineLength = 0
  337. d.maxLineChanged = false
  338. // Used for measuring wheel scrolling granularity
  339. d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null
  340. // True when shift is held down.
  341. d.shift = false
  342. // Used to track whether anything happened since the context menu
  343. // was opened.
  344. d.selForContextMenu = null
  345. d.activeTouch = null
  346. input.init(d)
  347. }
  348. // Find the line object corresponding to the given line number.
  349. function getLine(doc, n) {
  350. n -= doc.first
  351. if (n < 0 || n >= doc.size) { throw new Error("There is no line " + (n + doc.first) + " in the document.") }
  352. var chunk = doc
  353. while (!chunk.lines) {
  354. for (var i = 0;; ++i) {
  355. var child = chunk.children[i], sz = child.chunkSize()
  356. if (n < sz) { chunk = child; break }
  357. n -= sz
  358. }
  359. }
  360. return chunk.lines[n]
  361. }
  362. // Get the part of a document between two positions, as an array of
  363. // strings.
  364. function getBetween(doc, start, end) {
  365. var out = [], n = start.line
  366. doc.iter(start.line, end.line + 1, function (line) {
  367. var text = line.text
  368. if (n == end.line) { text = text.slice(0, end.ch) }
  369. if (n == start.line) { text = text.slice(start.ch) }
  370. out.push(text)
  371. ++n
  372. })
  373. return out
  374. }
  375. // Get the lines between from and to, as array of strings.
  376. function getLines(doc, from, to) {
  377. var out = []
  378. doc.iter(from, to, function (line) { out.push(line.text) }) // iter aborts when callback returns truthy value
  379. return out
  380. }
  381. // Update the height of a line, propagating the height change
  382. // upwards to parent nodes.
  383. function updateLineHeight(line, height) {
  384. var diff = height - line.height
  385. if (diff) { for (var n = line; n; n = n.parent) { n.height += diff } }
  386. }
  387. // Given a line object, find its line number by walking up through
  388. // its parent links.
  389. function lineNo(line) {
  390. if (line.parent == null) { return null }
  391. var cur = line.parent, no = indexOf(cur.lines, line)
  392. for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) {
  393. for (var i = 0;; ++i) {
  394. if (chunk.children[i] == cur) { break }
  395. no += chunk.children[i].chunkSize()
  396. }
  397. }
  398. return no + cur.first
  399. }
  400. // Find the line at the given vertical position, using the height
  401. // information in the document tree.
  402. function lineAtHeight(chunk, h) {
  403. var n = chunk.first
  404. outer: do {
  405. for (var i$1 = 0; i$1 < chunk.children.length; ++i$1) {
  406. var child = chunk.children[i$1], ch = child.height
  407. if (h < ch) { chunk = child; continue outer }
  408. h -= ch
  409. n += child.chunkSize()
  410. }
  411. return n
  412. } while (!chunk.lines)
  413. var i = 0
  414. for (; i < chunk.lines.length; ++i) {
  415. var line = chunk.lines[i], lh = line.height
  416. if (h < lh) { break }
  417. h -= lh
  418. }
  419. return n + i
  420. }
  421. function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size}
  422. function lineNumberFor(options, i) {
  423. return String(options.lineNumberFormatter(i + options.firstLineNumber))
  424. }
  425. // A Pos instance represents a position within the text.
  426. function Pos(line, ch, sticky) {
  427. if ( sticky === void 0 ) sticky = null;
  428. if (!(this instanceof Pos)) { return new Pos(line, ch, sticky) }
  429. this.line = line
  430. this.ch = ch
  431. this.sticky = sticky
  432. }
  433. // Compare two positions, return 0 if they are the same, a negative
  434. // number when a is less, and a positive number otherwise.
  435. function cmp(a, b) { return a.line - b.line || a.ch - b.ch }
  436. function equalCursorPos(a, b) { return a.sticky == b.sticky && cmp(a, b) == 0 }
  437. function copyPos(x) {return Pos(x.line, x.ch)}
  438. function maxPos(a, b) { return cmp(a, b) < 0 ? b : a }
  439. function minPos(a, b) { return cmp(a, b) < 0 ? a : b }
  440. // Most of the external API clips given positions to make sure they
  441. // actually exist within the document.
  442. function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1))}
  443. function clipPos(doc, pos) {
  444. if (pos.line < doc.first) { return Pos(doc.first, 0) }
  445. var last = doc.first + doc.size - 1
  446. if (pos.line > last) { return Pos(last, getLine(doc, last).text.length) }
  447. return clipToLen(pos, getLine(doc, pos.line).text.length)
  448. }
  449. function clipToLen(pos, linelen) {
  450. var ch = pos.ch
  451. if (ch == null || ch > linelen) { return Pos(pos.line, linelen) }
  452. else if (ch < 0) { return Pos(pos.line, 0) }
  453. else { return pos }
  454. }
  455. function clipPosArray(doc, array) {
  456. var out = []
  457. for (var i = 0; i < array.length; i++) { out[i] = clipPos(doc, array[i]) }
  458. return out
  459. }
  460. // Optimize some code when these features are not used.
  461. var sawReadOnlySpans = false;
  462. var sawCollapsedSpans = false;
  463. function seeReadOnlySpans() {
  464. sawReadOnlySpans = true
  465. }
  466. function seeCollapsedSpans() {
  467. sawCollapsedSpans = true
  468. }
  469. // TEXTMARKER SPANS
  470. function MarkedSpan(marker, from, to) {
  471. this.marker = marker
  472. this.from = from; this.to = to
  473. }
  474. // Search an array of spans for a span matching the given marker.
  475. function getMarkedSpanFor(spans, marker) {
  476. if (spans) { for (var i = 0; i < spans.length; ++i) {
  477. var span = spans[i]
  478. if (span.marker == marker) { return span }
  479. } }
  480. }
  481. // Remove a span from an array, returning undefined if no spans are
  482. // left (we don't store arrays for lines without spans).
  483. function removeMarkedSpan(spans, span) {
  484. var r
  485. for (var i = 0; i < spans.length; ++i)
  486. { if (spans[i] != span) { (r || (r = [])).push(spans[i]) } }
  487. return r
  488. }
  489. // Add a span to a line.
  490. function addMarkedSpan(line, span) {
  491. line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span]
  492. span.marker.attachLine(line)
  493. }
  494. // Used for the algorithm that adjusts markers for a change in the
  495. // document. These functions cut an array of spans at a given
  496. // character position, returning an array of remaining chunks (or
  497. // undefined if nothing remains).
  498. function markedSpansBefore(old, startCh, isInsert) {
  499. var nw
  500. if (old) { for (var i = 0; i < old.length; ++i) {
  501. var span = old[i], marker = span.marker
  502. var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh)
  503. if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) {
  504. var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh)
  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. // Test whether there exists a collapsed span that partially
  670. // overlaps (covers the start or end, but not both) of a new span.
  671. // Such overlap is not allowed.
  672. function conflictingCollapsedRange(doc, lineNo, from, to, marker) {
  673. var line = getLine(doc, lineNo)
  674. var sps = sawCollapsedSpans && line.markedSpans
  675. if (sps) { for (var i = 0; i < sps.length; ++i) {
  676. var sp = sps[i]
  677. if (!sp.marker.collapsed) { continue }
  678. var found = sp.marker.find(0)
  679. var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker)
  680. var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker)
  681. if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) { continue }
  682. if (fromCmp <= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.to, from) >= 0 : cmp(found.to, from) > 0) ||
  683. fromCmp >= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.from, to) <= 0 : cmp(found.from, to) < 0))
  684. { return true }
  685. } }
  686. }
  687. // A visual line is a line as drawn on the screen. Folding, for
  688. // example, can cause multiple logical lines to appear on the same
  689. // visual line. This finds the start of the visual line that the
  690. // given line is part of (usually that is the line itself).
  691. function visualLine(line) {
  692. var merged
  693. while (merged = collapsedSpanAtStart(line))
  694. { line = merged.find(-1, true).line }
  695. return line
  696. }
  697. function visualLineEnd(line) {
  698. var merged
  699. while (merged = collapsedSpanAtEnd(line))
  700. { line = merged.find(1, true).line }
  701. return line
  702. }
  703. // Returns an array of logical lines that continue the visual line
  704. // started by the argument, or undefined if there are no such lines.
  705. function visualLineContinued(line) {
  706. var merged, lines
  707. while (merged = collapsedSpanAtEnd(line)) {
  708. line = merged.find(1, true).line
  709. ;(lines || (lines = [])).push(line)
  710. }
  711. return lines
  712. }
  713. // Get the line number of the start of the visual line that the
  714. // given line number is part of.
  715. function visualLineNo(doc, lineN) {
  716. var line = getLine(doc, lineN), vis = visualLine(line)
  717. if (line == vis) { return lineN }
  718. return lineNo(vis)
  719. }
  720. // Get the line number of the start of the next visual line after
  721. // the given line.
  722. function visualLineEndNo(doc, lineN) {
  723. if (lineN > doc.lastLine()) { return lineN }
  724. var line = getLine(doc, lineN), merged
  725. if (!lineIsHidden(doc, line)) { return lineN }
  726. while (merged = collapsedSpanAtEnd(line))
  727. { line = merged.find(1, true).line }
  728. return lineNo(line) + 1
  729. }
  730. // Compute whether a line is hidden. Lines count as hidden when they
  731. // are part of a visual line that starts with another line, or when
  732. // they are entirely covered by collapsed, non-widget span.
  733. function lineIsHidden(doc, line) {
  734. var sps = sawCollapsedSpans && line.markedSpans
  735. if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) {
  736. sp = sps[i]
  737. if (!sp.marker.collapsed) { continue }
  738. if (sp.from == null) { return true }
  739. if (sp.marker.widgetNode) { continue }
  740. if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp))
  741. { return true }
  742. } }
  743. }
  744. function lineIsHiddenInner(doc, line, span) {
  745. if (span.to == null) {
  746. var end = span.marker.find(1, true)
  747. return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker))
  748. }
  749. if (span.marker.inclusiveRight && span.to == line.text.length)
  750. { return true }
  751. for (var sp = (void 0), i = 0; i < line.markedSpans.length; ++i) {
  752. sp = line.markedSpans[i]
  753. if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to &&
  754. (sp.to == null || sp.to != span.from) &&
  755. (sp.marker.inclusiveLeft || span.marker.inclusiveRight) &&
  756. lineIsHiddenInner(doc, line, sp)) { return true }
  757. }
  758. }
  759. // Find the height above the given line.
  760. function heightAtLine(lineObj) {
  761. lineObj = visualLine(lineObj)
  762. var h = 0, chunk = lineObj.parent
  763. for (var i = 0; i < chunk.lines.length; ++i) {
  764. var line = chunk.lines[i]
  765. if (line == lineObj) { break }
  766. else { h += line.height }
  767. }
  768. for (var p = chunk.parent; p; chunk = p, p = chunk.parent) {
  769. for (var i$1 = 0; i$1 < p.children.length; ++i$1) {
  770. var cur = p.children[i$1]
  771. if (cur == chunk) { break }
  772. else { h += cur.height }
  773. }
  774. }
  775. return h
  776. }
  777. // Compute the character length of a line, taking into account
  778. // collapsed ranges (see markText) that might hide parts, and join
  779. // other lines onto it.
  780. function lineLength(line) {
  781. if (line.height == 0) { return 0 }
  782. var len = line.text.length, merged, cur = line
  783. while (merged = collapsedSpanAtStart(cur)) {
  784. var found = merged.find(0, true)
  785. cur = found.from.line
  786. len += found.from.ch - found.to.ch
  787. }
  788. cur = line
  789. while (merged = collapsedSpanAtEnd(cur)) {
  790. var found$1 = merged.find(0, true)
  791. len -= cur.text.length - found$1.from.ch
  792. cur = found$1.to.line
  793. len += cur.text.length - found$1.to.ch
  794. }
  795. return len
  796. }
  797. // Find the longest line in the document.
  798. function findMaxLine(cm) {
  799. var d = cm.display, doc = cm.doc
  800. d.maxLine = getLine(doc, doc.first)
  801. d.maxLineLength = lineLength(d.maxLine)
  802. d.maxLineChanged = true
  803. doc.iter(function (line) {
  804. var len = lineLength(line)
  805. if (len > d.maxLineLength) {
  806. d.maxLineLength = len
  807. d.maxLine = line
  808. }
  809. })
  810. }
  811. // BIDI HELPERS
  812. function iterateBidiSections(order, from, to, f) {
  813. if (!order) { return f(from, to, "ltr", 0) }
  814. var found = false
  815. for (var i = 0; i < order.length; ++i) {
  816. var part = order[i]
  817. if (part.from < to && part.to > from || from == to && part.to == from) {
  818. f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr", i)
  819. found = true
  820. }
  821. }
  822. if (!found) { f(from, to, "ltr") }
  823. }
  824. var bidiOther = null
  825. function getBidiPartAt(order, ch, sticky) {
  826. var found
  827. bidiOther = null
  828. for (var i = 0; i < order.length; ++i) {
  829. var cur = order[i]
  830. if (cur.from < ch && cur.to > ch) { return i }
  831. if (cur.to == ch) {
  832. if (cur.from != cur.to && sticky == "before") { found = i }
  833. else { bidiOther = i }
  834. }
  835. if (cur.from == ch) {
  836. if (cur.from != cur.to && sticky != "before") { found = i }
  837. else { bidiOther = i }
  838. }
  839. }
  840. return found != null ? found : bidiOther
  841. }
  842. // Bidirectional ordering algorithm
  843. // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm
  844. // that this (partially) implements.
  845. // One-char codes used for character types:
  846. // L (L): Left-to-Right
  847. // R (R): Right-to-Left
  848. // r (AL): Right-to-Left Arabic
  849. // 1 (EN): European Number
  850. // + (ES): European Number Separator
  851. // % (ET): European Number Terminator
  852. // n (AN): Arabic Number
  853. // , (CS): Common Number Separator
  854. // m (NSM): Non-Spacing Mark
  855. // b (BN): Boundary Neutral
  856. // s (B): Paragraph Separator
  857. // t (S): Segment Separator
  858. // w (WS): Whitespace
  859. // N (ON): Other Neutrals
  860. // Returns null if characters are ordered as they appear
  861. // (left-to-right), or an array of sections ({from, to, level}
  862. // objects) in the order in which they occur visually.
  863. var bidiOrdering = (function() {
  864. // Character types for codepoints 0 to 0xff
  865. var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN"
  866. // Character types for codepoints 0x600 to 0x6f9
  867. var arabicTypes = "nnnnnnNNr%%r,rNNmmmmmmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmmmnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmnNmmmmmmrrmmNmmmmrr1111111111"
  868. function charType(code) {
  869. if (code <= 0xf7) { return lowTypes.charAt(code) }
  870. else if (0x590 <= code && code <= 0x5f4) { return "R" }
  871. else if (0x600 <= code && code <= 0x6f9) { return arabicTypes.charAt(code - 0x600) }
  872. else if (0x6ee <= code && code <= 0x8ac) { return "r" }
  873. else if (0x2000 <= code && code <= 0x200b) { return "w" }
  874. else if (code == 0x200c) { return "b" }
  875. else { return "L" }
  876. }
  877. var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/
  878. var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/
  879. function BidiSpan(level, from, to) {
  880. this.level = level
  881. this.from = from; this.to = to
  882. }
  883. return function(str, direction) {
  884. var outerType = direction == "ltr" ? "L" : "R"
  885. if (str.length == 0 || direction == "ltr" && !bidiRE.test(str)) { return false }
  886. var len = str.length, types = []
  887. for (var i = 0; i < len; ++i)
  888. { types.push(charType(str.charCodeAt(i))) }
  889. // W1. Examine each non-spacing mark (NSM) in the level run, and
  890. // change the type of the NSM to the type of the previous
  891. // character. If the NSM is at the start of the level run, it will
  892. // get the type of sor.
  893. for (var i$1 = 0, prev = outerType; i$1 < len; ++i$1) {
  894. var type = types[i$1]
  895. if (type == "m") { types[i$1] = prev }
  896. else { prev = type }
  897. }
  898. // W2. Search backwards from each instance of a European number
  899. // until the first strong type (R, L, AL, or sor) is found. If an
  900. // AL is found, change the type of the European number to Arabic
  901. // number.
  902. // W3. Change all ALs to R.
  903. for (var i$2 = 0, cur = outerType; i$2 < len; ++i$2) {
  904. var type$1 = types[i$2]
  905. if (type$1 == "1" && cur == "r") { types[i$2] = "n" }
  906. else if (isStrong.test(type$1)) { cur = type$1; if (type$1 == "r") { types[i$2] = "R" } }
  907. }
  908. // W4. A single European separator between two European numbers
  909. // changes to a European number. A single common separator between
  910. // two numbers of the same type changes to that type.
  911. for (var i$3 = 1, prev$1 = types[0]; i$3 < len - 1; ++i$3) {
  912. var type$2 = types[i$3]
  913. if (type$2 == "+" && prev$1 == "1" && types[i$3+1] == "1") { types[i$3] = "1" }
  914. else if (type$2 == "," && prev$1 == types[i$3+1] &&
  915. (prev$1 == "1" || prev$1 == "n")) { types[i$3] = prev$1 }
  916. prev$1 = type$2
  917. }
  918. // W5. A sequence of European terminators adjacent to European
  919. // numbers changes to all European numbers.
  920. // W6. Otherwise, separators and terminators change to Other
  921. // Neutral.
  922. for (var i$4 = 0; i$4 < len; ++i$4) {
  923. var type$3 = types[i$4]
  924. if (type$3 == ",") { types[i$4] = "N" }
  925. else if (type$3 == "%") {
  926. var end = (void 0)
  927. for (end = i$4 + 1; end < len && types[end] == "%"; ++end) {}
  928. var replace = (i$4 && types[i$4-1] == "!") || (end < len && types[end] == "1") ? "1" : "N"
  929. for (var j = i$4; j < end; ++j) { types[j] = replace }
  930. i$4 = end - 1
  931. }
  932. }
  933. // W7. Search backwards from each instance of a European number
  934. // until the first strong type (R, L, or sor) is found. If an L is
  935. // found, then change the type of the European number to L.
  936. for (var i$5 = 0, cur$1 = outerType; i$5 < len; ++i$5) {
  937. var type$4 = types[i$5]
  938. if (cur$1 == "L" && type$4 == "1") { types[i$5] = "L" }
  939. else if (isStrong.test(type$4)) { cur$1 = type$4 }
  940. }
  941. // N1. A sequence of neutrals takes the direction of the
  942. // surrounding strong text if the text on both sides has the same
  943. // direction. European and Arabic numbers act as if they were R in
  944. // terms of their influence on neutrals. Start-of-level-run (sor)
  945. // and end-of-level-run (eor) are used at level run boundaries.
  946. // N2. Any remaining neutrals take the embedding direction.
  947. for (var i$6 = 0; i$6 < len; ++i$6) {
  948. if (isNeutral.test(types[i$6])) {
  949. var end$1 = (void 0)
  950. for (end$1 = i$6 + 1; end$1 < len && isNeutral.test(types[end$1]); ++end$1) {}
  951. var before = (i$6 ? types[i$6-1] : outerType) == "L"
  952. var after = (end$1 < len ? types[end$1] : outerType) == "L"
  953. var replace$1 = before == after ? (before ? "L" : "R") : outerType
  954. for (var j$1 = i$6; j$1 < end$1; ++j$1) { types[j$1] = replace$1 }
  955. i$6 = end$1 - 1
  956. }
  957. }
  958. // Here we depart from the documented algorithm, in order to avoid
  959. // building up an actual levels array. Since there are only three
  960. // levels (0, 1, 2) in an implementation that doesn't take
  961. // explicit embedding into account, we can build up the order on
  962. // the fly, without following the level-based algorithm.
  963. var order = [], m
  964. for (var i$7 = 0; i$7 < len;) {
  965. if (countsAsLeft.test(types[i$7])) {
  966. var start = i$7
  967. for (++i$7; i$7 < len && countsAsLeft.test(types[i$7]); ++i$7) {}
  968. order.push(new BidiSpan(0, start, i$7))
  969. } else {
  970. var pos = i$7, at = order.length
  971. for (++i$7; i$7 < len && types[i$7] != "L"; ++i$7) {}
  972. for (var j$2 = pos; j$2 < i$7;) {
  973. if (countsAsNum.test(types[j$2])) {
  974. if (pos < j$2) { order.splice(at, 0, new BidiSpan(1, pos, j$2)) }
  975. var nstart = j$2
  976. for (++j$2; j$2 < i$7 && countsAsNum.test(types[j$2]); ++j$2) {}
  977. order.splice(at, 0, new BidiSpan(2, nstart, j$2))
  978. pos = j$2
  979. } else { ++j$2 }
  980. }
  981. if (pos < i$7) { order.splice(at, 0, new BidiSpan(1, pos, i$7)) }
  982. }
  983. }
  984. if (direction == "ltr") {
  985. if (order[0].level == 1 && (m = str.match(/^\s+/))) {
  986. order[0].from = m[0].length
  987. order.unshift(new BidiSpan(0, 0, m[0].length))
  988. }
  989. if (lst(order).level == 1 && (m = str.match(/\s+$/))) {
  990. lst(order).to -= m[0].length
  991. order.push(new BidiSpan(0, len - m[0].length, len))
  992. }
  993. }
  994. return direction == "rtl" ? order.reverse() : order
  995. }
  996. })()
  997. // Get the bidi ordering for the given line (and cache it). Returns
  998. // false for lines that are fully left-to-right, and an array of
  999. // BidiSpan objects otherwise.
  1000. function getOrder(line, direction) {
  1001. var order = line.order
  1002. if (order == null) { order = line.order = bidiOrdering(line.text, direction) }
  1003. return order
  1004. }
  1005. // EVENT HANDLING
  1006. // Lightweight event framework. on/off also work on DOM nodes,
  1007. // registering native DOM handlers.
  1008. var noHandlers = []
  1009. var on = function(emitter, type, f) {
  1010. if (emitter.addEventListener) {
  1011. emitter.addEventListener(type, f, false)
  1012. } else if (emitter.attachEvent) {
  1013. emitter.attachEvent("on" + type, f)
  1014. } else {
  1015. var map = emitter._handlers || (emitter._handlers = {})
  1016. map[type] = (map[type] || noHandlers).concat(f)
  1017. }
  1018. }
  1019. function getHandlers(emitter, type) {
  1020. return emitter._handlers && emitter._handlers[type] || noHandlers
  1021. }
  1022. function off(emitter, type, f) {
  1023. if (emitter.removeEventListener) {
  1024. emitter.removeEventListener(type, f, false)
  1025. } else if (emitter.detachEvent) {
  1026. emitter.detachEvent("on" + type, f)
  1027. } else {
  1028. var map = emitter._handlers, arr = map && map[type]
  1029. if (arr) {
  1030. var index = indexOf(arr, f)
  1031. if (index > -1)
  1032. { map[type] = arr.slice(0, index).concat(arr.slice(index + 1)) }
  1033. }
  1034. }
  1035. }
  1036. function signal(emitter, type /*, values...*/) {
  1037. var handlers = getHandlers(emitter, type)
  1038. if (!handlers.length) { return }
  1039. var args = Array.prototype.slice.call(arguments, 2)
  1040. for (var i = 0; i < handlers.length; ++i) { handlers[i].apply(null, args) }
  1041. }
  1042. // The DOM events that CodeMirror handles can be overridden by
  1043. // registering a (non-DOM) handler on the editor for the event name,
  1044. // and preventDefault-ing the event in that handler.
  1045. function signalDOMEvent(cm, e, override) {
  1046. if (typeof e == "string")
  1047. { e = {type: e, preventDefault: function() { this.defaultPrevented = true }} }
  1048. signal(cm, override || e.type, cm, e)
  1049. return e_defaultPrevented(e) || e.codemirrorIgnore
  1050. }
  1051. function signalCursorActivity(cm) {
  1052. var arr = cm._handlers && cm._handlers.cursorActivity
  1053. if (!arr) { return }
  1054. var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = [])
  1055. for (var i = 0; i < arr.length; ++i) { if (indexOf(set, arr[i]) == -1)
  1056. { set.push(arr[i]) } }
  1057. }
  1058. function hasHandler(emitter, type) {
  1059. return getHandlers(emitter, type).length > 0
  1060. }
  1061. // Add on and off methods to a constructor's prototype, to make
  1062. // registering events on such objects more convenient.
  1063. function eventMixin(ctor) {
  1064. ctor.prototype.on = function(type, f) {on(this, type, f)}
  1065. ctor.prototype.off = function(type, f) {off(this, type, f)}
  1066. }
  1067. // Due to the fact that we still support jurassic IE versions, some
  1068. // compatibility wrappers are needed.
  1069. function e_preventDefault(e) {
  1070. if (e.preventDefault) { e.preventDefault() }
  1071. else { e.returnValue = false }
  1072. }
  1073. function e_stopPropagation(e) {
  1074. if (e.stopPropagation) { e.stopPropagation() }
  1075. else { e.cancelBubble = true }
  1076. }
  1077. function e_defaultPrevented(e) {
  1078. return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false
  1079. }
  1080. function e_stop(e) {e_preventDefault(e); e_stopPropagation(e)}
  1081. function e_target(e) {return e.target || e.srcElement}
  1082. function e_button(e) {
  1083. var b = e.which
  1084. if (b == null) {
  1085. if (e.button & 1) { b = 1 }
  1086. else if (e.button & 2) { b = 3 }
  1087. else if (e.button & 4) { b = 2 }
  1088. }
  1089. if (mac && e.ctrlKey && b == 1) { b = 3 }
  1090. return b
  1091. }
  1092. // Detect drag-and-drop
  1093. var dragAndDrop = function() {
  1094. // There is *some* kind of drag-and-drop support in IE6-8, but I
  1095. // couldn't get it to work yet.
  1096. if (ie && ie_version < 9) { return false }
  1097. var div = elt('div')
  1098. return "draggable" in div || "dragDrop" in div
  1099. }()
  1100. var zwspSupported
  1101. function zeroWidthElement(measure) {
  1102. if (zwspSupported == null) {
  1103. var test = elt("span", "\u200b")
  1104. removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")]))
  1105. if (measure.firstChild.offsetHeight != 0)
  1106. { zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8) }
  1107. }
  1108. var node = zwspSupported ? elt("span", "\u200b") :
  1109. elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px")
  1110. node.setAttribute("cm-text", "")
  1111. return node
  1112. }
  1113. // Feature-detect IE's crummy client rect reporting for bidi text
  1114. var badBidiRects
  1115. function hasBadBidiRects(measure) {
  1116. if (badBidiRects != null) { return badBidiRects }
  1117. var txt = removeChildrenAndAdd(measure, document.createTextNode("A\u062eA"))
  1118. var r0 = range(txt, 0, 1).getBoundingClientRect()
  1119. var r1 = range(txt, 1, 2).getBoundingClientRect()
  1120. removeChildren(measure)
  1121. if (!r0 || r0.left == r0.right) { return false } // Safari returns null in some cases (#2780)
  1122. return badBidiRects = (r1.right - r0.right < 3)
  1123. }
  1124. // See if "".split is the broken IE version, if so, provide an
  1125. // alternative way to split lines.
  1126. var splitLinesAuto = "\n\nb".split(/\n/).length != 3 ? function (string) {
  1127. var pos = 0, result = [], l = string.length
  1128. while (pos <= l) {
  1129. var nl = string.indexOf("\n", pos)
  1130. if (nl == -1) { nl = string.length }
  1131. var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl)
  1132. var rt = line.indexOf("\r")
  1133. if (rt != -1) {
  1134. result.push(line.slice(0, rt))
  1135. pos += rt + 1
  1136. } else {
  1137. result.push(line)
  1138. pos = nl + 1
  1139. }
  1140. }
  1141. return result
  1142. } : function (string) { return string.split(/\r\n?|\n/); }
  1143. var hasSelection = window.getSelection ? function (te) {
  1144. try { return te.selectionStart != te.selectionEnd }
  1145. catch(e) { return false }
  1146. } : function (te) {
  1147. var range
  1148. try {range = te.ownerDocument.selection.createRange()}
  1149. catch(e) {}
  1150. if (!range || range.parentElement() != te) { return false }
  1151. return range.compareEndPoints("StartToEnd", range) != 0
  1152. }
  1153. var hasCopyEvent = (function () {
  1154. var e = elt("div")
  1155. if ("oncopy" in e) { return true }
  1156. e.setAttribute("oncopy", "return;")
  1157. return typeof e.oncopy == "function"
  1158. })()
  1159. var badZoomedRects = null
  1160. function hasBadZoomedRects(measure) {
  1161. if (badZoomedRects != null) { return badZoomedRects }
  1162. var node = removeChildrenAndAdd(measure, elt("span", "x"))
  1163. var normal = node.getBoundingClientRect()
  1164. var fromRange = range(node, 0, 1).getBoundingClientRect()
  1165. return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1
  1166. }
  1167. var modes = {};
  1168. var mimeModes = {};
  1169. // Extra arguments are stored as the mode's dependencies, which is
  1170. // used by (legacy) mechanisms like loadmode.js to automatically
  1171. // load a mode. (Preferred mechanism is the require/define calls.)
  1172. function defineMode(name, mode) {
  1173. if (arguments.length > 2)
  1174. { mode.dependencies = Array.prototype.slice.call(arguments, 2) }
  1175. modes[name] = mode
  1176. }
  1177. function defineMIME(mime, spec) {
  1178. mimeModes[mime] = spec
  1179. }
  1180. // Given a MIME type, a {name, ...options} config object, or a name
  1181. // string, return a mode config object.
  1182. function resolveMode(spec) {
  1183. if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) {
  1184. spec = mimeModes[spec]
  1185. } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) {
  1186. var found = mimeModes[spec.name]
  1187. if (typeof found == "string") { found = {name: found} }
  1188. spec = createObj(found, spec)
  1189. spec.name = found.name
  1190. } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) {
  1191. return resolveMode("application/xml")
  1192. } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+json$/.test(spec)) {
  1193. return resolveMode("application/json")
  1194. }
  1195. if (typeof spec == "string") { return {name: spec} }
  1196. else { return spec || {name: "null"} }
  1197. }
  1198. // Given a mode spec (anything that resolveMode accepts), find and
  1199. // initialize an actual mode object.
  1200. function getMode(options, spec) {
  1201. spec = resolveMode(spec)
  1202. var mfactory = modes[spec.name]
  1203. if (!mfactory) { return getMode(options, "text/plain") }
  1204. var modeObj = mfactory(options, spec)
  1205. if (modeExtensions.hasOwnProperty(spec.name)) {
  1206. var exts = modeExtensions[spec.name]
  1207. for (var prop in exts) {
  1208. if (!exts.hasOwnProperty(prop)) { continue }
  1209. if (modeObj.hasOwnProperty(prop)) { modeObj["_" + prop] = modeObj[prop] }
  1210. modeObj[prop] = exts[prop]
  1211. }
  1212. }
  1213. modeObj.name = spec.name
  1214. if (spec.helperType) { modeObj.helperType = spec.helperType }
  1215. if (spec.modeProps) { for (var prop$1 in spec.modeProps)
  1216. { modeObj[prop$1] = spec.modeProps[prop$1] } }
  1217. return modeObj
  1218. }
  1219. // This can be used to attach properties to mode objects from
  1220. // outside the actual mode definition.
  1221. var modeExtensions = {}
  1222. function extendMode(mode, properties) {
  1223. var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {})
  1224. copyObj(properties, exts)
  1225. }
  1226. function copyState(mode, state) {
  1227. if (state === true) { return state }
  1228. if (mode.copyState) { return mode.copyState(state) }
  1229. var nstate = {}
  1230. for (var n in state) {
  1231. var val = state[n]
  1232. if (val instanceof Array) { val = val.concat([]) }
  1233. nstate[n] = val
  1234. }
  1235. return nstate
  1236. }
  1237. // Given a mode and a state (for that mode), find the inner mode and
  1238. // state at the position that the state refers to.
  1239. function innerMode(mode, state) {
  1240. var info
  1241. while (mode.innerMode) {
  1242. info = mode.innerMode(state)
  1243. if (!info || info.mode == mode) { break }
  1244. state = info.state
  1245. mode = info.mode
  1246. }
  1247. return info || {mode: mode, state: state}
  1248. }
  1249. function startState(mode, a1, a2) {
  1250. return mode.startState ? mode.startState(a1, a2) : true
  1251. }
  1252. // STRING STREAM
  1253. // Fed to the mode parsers, provides helper functions to make
  1254. // parsers more succinct.
  1255. var StringStream = function(string, tabSize, lineOracle) {
  1256. this.pos = this.start = 0
  1257. this.string = string
  1258. this.tabSize = tabSize || 8
  1259. this.lastColumnPos = this.lastColumnValue = 0
  1260. this.lineStart = 0
  1261. this.lineOracle = lineOracle
  1262. };
  1263. StringStream.prototype.eol = function () {return this.pos >= this.string.length};
  1264. StringStream.prototype.sol = function () {return this.pos == this.lineStart};
  1265. StringStream.prototype.peek = function () {return this.string.charAt(this.pos) || undefined};
  1266. StringStream.prototype.next = function () {
  1267. if (this.pos < this.string.length)
  1268. { return this.string.charAt(this.pos++) }
  1269. };
  1270. StringStream.prototype.eat = function (match) {
  1271. var ch = this.string.charAt(this.pos)
  1272. var ok
  1273. if (typeof match == "string") { ok = ch == match }
  1274. else { ok = ch && (match.test ? match.test(ch) : match(ch)) }
  1275. if (ok) {++this.pos; return ch}
  1276. };
  1277. StringStream.prototype.eatWhile = function (match) {
  1278. var start = this.pos
  1279. while (this.eat(match)){}
  1280. return this.pos > start
  1281. };
  1282. StringStream.prototype.eatSpace = function () {
  1283. var this$1 = this;
  1284. var start = this.pos
  1285. while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) { ++this$1.pos }
  1286. return this.pos > start
  1287. };
  1288. StringStream.prototype.skipToEnd = function () {this.pos = this.string.length};
  1289. StringStream.prototype.skipTo = function (ch) {
  1290. var found = this.string.indexOf(ch, this.pos)
  1291. if (found > -1) {this.pos = found; return true}
  1292. };
  1293. StringStream.prototype.backUp = function (n) {this.pos -= n};
  1294. StringStream.prototype.column = function () {
  1295. if (this.lastColumnPos < this.start) {
  1296. this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue)
  1297. this.lastColumnPos = this.start
  1298. }
  1299. return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0)
  1300. };
  1301. StringStream.prototype.indentation = function () {
  1302. return countColumn(this.string, null, this.tabSize) -
  1303. (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0)
  1304. };
  1305. StringStream.prototype.match = function (pattern, consume, caseInsensitive) {
  1306. if (typeof pattern == "string") {
  1307. var cased = function (str) { return caseInsensitive ? str.toLowerCase() : str; }
  1308. var substr = this.string.substr(this.pos, pattern.length)
  1309. if (cased(substr) == cased(pattern)) {
  1310. if (consume !== false) { this.pos += pattern.length }
  1311. return true
  1312. }
  1313. } else {
  1314. var match = this.string.slice(this.pos).match(pattern)
  1315. if (match && match.index > 0) { return null }
  1316. if (match && consume !== false) { this.pos += match[0].length }
  1317. return match
  1318. }
  1319. };
  1320. StringStream.prototype.current = function (){return this.string.slice(this.start, this.pos)};
  1321. StringStream.prototype.hideFirstChars = function (n, inner) {
  1322. this.lineStart += n
  1323. try { return inner() }
  1324. finally { this.lineStart -= n }
  1325. };
  1326. StringStream.prototype.lookAhead = function (n) {
  1327. var oracle = this.lineOracle
  1328. return oracle && oracle.lookAhead(n)
  1329. };
  1330. StringStream.prototype.baseToken = function () {
  1331. var oracle = this.lineOracle
  1332. return oracle && oracle.baseToken(this.pos)
  1333. };
  1334. var SavedContext = function(state, lookAhead) {
  1335. this.state = state
  1336. this.lookAhead = lookAhead
  1337. };
  1338. var Context = function(doc, state, line, lookAhead) {
  1339. this.state = state
  1340. this.doc = doc
  1341. this.line = line
  1342. this.maxLookAhead = lookAhead || 0
  1343. this.baseTokens = null
  1344. this.baseTokenPos = 1
  1345. };
  1346. Context.prototype.lookAhead = function (n) {
  1347. var line = this.doc.getLine(this.line + n)
  1348. if (line != null && n > this.maxLookAhead) { this.maxLookAhead = n }
  1349. return line
  1350. };
  1351. Context.prototype.baseToken = function (n) {
  1352. var this$1 = this;
  1353. if (!this.baseTokens) { return null }
  1354. while (this.baseTokens[this.baseTokenPos] <= n)
  1355. { this$1.baseTokenPos += 2 }
  1356. var type = this.baseTokens[this.baseTokenPos + 1]
  1357. return {type: type && type.replace(/( |^)overlay .*/, ""),
  1358. size: this.baseTokens[this.baseTokenPos] - n}
  1359. };
  1360. Context.prototype.nextLine = function () {
  1361. this.line++
  1362. if (this.maxLookAhead > 0) { this.maxLookAhead-- }
  1363. };
  1364. Context.fromSaved = function (doc, saved, line) {
  1365. if (saved instanceof SavedContext)
  1366. { return new Context(doc, copyState(doc.mode, saved.state), line, saved.lookAhead) }
  1367. else
  1368. { return new Context(doc, copyState(doc.mode, saved), line) }
  1369. };
  1370. Context.prototype.save = function (copy) {
  1371. var state = copy !== false ? copyState(this.doc.mode, this.state) : this.state
  1372. return this.maxLookAhead > 0 ? new SavedContext(state, this.maxLookAhead) : state
  1373. };
  1374. // Compute a style array (an array starting with a mode generation
  1375. // -- for invalidation -- followed by pairs of end positions and
  1376. // style strings), which is used to highlight the tokens on the
  1377. // line.
  1378. function highlightLine(cm, line, context, forceToEnd) {
  1379. // A styles array always starts with a number identifying the
  1380. // mode/overlays that it is based on (for easy invalidation).
  1381. var st = [cm.state.modeGen], lineClasses = {}
  1382. // Compute the base array of styles
  1383. runMode(cm, line.text, cm.doc.mode, context, function (end, style) { return st.push(end, style); },
  1384. lineClasses, forceToEnd)
  1385. var state = context.state
  1386. // Run overlays, adjust style array.
  1387. var loop = function ( o ) {
  1388. context.baseTokens = st
  1389. var overlay = cm.state.overlays[o], i = 1, at = 0
  1390. context.state = true
  1391. runMode(cm, line.text, overlay.mode, context, function (end, style) {
  1392. var start = i
  1393. // Ensure there's a token end at the current position, and that i points at it
  1394. while (at < end) {
  1395. var i_end = st[i]
  1396. if (i_end > end)
  1397. { st.splice(i, 1, end, st[i+1], i_end) }
  1398. i += 2
  1399. at = Math.min(end, i_end)
  1400. }
  1401. if (!style) { return }
  1402. if (overlay.opaque) {
  1403. st.splice(start, i - start, end, "overlay " + style)
  1404. i = start + 2
  1405. } else {
  1406. for (; start < i; start += 2) {
  1407. var cur = st[start+1]
  1408. st[start+1] = (cur ? cur + " " : "") + "overlay " + style
  1409. }
  1410. }
  1411. }, lineClasses)
  1412. context.state = state
  1413. context.baseTokens = null
  1414. context.baseTokenPos = 1
  1415. };
  1416. for (var o = 0; o < cm.state.overlays.length; ++o) loop( o );
  1417. return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null}
  1418. }
  1419. function getLineStyles(cm, line, updateFrontier) {
  1420. if (!line.styles || line.styles[0] != cm.state.modeGen) {
  1421. var context = getContextBefore(cm, lineNo(line))
  1422. var resetState = line.text.length > cm.options.maxHighlightLength && copyState(cm.doc.mode, context.state)
  1423. var result = highlightLine(cm, line, context)
  1424. if (resetState) { context.state = resetState }
  1425. line.stateAfter = context.save(!resetState)
  1426. line.styles = result.styles
  1427. if (result.classes) { line.styleClasses = result.classes }
  1428. else if (line.styleClasses) { line.styleClasses = null }
  1429. if (updateFrontier === cm.doc.highlightFrontier)
  1430. { cm.doc.modeFrontier = Math.max(cm.doc.modeFrontier, ++cm.doc.highlightFrontier) }
  1431. }
  1432. return line.styles
  1433. }
  1434. function getContextBefore(cm, n, precise) {
  1435. var doc = cm.doc, display = cm.display
  1436. if (!doc.mode.startState) { return new Context(doc, true, n) }
  1437. var start = findStartLine(cm, n, precise)
  1438. var saved = start > doc.first && getLine(doc, start - 1).stateAfter
  1439. var context = saved ? Context.fromSaved(doc, saved, start) : new Context(doc, startState(doc.mode), start)
  1440. doc.iter(start, n, function (line) {
  1441. processLine(cm, line.text, context)
  1442. var pos = context.line
  1443. line.stateAfter = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo ? context.save() : null
  1444. context.nextLine()
  1445. })
  1446. if (precise) { doc.modeFrontier = context.line }
  1447. return context
  1448. }
  1449. // Lightweight form of highlight -- proceed over this line and
  1450. // update state, but don't save a style array. Used for lines that
  1451. // aren't currently visible.
  1452. function processLine(cm, text, context, startAt) {
  1453. var mode = cm.doc.mode
  1454. var stream = new StringStream(text, cm.options.tabSize, context)
  1455. stream.start = stream.pos = startAt || 0
  1456. if (text == "") { callBlankLine(mode, context.state) }
  1457. while (!stream.eol()) {
  1458. readToken(mode, stream, context.state)
  1459. stream.start = stream.pos
  1460. }
  1461. }
  1462. function callBlankLine(mode, state) {
  1463. if (mode.blankLine) { return mode.blankLine(state) }
  1464. if (!mode.innerMode) { return }
  1465. var inner = innerMode(mode, state)
  1466. if (inner.mode.blankLine) { return inner.mode.blankLine(inner.state) }
  1467. }
  1468. function readToken(mode, stream, state, inner) {
  1469. for (var i = 0; i < 10; i++) {
  1470. if (inner) { inner[0] = innerMode(mode, state).mode }
  1471. var style = mode.token(stream, state)
  1472. if (stream.pos > stream.start) { return style }
  1473. }
  1474. throw new Error("Mode " + mode.name + " failed to advance stream.")
  1475. }
  1476. var Token = function(stream, type, state) {
  1477. this.start = stream.start; this.end = stream.pos
  1478. this.string = stream.current()
  1479. this.type = type || null
  1480. this.state = state
  1481. };
  1482. // Utility for getTokenAt and getLineTokens
  1483. function takeToken(cm, pos, precise, asArray) {
  1484. var doc = cm.doc, mode = doc.mode, style
  1485. pos = clipPos(doc, pos)
  1486. var line = getLine(doc, pos.line), context = getContextBefore(cm, pos.line, precise)
  1487. var stream = new StringStream(line.text, cm.options.tabSize, context), tokens
  1488. if (asArray) { tokens = [] }
  1489. while ((asArray || stream.pos < pos.ch) && !stream.eol()) {
  1490. stream.start = stream.pos
  1491. style = readToken(mode, stream, context.state)
  1492. if (asArray) { tokens.push(new Token(stream, style, copyState(doc.mode, context.state))) }
  1493. }
  1494. return asArray ? tokens : new Token(stream, style, context.state)
  1495. }
  1496. function extractLineClasses(type, output) {
  1497. if (type) { for (;;) {
  1498. var lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/)
  1499. if (!lineClass) { break }
  1500. type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length)
  1501. var prop = lineClass[1] ? "bgClass" : "textClass"
  1502. if (output[prop] == null)
  1503. { output[prop] = lineClass[2] }
  1504. else if (!(new RegExp("(?:^|\s)" + lineClass[2] + "(?:$|\s)")).test(output[prop]))
  1505. { output[prop] += " " + lineClass[2] }
  1506. } }
  1507. return type
  1508. }
  1509. // Run the given mode's parser over a line, calling f for each token.
  1510. function runMode(cm, text, mode, context, f, lineClasses, forceToEnd) {
  1511. var flattenSpans = mode.flattenSpans
  1512. if (flattenSpans == null) { flattenSpans = cm.options.flattenSpans }
  1513. var curStart = 0, curStyle = null
  1514. var stream = new StringStream(text, cm.options.tabSize, context), style
  1515. var inner = cm.options.addModeClass && [null]
  1516. if (text == "") { extractLineClasses(callBlankLine(mode, context.state), lineClasses) }
  1517. while (!stream.eol()) {
  1518. if (stream.pos > cm.options.maxHighlightLength) {
  1519. flattenSpans = false
  1520. if (forceToEnd) { processLine(cm, text, context, stream.pos) }
  1521. stream.pos = text.length
  1522. style = null
  1523. } else {
  1524. style = extractLineClasses(readToken(mode, stream, context.state, inner), lineClasses)
  1525. }
  1526. if (inner) {
  1527. var mName = inner[0].name
  1528. if (mName) { style = "m-" + (style ? mName + " " + style : mName) }
  1529. }
  1530. if (!flattenSpans || curStyle != style) {
  1531. while (curStart < stream.start) {
  1532. curStart = Math.min(stream.start, curStart + 5000)
  1533. f(curStart, curStyle)
  1534. }
  1535. curStyle = style
  1536. }
  1537. stream.start = stream.pos
  1538. }
  1539. while (curStart < stream.pos) {
  1540. // Webkit seems to refuse to render text nodes longer than 57444
  1541. // characters, and returns inaccurate measurements in nodes
  1542. // starting around 5000 chars.
  1543. var pos = Math.min(stream.pos, curStart + 5000)
  1544. f(pos, curStyle)
  1545. curStart = pos
  1546. }
  1547. }
  1548. // Finds the line to start with when starting a parse. Tries to
  1549. // find a line with a stateAfter, so that it can start with a
  1550. // valid state. If that fails, it returns the line with the
  1551. // smallest indentation, which tends to need the least context to
  1552. // parse correctly.
  1553. function findStartLine(cm, n, precise) {
  1554. var minindent, minline, doc = cm.doc
  1555. var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100)
  1556. for (var search = n; search > lim; --search) {
  1557. if (search <= doc.first) { return doc.first }
  1558. var line = getLine(doc, search - 1), after = line.stateAfter
  1559. if (after && (!precise || search + (after instanceof SavedContext ? after.lookAhead : 0) <= doc.modeFrontier))
  1560. { return search }
  1561. var indented = countColumn(line.text, null, cm.options.tabSize)
  1562. if (minline == null || minindent > indented) {
  1563. minline = search - 1
  1564. minindent = indented
  1565. }
  1566. }
  1567. return minline
  1568. }
  1569. function retreatFrontier(doc, n) {
  1570. doc.modeFrontier = Math.min(doc.modeFrontier, n)
  1571. if (doc.highlightFrontier < n - 10) { return }
  1572. var start = doc.first
  1573. for (var line = n - 1; line > start; line--) {
  1574. var saved = getLine(doc, line).stateAfter
  1575. // change is on 3
  1576. // state on line 1 looked ahead 2 -- so saw 3
  1577. // test 1 + 2 < 3 should cover this
  1578. if (saved && (!(saved instanceof SavedContext) || line + saved.lookAhead < n)) {
  1579. start = line + 1
  1580. break
  1581. }
  1582. }
  1583. doc.highlightFrontier = Math.min(doc.highlightFrontier, start)
  1584. }
  1585. // LINE DATA STRUCTURE
  1586. // Line objects. These hold state related to a line, including
  1587. // highlighting info (the styles array).
  1588. var Line = function(text, markedSpans, estimateHeight) {
  1589. this.text = text
  1590. attachMarkedSpans(this, markedSpans)
  1591. this.height = estimateHeight ? estimateHeight(this) : 1
  1592. };
  1593. Line.prototype.lineNo = function () { return lineNo(this) };
  1594. eventMixin(Line)
  1595. // Change the content (text, markers) of a line. Automatically
  1596. // invalidates cached information and tries to re-estimate the
  1597. // line's height.
  1598. function updateLine(line, text, markedSpans, estimateHeight) {
  1599. line.text = text
  1600. if (line.stateAfter) { line.stateAfter = null }
  1601. if (line.styles) { line.styles = null }
  1602. if (line.order != null) { line.order = null }
  1603. detachMarkedSpans(line)
  1604. attachMarkedSpans(line, markedSpans)
  1605. var estHeight = estimateHeight ? estimateHeight(line) : 1
  1606. if (estHeight != line.height) { updateLineHeight(line, estHeight) }
  1607. }
  1608. // Detach a line from the document tree and its markers.
  1609. function cleanUpLine(line) {
  1610. line.parent = null
  1611. detachMarkedSpans(line)
  1612. }
  1613. // Convert a style as returned by a mode (either null, or a string
  1614. // containing one or more styles) to a CSS style. This is cached,
  1615. // and also looks for line-wide styles.
  1616. var styleToClassCache = {};
  1617. var styleToClassCacheWithMode = {};
  1618. function interpretTokenStyle(style, options) {
  1619. if (!style || /^\s*$/.test(style)) { return null }
  1620. var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache
  1621. return cache[style] ||
  1622. (cache[style] = style.replace(/\S+/g, "cm-$&"))
  1623. }
  1624. // Render the DOM representation of the text of a line. Also builds
  1625. // up a 'line map', which points at the DOM nodes that represent
  1626. // specific stretches of text, and is used by the measuring code.
  1627. // The returned object contains the DOM node, this map, and
  1628. // information about line-wide styles that were set by the mode.
  1629. function buildLineContent(cm, lineView) {
  1630. // The padding-right forces the element to have a 'border', which
  1631. // is needed on Webkit to be able to get line-level bounding
  1632. // rectangles for it (in measureChar).
  1633. var content = eltP("span", null, null, webkit ? "padding-right: .1px" : null)
  1634. var builder = {pre: eltP("pre", [content], "CodeMirror-line"), content: content,
  1635. col: 0, pos: 0, cm: cm,
  1636. trailingSpace: false,
  1637. splitSpaces: (ie || webkit) && cm.getOption("lineWrapping")}
  1638. lineView.measure = {}
  1639. // Iterate over the logical lines that make up this visual line.
  1640. for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) {
  1641. var line = i ? lineView.rest[i - 1] : lineView.line, order = (void 0)
  1642. builder.pos = 0
  1643. builder.addToken = buildToken
  1644. // Optionally wire in some hacks into the token-rendering
  1645. // algorithm, to deal with browser quirks.
  1646. if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line, cm.doc.direction)))
  1647. { builder.addToken = buildTokenBadBidi(builder.addToken, order) }
  1648. builder.map = []
  1649. var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line)
  1650. insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate))
  1651. if (line.styleClasses) {
  1652. if (line.styleClasses.bgClass)
  1653. { builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || "") }
  1654. if (line.styleClasses.textClass)
  1655. { builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || "") }
  1656. }
  1657. // Ensure at least a single node is present, for measuring.
  1658. if (builder.map.length == 0)
  1659. { builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure))) }
  1660. // Store the map and a cache object for the current logical line
  1661. if (i == 0) {
  1662. lineView.measure.map = builder.map
  1663. lineView.measure.cache = {}
  1664. } else {
  1665. ;(lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map)
  1666. ;(lineView.measure.caches || (lineView.measure.caches = [])).push({})
  1667. }
  1668. }
  1669. // See issue #2901
  1670. if (webkit) {
  1671. var last = builder.content.lastChild
  1672. if (/\bcm-tab\b/.test(last.className) || (last.querySelector && last.querySelector(".cm-tab")))
  1673. { builder.content.className = "cm-tab-wrap-hack" }
  1674. }
  1675. signal(cm, "renderLine", cm, lineView.line, builder.pre)
  1676. if (builder.pre.className)
  1677. { builder.textClass = joinClasses(builder.pre.className, builder.textClass || "") }
  1678. return builder
  1679. }
  1680. function defaultSpecialCharPlaceholder(ch) {
  1681. var token = elt("span", "\u2022", "cm-invalidchar")
  1682. token.title = "\\u" + ch.charCodeAt(0).toString(16)
  1683. token.setAttribute("aria-label", token.title)
  1684. return token
  1685. }
  1686. // Build up the DOM representation for a single token, and add it to
  1687. // the line map. Takes care to render special characters separately.
  1688. function buildToken(builder, text, style, startStyle, endStyle, title, css) {
  1689. if (!text) { return }
  1690. var displayText = builder.splitSpaces ? splitSpaces(text, builder.trailingSpace) : text
  1691. var special = builder.cm.state.specialChars, mustWrap = false
  1692. var content
  1693. if (!special.test(text)) {
  1694. builder.col += text.length
  1695. content = document.createTextNode(displayText)
  1696. builder.map.push(builder.pos, builder.pos + text.length, content)
  1697. if (ie && ie_version < 9) { mustWrap = true }
  1698. builder.pos += text.length
  1699. } else {
  1700. content = document.createDocumentFragment()
  1701. var pos = 0
  1702. while (true) {
  1703. special.lastIndex = pos
  1704. var m = special.exec(text)
  1705. var skipped = m ? m.index - pos : text.length - pos
  1706. if (skipped) {
  1707. var txt = document.createTextNode(displayText.slice(pos, pos + skipped))
  1708. if (ie && ie_version < 9) { content.appendChild(elt("span", [txt])) }
  1709. else { content.appendChild(txt) }
  1710. builder.map.push(builder.pos, builder.pos + skipped, txt)
  1711. builder.col += skipped
  1712. builder.pos += skipped
  1713. }
  1714. if (!m) { break }
  1715. pos += skipped + 1
  1716. var txt$1 = (void 0)
  1717. if (m[0] == "\t") {
  1718. var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize
  1719. txt$1 = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab"))
  1720. txt$1.setAttribute("role", "presentation")
  1721. txt$1.setAttribute("cm-text", "\t")
  1722. builder.col += tabWidth
  1723. } else if (m[0] == "\r" || m[0] == "\n") {
  1724. txt$1 = content.appendChild(elt("span", m[0] == "\r" ? "\u240d" : "\u2424", "cm-invalidchar"))
  1725. txt$1.setAttribute("cm-text", m[0])
  1726. builder.col += 1
  1727. } else {
  1728. txt$1 = builder.cm.options.specialCharPlaceholder(m[0])
  1729. txt$1.setAttribute("cm-text", m[0])
  1730. if (ie && ie_version < 9) { content.appendChild(elt("span", [txt$1])) }
  1731. else { content.appendChild(txt$1) }
  1732. builder.col += 1
  1733. }
  1734. builder.map.push(builder.pos, builder.pos + 1, txt$1)
  1735. builder.pos++
  1736. }
  1737. }
  1738. builder.trailingSpace = displayText.charCodeAt(text.length - 1) == 32
  1739. if (style || startStyle || endStyle || mustWrap || css) {
  1740. var fullStyle = style || ""
  1741. if (startStyle) { fullStyle += startStyle }
  1742. if (endStyle) { fullStyle += endStyle }
  1743. var token = elt("span", [content], fullStyle, css)
  1744. if (title) { token.title = title }
  1745. return builder.content.appendChild(token)
  1746. }
  1747. builder.content.appendChild(content)
  1748. }
  1749. function splitSpaces(text, trailingBefore) {
  1750. if (text.length > 1 && !/ /.test(text)) { return text }
  1751. var spaceBefore = trailingBefore, result = ""
  1752. for (var i = 0; i < text.length; i++) {
  1753. var ch = text.charAt(i)
  1754. if (ch == " " && spaceBefore && (i == text.length - 1 || text.charCodeAt(i + 1) == 32))
  1755. { ch = "\u00a0" }
  1756. result += ch
  1757. spaceBefore = ch == " "
  1758. }
  1759. return result
  1760. }
  1761. // Work around nonsense dimensions being reported for stretches of
  1762. // right-to-left text.
  1763. function buildTokenBadBidi(inner, order) {
  1764. return function (builder, text, style, startStyle, endStyle, title, css) {
  1765. style = style ? style + " cm-force-border" : "cm-force-border"
  1766. var start = builder.pos, end = start + text.length
  1767. for (;;) {
  1768. // Find the part that overlaps with the start of this text
  1769. var part = (void 0)
  1770. for (var i = 0; i < order.length; i++) {
  1771. part = order[i]
  1772. if (part.to > start && part.from <= start) { break }
  1773. }
  1774. if (part.to >= end) { return inner(builder, text, style, startStyle, endStyle, title, css) }
  1775. inner(builder, text.slice(0, part.to - start), style, startStyle, null, title, css)
  1776. startStyle = null
  1777. text = text.slice(part.to - start)
  1778. start = part.to
  1779. }
  1780. }
  1781. }
  1782. function buildCollapsedSpan(builder, size, marker, ignoreWidget) {
  1783. var widget = !ignoreWidget && marker.widgetNode
  1784. if (widget) { builder.map.push(builder.pos, builder.pos + size, widget) }
  1785. if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) {
  1786. if (!widget)
  1787. { widget = builder.content.appendChild(document.createElement("span")) }
  1788. widget.setAttribute("cm-marker", marker.id)
  1789. }
  1790. if (widget) {
  1791. builder.cm.display.input.setUneditable(widget)
  1792. builder.content.appendChild(widget)
  1793. }
  1794. builder.pos += size
  1795. builder.trailingSpace = false
  1796. }
  1797. // Outputs a number of spans to make up a line, taking highlighting
  1798. // and marked text into account.
  1799. function insertLineContent(line, builder, styles) {
  1800. var spans = line.markedSpans, allText = line.text, at = 0
  1801. if (!spans) {
  1802. for (var i$1 = 1; i$1 < styles.length; i$1+=2)
  1803. { builder.addToken(builder, allText.slice(at, at = styles[i$1]), interpretTokenStyle(styles[i$1+1], builder.cm.options)) }
  1804. return
  1805. }
  1806. var len = allText.length, pos = 0, i = 1, text = "", style, css
  1807. var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, title, collapsed
  1808. for (;;) {
  1809. if (nextChange == pos) { // Update current marker set
  1810. spanStyle = spanEndStyle = spanStartStyle = title = css = ""
  1811. collapsed = null; nextChange = Infinity
  1812. var foundBookmarks = [], endStyles = (void 0)
  1813. for (var j = 0; j < spans.length; ++j) {
  1814. var sp = spans[j], m = sp.marker
  1815. if (m.type == "bookmark" && sp.from == pos && m.widgetNode) {
  1816. foundBookmarks.push(m)
  1817. } else if (sp.from <= pos && (sp.to == null || sp.to > pos || m.collapsed && sp.to == pos && sp.from == pos)) {
  1818. if (sp.to != null && sp.to != pos && nextChange > sp.to) {
  1819. nextChange = sp.to
  1820. spanEndStyle = ""
  1821. }
  1822. if (m.className) { spanStyle += " " + m.className }
  1823. if (m.css) { css = (css ? css + ";" : "") + m.css }
  1824. if (m.startStyle && sp.from == pos) { spanStartStyle += " " + m.startStyle }
  1825. if (m.endStyle && sp.to == nextChange) { (endStyles || (endStyles = [])).push(m.endStyle, sp.to) }
  1826. if (m.title && !title) { title = m.title }
  1827. if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0))
  1828. { collapsed = sp }
  1829. } else if (sp.from > pos && nextChange > sp.from) {
  1830. nextChange = sp.from
  1831. }
  1832. }
  1833. if (endStyles) { for (var j$1 = 0; j$1 < endStyles.length; j$1 += 2)
  1834. { if (endStyles[j$1 + 1] == nextChange) { spanEndStyle += " " + endStyles[j$1] } } }
  1835. if (!collapsed || collapsed.from == pos) { for (var j$2 = 0; j$2 < foundBookmarks.length; ++j$2)
  1836. { buildCollapsedSpan(builder, 0, foundBookmarks[j$2]) } }
  1837. if (collapsed && (collapsed.from || 0) == pos) {
  1838. buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos,
  1839. collapsed.marker, collapsed.from == null)
  1840. if (collapsed.to == null) { return }
  1841. if (collapsed.to == pos) { collapsed = false }
  1842. }
  1843. }
  1844. if (pos >= len) { break }
  1845. var upto = Math.min(len, nextChange)
  1846. while (true) {
  1847. if (text) {
  1848. var end = pos + text.length
  1849. if (!collapsed) {
  1850. var tokenText = end > upto ? text.slice(0, upto - pos) : text
  1851. builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle,
  1852. spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", title, css)
  1853. }
  1854. if (end >= upto) {text = text.slice(upto - pos); pos = upto; break}
  1855. pos = end
  1856. spanStartStyle = ""
  1857. }
  1858. text = allText.slice(at, at = styles[i++])
  1859. style = interpretTokenStyle(styles[i++], builder.cm.options)
  1860. }
  1861. }
  1862. }
  1863. // These objects are used to represent the visible (currently drawn)
  1864. // part of the document. A LineView may correspond to multiple
  1865. // logical lines, if those are connected by collapsed ranges.
  1866. function LineView(doc, line, lineN) {
  1867. // The starting line
  1868. this.line = line
  1869. // Continuing lines, if any
  1870. this.rest = visualLineContinued(line)
  1871. // Number of logical lines in this visual line
  1872. this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1
  1873. this.node = this.text = null
  1874. this.hidden = lineIsHidden(doc, line)
  1875. }
  1876. // Create a range of LineView objects for the given lines.
  1877. function buildViewArray(cm, from, to) {
  1878. var array = [], nextPos
  1879. for (var pos = from; pos < to; pos = nextPos) {
  1880. var view = new LineView(cm.doc, getLine(cm.doc, pos), pos)
  1881. nextPos = pos + view.size
  1882. array.push(view)
  1883. }
  1884. return array
  1885. }
  1886. var operationGroup = null
  1887. function pushOperation(op) {
  1888. if (operationGroup) {
  1889. operationGroup.ops.push(op)
  1890. } else {
  1891. op.ownsGroup = operationGroup = {
  1892. ops: [op],
  1893. delayedCallbacks: []
  1894. }
  1895. }
  1896. }
  1897. function fireCallbacksForOps(group) {
  1898. // Calls delayed callbacks and cursorActivity handlers until no
  1899. // new ones appear
  1900. var callbacks = group.delayedCallbacks, i = 0
  1901. do {
  1902. for (; i < callbacks.length; i++)
  1903. { callbacks[i].call(null) }
  1904. for (var j = 0; j < group.ops.length; j++) {
  1905. var op = group.ops[j]
  1906. if (op.cursorActivityHandlers)
  1907. { while (op.cursorActivityCalled < op.cursorActivityHandlers.length)
  1908. { op.cursorActivityHandlers[op.cursorActivityCalled++].call(null, op.cm) } }
  1909. }
  1910. } while (i < callbacks.length)
  1911. }
  1912. function finishOperation(op, endCb) {
  1913. var group = op.ownsGroup
  1914. if (!group) { return }
  1915. try { fireCallbacksForOps(group) }
  1916. finally {
  1917. operationGroup = null
  1918. endCb(group)
  1919. }
  1920. }
  1921. var orphanDelayedCallbacks = null
  1922. // Often, we want to signal events at a point where we are in the
  1923. // middle of some work, but don't want the handler to start calling
  1924. // other methods on the editor, which might be in an inconsistent
  1925. // state or simply not expect any other events to happen.
  1926. // signalLater looks whether there are any handlers, and schedules
  1927. // them to be executed when the last operation ends, or, if no
  1928. // operation is active, when a timeout fires.
  1929. function signalLater(emitter, type /*, values...*/) {
  1930. var arr = getHandlers(emitter, type)
  1931. if (!arr.length) { return }
  1932. var args = Array.prototype.slice.call(arguments, 2), list
  1933. if (operationGroup) {
  1934. list = operationGroup.delayedCallbacks
  1935. } else if (orphanDelayedCallbacks) {
  1936. list = orphanDelayedCallbacks
  1937. } else {
  1938. list = orphanDelayedCallbacks = []
  1939. setTimeout(fireOrphanDelayed, 0)
  1940. }
  1941. var loop = function ( i ) {
  1942. list.push(function () { return arr[i].apply(null, args); })
  1943. };
  1944. for (var i = 0; i < arr.length; ++i)
  1945. loop( i );
  1946. }
  1947. function fireOrphanDelayed() {
  1948. var delayed = orphanDelayedCallbacks
  1949. orphanDelayedCallbacks = null
  1950. for (var i = 0; i < delayed.length; ++i) { delayed[i]() }
  1951. }
  1952. // When an aspect of a line changes, a string is added to
  1953. // lineView.changes. This updates the relevant part of the line's
  1954. // DOM structure.
  1955. function updateLineForChanges(cm, lineView, lineN, dims) {
  1956. for (var j = 0; j < lineView.changes.length; j++) {
  1957. var type = lineView.changes[j]
  1958. if (type == "text") { updateLineText(cm, lineView) }
  1959. else if (type == "gutter") { updateLineGutter(cm, lineView, lineN, dims) }
  1960. else if (type == "class") { updateLineClasses(cm, lineView) }
  1961. else if (type == "widget") { updateLineWidgets(cm, lineView, dims) }
  1962. }
  1963. lineView.changes = null
  1964. }
  1965. // Lines with gutter elements, widgets or a background class need to
  1966. // be wrapped, and have the extra elements added to the wrapper div
  1967. function ensureLineWrapped(lineView) {
  1968. if (lineView.node == lineView.text) {
  1969. lineView.node = elt("div", null, null, "position: relative")
  1970. if (lineView.text.parentNode)
  1971. { lineView.text.parentNode.replaceChild(lineView.node, lineView.text) }
  1972. lineView.node.appendChild(lineView.text)
  1973. if (ie && ie_version < 8) { lineView.node.style.zIndex = 2 }
  1974. }
  1975. return lineView.node
  1976. }
  1977. function updateLineBackground(cm, lineView) {
  1978. var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass
  1979. if (cls) { cls += " CodeMirror-linebackground" }
  1980. if (lineView.background) {
  1981. if (cls) { lineView.background.className = cls }
  1982. else { lineView.background.parentNode.removeChild(lineView.background); lineView.background = null }
  1983. } else if (cls) {
  1984. var wrap = ensureLineWrapped(lineView)
  1985. lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild)
  1986. cm.display.input.setUneditable(lineView.background)
  1987. }
  1988. }
  1989. // Wrapper around buildLineContent which will reuse the structure
  1990. // in display.externalMeasured when possible.
  1991. function getLineContent(cm, lineView) {
  1992. var ext = cm.display.externalMeasured
  1993. if (ext && ext.line == lineView.line) {
  1994. cm.display.externalMeasured = null
  1995. lineView.measure = ext.measure
  1996. return ext.built
  1997. }
  1998. return buildLineContent(cm, lineView)
  1999. }
  2000. // Redraw the line's text. Interacts with the background and text
  2001. // classes because the mode may output tokens that influence these
  2002. // classes.
  2003. function updateLineText(cm, lineView) {
  2004. var cls = lineView.text.className
  2005. var built = getLineContent(cm, lineView)
  2006. if (lineView.text == lineView.node) { lineView.node = built.pre }
  2007. lineView.text.parentNode.replaceChild(built.pre, lineView.text)
  2008. lineView.text = built.pre
  2009. if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) {
  2010. lineView.bgClass = built.bgClass
  2011. lineView.textClass = built.textClass
  2012. updateLineClasses(cm, lineView)
  2013. } else if (cls) {
  2014. lineView.text.className = cls
  2015. }
  2016. }
  2017. function updateLineClasses(cm, lineView) {
  2018. updateLineBackground(cm, lineView)
  2019. if (lineView.line.wrapClass)
  2020. { ensureLineWrapped(lineView).className = lineView.line.wrapClass }
  2021. else if (lineView.node != lineView.text)
  2022. { lineView.node.className = "" }
  2023. var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass
  2024. lineView.text.className = textClass || ""
  2025. }
  2026. function updateLineGutter(cm, lineView, lineN, dims) {
  2027. if (lineView.gutter) {
  2028. lineView.node.removeChild(lineView.gutter)
  2029. lineView.gutter = null
  2030. }
  2031. if (lineView.gutterBackground) {
  2032. lineView.node.removeChild(lineView.gutterBackground)
  2033. lineView.gutterBackground = null
  2034. }
  2035. if (lineView.line.gutterClass) {
  2036. var wrap = ensureLineWrapped(lineView)
  2037. lineView.gutterBackground = elt("div", null, "CodeMirror-gutter-background " + lineView.line.gutterClass,
  2038. ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px; width: " + (dims.gutterTotalWidth) + "px"))
  2039. cm.display.input.setUneditable(lineView.gutterBackground)
  2040. wrap.insertBefore(lineView.gutterBackground, lineView.text)
  2041. }
  2042. var markers = lineView.line.gutterMarkers
  2043. if (cm.options.lineNumbers || markers) {
  2044. var wrap$1 = ensureLineWrapped(lineView)
  2045. var gutterWrap = lineView.gutter = elt("div", null, "CodeMirror-gutter-wrapper", ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px"))
  2046. cm.display.input.setUneditable(gutterWrap)
  2047. wrap$1.insertBefore(gutterWrap, lineView.text)
  2048. if (lineView.line.gutterClass)
  2049. { gutterWrap.className += " " + lineView.line.gutterClass }
  2050. if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"]))
  2051. { lineView.lineNumber = gutterWrap.appendChild(
  2052. elt("div", lineNumberFor(cm.options, lineN),
  2053. "CodeMirror-linenumber CodeMirror-gutter-elt",
  2054. ("left: " + (dims.gutterLeft["CodeMirror-linenumbers"]) + "px; width: " + (cm.display.lineNumInnerWidth) + "px"))) }
  2055. if (markers) { for (var k = 0; k < cm.options.gutters.length; ++k) {
  2056. var id = cm.options.gutters[k], found = markers.hasOwnProperty(id) && markers[id]
  2057. if (found)
  2058. { gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt",
  2059. ("left: " + (dims.gutterLeft[id]) + "px; width: " + (dims.gutterWidth[id]) + "px"))) }
  2060. } }
  2061. }
  2062. }
  2063. function updateLineWidgets(cm, lineView, dims) {
  2064. if (lineView.alignable) { lineView.alignable = null }
  2065. for (var node = lineView.node.firstChild, next = (void 0); node; node = next) {
  2066. next = node.nextSibling
  2067. if (node.className == "CodeMirror-linewidget")
  2068. { lineView.node.removeChild(node) }
  2069. }
  2070. insertLineWidgets(cm, lineView, dims)
  2071. }
  2072. // Build a line's DOM representation from scratch
  2073. function buildLineElement(cm, lineView, lineN, dims) {
  2074. var built = getLineContent(cm, lineView)
  2075. lineView.text = lineView.node = built.pre
  2076. if (built.bgClass) { lineView.bgClass = built.bgClass }
  2077. if (built.textClass) { lineView.textClass = built.textClass }
  2078. updateLineClasses(cm, lineView)
  2079. updateLineGutter(cm, lineView, lineN, dims)
  2080. insertLineWidgets(cm, lineView, dims)
  2081. return lineView.node
  2082. }
  2083. // A lineView may contain multiple logical lines (when merged by
  2084. // collapsed spans). The widgets for all of them need to be drawn.
  2085. function insertLineWidgets(cm, lineView, dims) {
  2086. insertLineWidgetsFor(cm, lineView.line, lineView, dims, true)
  2087. if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++)
  2088. { insertLineWidgetsFor(cm, lineView.rest[i], lineView, dims, false) } }
  2089. }
  2090. function insertLineWidgetsFor(cm, line, lineView, dims, allowAbove) {
  2091. if (!line.widgets) { return }
  2092. var wrap = ensureLineWrapped(lineView)
  2093. for (var i = 0, ws = line.widgets; i < ws.length; ++i) {
  2094. var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget")
  2095. if (!widget.handleMouseEvents) { node.setAttribute("cm-ignore-events", "true") }
  2096. positionLineWidget(widget, node, lineView, dims)
  2097. cm.display.input.setUneditable(node)
  2098. if (allowAbove && widget.above)
  2099. { wrap.insertBefore(node, lineView.gutter || lineView.text) }
  2100. else
  2101. { wrap.appendChild(node) }
  2102. signalLater(widget, "redraw")
  2103. }
  2104. }
  2105. function positionLineWidget(widget, node, lineView, dims) {
  2106. if (widget.noHScroll) {
  2107. ;(lineView.alignable || (lineView.alignable = [])).push(node)
  2108. var width = dims.wrapperWidth
  2109. node.style.left = dims.fixedPos + "px"
  2110. if (!widget.coverGutter) {
  2111. width -= dims.gutterTotalWidth
  2112. node.style.paddingLeft = dims.gutterTotalWidth + "px"
  2113. }
  2114. node.style.width = width + "px"
  2115. }
  2116. if (widget.coverGutter) {
  2117. node.style.zIndex = 5
  2118. node.style.position = "relative"
  2119. if (!widget.noHScroll) { node.style.marginLeft = -dims.gutterTotalWidth + "px" }
  2120. }
  2121. }
  2122. function widgetHeight(widget) {
  2123. if (widget.height != null) { return widget.height }
  2124. var cm = widget.doc.cm
  2125. if (!cm) { return 0 }
  2126. if (!contains(document.body, widget.node)) {
  2127. var parentStyle = "position: relative;"
  2128. if (widget.coverGutter)
  2129. { parentStyle += "margin-left: -" + cm.display.gutters.offsetWidth + "px;" }
  2130. if (widget.noHScroll)
  2131. { parentStyle += "width: " + cm.display.wrapper.clientWidth + "px;" }
  2132. removeChildrenAndAdd(cm.display.measure, elt("div", [widget.node], null, parentStyle))
  2133. }
  2134. return widget.height = widget.node.parentNode.offsetHeight
  2135. }
  2136. // Return true when the given mouse event happened in a widget
  2137. function eventInWidget(display, e) {
  2138. for (var n = e_target(e); n != display.wrapper; n = n.parentNode) {
  2139. if (!n || (n.nodeType == 1 && n.getAttribute("cm-ignore-events") == "true") ||
  2140. (n.parentNode == display.sizer && n != display.mover))
  2141. { return true }
  2142. }
  2143. }
  2144. // POSITION MEASUREMENT
  2145. function paddingTop(display) {return display.lineSpace.offsetTop}
  2146. function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight}
  2147. function paddingH(display) {
  2148. if (display.cachedPaddingH) { return display.cachedPaddingH }
  2149. var e = removeChildrenAndAdd(display.measure, elt("pre", "x"))
  2150. var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle
  2151. var data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)}
  2152. if (!isNaN(data.left) && !isNaN(data.right)) { display.cachedPaddingH = data }
  2153. return data
  2154. }
  2155. function scrollGap(cm) { return scrollerGap - cm.display.nativeBarWidth }
  2156. function displayWidth(cm) {
  2157. return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth
  2158. }
  2159. function displayHeight(cm) {
  2160. return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight
  2161. }
  2162. // Ensure the lineView.wrapping.heights array is populated. This is
  2163. // an array of bottom offsets for the lines that make up a drawn
  2164. // line. When lineWrapping is on, there might be more than one
  2165. // height.
  2166. function ensureLineHeights(cm, lineView, rect) {
  2167. var wrapping = cm.options.lineWrapping
  2168. var curWidth = wrapping && displayWidth(cm)
  2169. if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) {
  2170. var heights = lineView.measure.heights = []
  2171. if (wrapping) {
  2172. lineView.measure.width = curWidth
  2173. var rects = lineView.text.firstChild.getClientRects()
  2174. for (var i = 0; i < rects.length - 1; i++) {
  2175. var cur = rects[i], next = rects[i + 1]
  2176. if (Math.abs(cur.bottom - next.bottom) > 2)
  2177. { heights.push((cur.bottom + next.top) / 2 - rect.top) }
  2178. }
  2179. }
  2180. heights.push(rect.bottom - rect.top)
  2181. }
  2182. }
  2183. // Find a line map (mapping character offsets to text nodes) and a
  2184. // measurement cache for the given line number. (A line view might
  2185. // contain multiple lines when collapsed ranges are present.)
  2186. function mapFromLineView(lineView, line, lineN) {
  2187. if (lineView.line == line)
  2188. { return {map: lineView.measure.map, cache: lineView.measure.cache} }
  2189. for (var i = 0; i < lineView.rest.length; i++)
  2190. { if (lineView.rest[i] == line)
  2191. { return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i]} } }
  2192. for (var i$1 = 0; i$1 < lineView.rest.length; i$1++)
  2193. { if (lineNo(lineView.rest[i$1]) > lineN)
  2194. { return {map: lineView.measure.maps[i$1], cache: lineView.measure.caches[i$1], before: true} } }
  2195. }
  2196. // Render a line into the hidden node display.externalMeasured. Used
  2197. // when measurement is needed for a line that's not in the viewport.
  2198. function updateExternalMeasurement(cm, line) {
  2199. line = visualLine(line)
  2200. var lineN = lineNo(line)
  2201. var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN)
  2202. view.lineN = lineN
  2203. var built = view.built = buildLineContent(cm, view)
  2204. view.text = built.pre
  2205. removeChildrenAndAdd(cm.display.lineMeasure, built.pre)
  2206. return view
  2207. }
  2208. // Get a {top, bottom, left, right} box (in line-local coordinates)
  2209. // for a given character.
  2210. function measureChar(cm, line, ch, bias) {
  2211. return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias)
  2212. }
  2213. // Find a line view that corresponds to the given line number.
  2214. function findViewForLine(cm, lineN) {
  2215. if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo)
  2216. { return cm.display.view[findViewIndex(cm, lineN)] }
  2217. var ext = cm.display.externalMeasured
  2218. if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size)
  2219. { return ext }
  2220. }
  2221. // Measurement can be split in two steps, the set-up work that
  2222. // applies to the whole line, and the measurement of the actual
  2223. // character. Functions like coordsChar, that need to do a lot of
  2224. // measurements in a row, can thus ensure that the set-up work is
  2225. // only done once.
  2226. function prepareMeasureForLine(cm, line) {
  2227. var lineN = lineNo(line)
  2228. var view = findViewForLine(cm, lineN)
  2229. if (view && !view.text) {
  2230. view = null
  2231. } else if (view && view.changes) {
  2232. updateLineForChanges(cm, view, lineN, getDimensions(cm))
  2233. cm.curOp.forceUpdate = true
  2234. }
  2235. if (!view)
  2236. { view = updateExternalMeasurement(cm, line) }
  2237. var info = mapFromLineView(view, line, lineN)
  2238. return {
  2239. line: line, view: view, rect: null,
  2240. map: info.map, cache: info.cache, before: info.before,
  2241. hasHeights: false
  2242. }
  2243. }
  2244. // Given a prepared measurement object, measures the position of an
  2245. // actual character (or fetches it from the cache).
  2246. function measureCharPrepared(cm, prepared, ch, bias, varHeight) {
  2247. if (prepared.before) { ch = -1 }
  2248. var key = ch + (bias || ""), found
  2249. if (prepared.cache.hasOwnProperty(key)) {
  2250. found = prepared.cache[key]
  2251. } else {
  2252. if (!prepared.rect)
  2253. { prepared.rect = prepared.view.text.getBoundingClientRect() }
  2254. if (!prepared.hasHeights) {
  2255. ensureLineHeights(cm, prepared.view, prepared.rect)
  2256. prepared.hasHeights = true
  2257. }
  2258. found = measureCharInner(cm, prepared, ch, bias)
  2259. if (!found.bogus) { prepared.cache[key] = found }
  2260. }
  2261. return {left: found.left, right: found.right,
  2262. top: varHeight ? found.rtop : found.top,
  2263. bottom: varHeight ? found.rbottom : found.bottom}
  2264. }
  2265. var nullRect = {left: 0, right: 0, top: 0, bottom: 0}
  2266. function nodeAndOffsetInLineMap(map, ch, bias) {
  2267. var node, start, end, collapse, mStart, mEnd
  2268. // First, search the line map for the text node corresponding to,
  2269. // or closest to, the target character.
  2270. for (var i = 0; i < map.length; i += 3) {
  2271. mStart = map[i]
  2272. mEnd = map[i + 1]
  2273. if (ch < mStart) {
  2274. start = 0; end = 1
  2275. collapse = "left"
  2276. } else if (ch < mEnd) {
  2277. start = ch - mStart
  2278. end = start + 1
  2279. } else if (i == map.length - 3 || ch == mEnd && map[i + 3] > ch) {
  2280. end = mEnd - mStart
  2281. start = end - 1
  2282. if (ch >= mEnd) { collapse = "right" }
  2283. }
  2284. if (start != null) {
  2285. node = map[i + 2]
  2286. if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right"))
  2287. { collapse = bias }
  2288. if (bias == "left" && start == 0)
  2289. { while (i && map[i - 2] == map[i - 3] && map[i - 1].insertLeft) {
  2290. node = map[(i -= 3) + 2]
  2291. collapse = "left"
  2292. } }
  2293. if (bias == "right" && start == mEnd - mStart)
  2294. { while (i < map.length - 3 && map[i + 3] == map[i + 4] && !map[i + 5].insertLeft) {
  2295. node = map[(i += 3) + 2]
  2296. collapse = "right"
  2297. } }
  2298. break
  2299. }
  2300. }
  2301. return {node: node, start: start, end: end, collapse: collapse, coverStart: mStart, coverEnd: mEnd}
  2302. }
  2303. function getUsefulRect(rects, bias) {
  2304. var rect = nullRect
  2305. if (bias == "left") { for (var i = 0; i < rects.length; i++) {
  2306. if ((rect = rects[i]).left != rect.right) { break }
  2307. } } else { for (var i$1 = rects.length - 1; i$1 >= 0; i$1--) {
  2308. if ((rect = rects[i$1]).left != rect.right) { break }
  2309. } }
  2310. return rect
  2311. }
  2312. function measureCharInner(cm, prepared, ch, bias) {
  2313. var place = nodeAndOffsetInLineMap(prepared.map, ch, bias)
  2314. var node = place.node, start = place.start, end = place.end, collapse = place.collapse
  2315. var rect
  2316. if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates.
  2317. for (var i$1 = 0; i$1 < 4; i$1++) { // Retry a maximum of 4 times when nonsense rectangles are returned
  2318. while (start && isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) { --start }
  2319. while (place.coverStart + end < place.coverEnd && isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) { ++end }
  2320. if (ie && ie_version < 9 && start == 0 && end == place.coverEnd - place.coverStart)
  2321. { rect = node.parentNode.getBoundingClientRect() }
  2322. else
  2323. { rect = getUsefulRect(range(node, start, end).getClientRects(), bias) }
  2324. if (rect.left || rect.right || start == 0) { break }
  2325. end = start
  2326. start = start - 1
  2327. collapse = "right"
  2328. }
  2329. if (ie && ie_version < 11) { rect = maybeUpdateRectForZooming(cm.display.measure, rect) }
  2330. } else { // If it is a widget, simply get the box for the whole widget.
  2331. if (start > 0) { collapse = bias = "right" }
  2332. var rects
  2333. if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1)
  2334. { rect = rects[bias == "right" ? rects.length - 1 : 0] }
  2335. else
  2336. { rect = node.getBoundingClientRect() }
  2337. }
  2338. if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) {
  2339. var rSpan = node.parentNode.getClientRects()[0]
  2340. if (rSpan)
  2341. { rect = {left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom} }
  2342. else
  2343. { rect = nullRect }
  2344. }
  2345. var rtop = rect.top - prepared.rect.top, rbot = rect.bottom - prepared.rect.top
  2346. var mid = (rtop + rbot) / 2
  2347. var heights = prepared.view.measure.heights
  2348. var i = 0
  2349. for (; i < heights.length - 1; i++)
  2350. { if (mid < heights[i]) { break } }
  2351. var top = i ? heights[i - 1] : 0, bot = heights[i]
  2352. var result = {left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left,
  2353. right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left,
  2354. top: top, bottom: bot}
  2355. if (!rect.left && !rect.right) { result.bogus = true }
  2356. if (!cm.options.singleCursorHeightPerLine) { result.rtop = rtop; result.rbottom = rbot }
  2357. return result
  2358. }
  2359. // Work around problem with bounding client rects on ranges being
  2360. // returned incorrectly when zoomed on IE10 and below.
  2361. function maybeUpdateRectForZooming(measure, rect) {
  2362. if (!window.screen || screen.logicalXDPI == null ||
  2363. screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure))
  2364. { return rect }
  2365. var scaleX = screen.logicalXDPI / screen.deviceXDPI
  2366. var scaleY = screen.logicalYDPI / screen.deviceYDPI
  2367. return {left: rect.left * scaleX, right: rect.right * scaleX,
  2368. top: rect.top * scaleY, bottom: rect.bottom * scaleY}
  2369. }
  2370. function clearLineMeasurementCacheFor(lineView) {
  2371. if (lineView.measure) {
  2372. lineView.measure.cache = {}
  2373. lineView.measure.heights = null
  2374. if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++)
  2375. { lineView.measure.caches[i] = {} } }
  2376. }
  2377. }
  2378. function clearLineMeasurementCache(cm) {
  2379. cm.display.externalMeasure = null
  2380. removeChildren(cm.display.lineMeasure)
  2381. for (var i = 0; i < cm.display.view.length; i++)
  2382. { clearLineMeasurementCacheFor(cm.display.view[i]) }
  2383. }
  2384. function clearCaches(cm) {
  2385. clearLineMeasurementCache(cm)
  2386. cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null
  2387. if (!cm.options.lineWrapping) { cm.display.maxLineChanged = true }
  2388. cm.display.lineNumChars = null
  2389. }
  2390. function pageScrollX() {
  2391. // Work around https://bugs.chromium.org/p/chromium/issues/detail?id=489206
  2392. // which causes page_Offset and bounding client rects to use
  2393. // different reference viewports and invalidate our calculations.
  2394. if (chrome && android) { return -(document.body.getBoundingClientRect().left - parseInt(getComputedStyle(document.body).marginLeft)) }
  2395. return window.pageXOffset || (document.documentElement || document.body).scrollLeft
  2396. }
  2397. function pageScrollY() {
  2398. if (chrome && android) { return -(document.body.getBoundingClientRect().top - parseInt(getComputedStyle(document.body).marginTop)) }
  2399. return window.pageYOffset || (document.documentElement || document.body).scrollTop
  2400. }
  2401. function widgetTopHeight(lineObj) {
  2402. var height = 0
  2403. if (lineObj.widgets) { for (var i = 0; i < lineObj.widgets.length; ++i) { if (lineObj.widgets[i].above)
  2404. { height += widgetHeight(lineObj.widgets[i]) } } }
  2405. return height
  2406. }
  2407. // Converts a {top, bottom, left, right} box from line-local
  2408. // coordinates into another coordinate system. Context may be one of
  2409. // "line", "div" (display.lineDiv), "local"./null (editor), "window",
  2410. // or "page".
  2411. function intoCoordSystem(cm, lineObj, rect, context, includeWidgets) {
  2412. if (!includeWidgets) {
  2413. var height = widgetTopHeight(lineObj)
  2414. rect.top += height; rect.bottom += height
  2415. }
  2416. if (context == "line") { return rect }
  2417. if (!context) { context = "local" }
  2418. var yOff = heightAtLine(lineObj)
  2419. if (context == "local") { yOff += paddingTop(cm.display) }
  2420. else { yOff -= cm.display.viewOffset }
  2421. if (context == "page" || context == "window") {
  2422. var lOff = cm.display.lineSpace.getBoundingClientRect()
  2423. yOff += lOff.top + (context == "window" ? 0 : pageScrollY())
  2424. var xOff = lOff.left + (context == "window" ? 0 : pageScrollX())
  2425. rect.left += xOff; rect.right += xOff
  2426. }
  2427. rect.top += yOff; rect.bottom += yOff
  2428. return rect
  2429. }
  2430. // Coverts a box from "div" coords to another coordinate system.
  2431. // Context may be "window", "page", "div", or "local"./null.
  2432. function fromCoordSystem(cm, coords, context) {
  2433. if (context == "div") { return coords }
  2434. var left = coords.left, top = coords.top
  2435. // First move into "page" coordinate system
  2436. if (context == "page") {
  2437. left -= pageScrollX()
  2438. top -= pageScrollY()
  2439. } else if (context == "local" || !context) {
  2440. var localBox = cm.display.sizer.getBoundingClientRect()
  2441. left += localBox.left
  2442. top += localBox.top
  2443. }
  2444. var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect()
  2445. return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top}
  2446. }
  2447. function charCoords(cm, pos, context, lineObj, bias) {
  2448. if (!lineObj) { lineObj = getLine(cm.doc, pos.line) }
  2449. return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context)
  2450. }
  2451. // Returns a box for a given cursor position, which may have an
  2452. // 'other' property containing the position of the secondary cursor
  2453. // on a bidi boundary.
  2454. // A cursor Pos(line, char, "before") is on the same visual line as `char - 1`
  2455. // and after `char - 1` in writing order of `char - 1`
  2456. // A cursor Pos(line, char, "after") is on the same visual line as `char`
  2457. // and before `char` in writing order of `char`
  2458. // Examples (upper-case letters are RTL, lower-case are LTR):
  2459. // Pos(0, 1, ...)
  2460. // before after
  2461. // ab a|b a|b
  2462. // aB a|B aB|
  2463. // Ab |Ab A|b
  2464. // AB B|A B|A
  2465. // Every position after the last character on a line is considered to stick
  2466. // to the last character on the line.
  2467. function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) {
  2468. lineObj = lineObj || getLine(cm.doc, pos.line)
  2469. if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj) }
  2470. function get(ch, right) {
  2471. var m = measureCharPrepared(cm, preparedMeasure, ch, right ? "right" : "left", varHeight)
  2472. if (right) { m.left = m.right; } else { m.right = m.left }
  2473. return intoCoordSystem(cm, lineObj, m, context)
  2474. }
  2475. var order = getOrder(lineObj, cm.doc.direction), ch = pos.ch, sticky = pos.sticky
  2476. if (ch >= lineObj.text.length) {
  2477. ch = lineObj.text.length
  2478. sticky = "before"
  2479. } else if (ch <= 0) {
  2480. ch = 0
  2481. sticky = "after"
  2482. }
  2483. if (!order) { return get(sticky == "before" ? ch - 1 : ch, sticky == "before") }
  2484. function getBidi(ch, partPos, invert) {
  2485. var part = order[partPos], right = part.level == 1
  2486. return get(invert ? ch - 1 : ch, right != invert)
  2487. }
  2488. var partPos = getBidiPartAt(order, ch, sticky)
  2489. var other = bidiOther
  2490. var val = getBidi(ch, partPos, sticky == "before")
  2491. if (other != null) { val.other = getBidi(ch, other, sticky != "before") }
  2492. return val
  2493. }
  2494. // Used to cheaply estimate the coordinates for a position. Used for
  2495. // intermediate scroll updates.
  2496. function estimateCoords(cm, pos) {
  2497. var left = 0
  2498. pos = clipPos(cm.doc, pos)
  2499. if (!cm.options.lineWrapping) { left = charWidth(cm.display) * pos.ch }
  2500. var lineObj = getLine(cm.doc, pos.line)
  2501. var top = heightAtLine(lineObj) + paddingTop(cm.display)
  2502. return {left: left, right: left, top: top, bottom: top + lineObj.height}
  2503. }
  2504. // Positions returned by coordsChar contain some extra information.
  2505. // xRel is the relative x position of the input coordinates compared
  2506. // to the found position (so xRel > 0 means the coordinates are to
  2507. // the right of the character position, for example). When outside
  2508. // is true, that means the coordinates lie outside the line's
  2509. // vertical range.
  2510. function PosWithInfo(line, ch, sticky, outside, xRel) {
  2511. var pos = Pos(line, ch, sticky)
  2512. pos.xRel = xRel
  2513. if (outside) { pos.outside = true }
  2514. return pos
  2515. }
  2516. // Compute the character position closest to the given coordinates.
  2517. // Input must be lineSpace-local ("div" coordinate system).
  2518. function coordsChar(cm, x, y) {
  2519. var doc = cm.doc
  2520. y += cm.display.viewOffset
  2521. if (y < 0) { return PosWithInfo(doc.first, 0, null, true, -1) }
  2522. var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1
  2523. if (lineN > last)
  2524. { return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, null, true, 1) }
  2525. if (x < 0) { x = 0 }
  2526. var lineObj = getLine(doc, lineN)
  2527. for (;;) {
  2528. var found = coordsCharInner(cm, lineObj, lineN, x, y)
  2529. var merged = collapsedSpanAtEnd(lineObj)
  2530. var mergedPos = merged && merged.find(0, true)
  2531. if (merged && (found.ch > mergedPos.from.ch || found.ch == mergedPos.from.ch && found.xRel > 0))
  2532. { lineN = lineNo(lineObj = mergedPos.to.line) }
  2533. else
  2534. { return found }
  2535. }
  2536. }
  2537. function wrappedLineExtent(cm, lineObj, preparedMeasure, y) {
  2538. y -= widgetTopHeight(lineObj)
  2539. var end = lineObj.text.length
  2540. var begin = findFirst(function (ch) { return measureCharPrepared(cm, preparedMeasure, ch - 1).bottom <= y; }, end, 0)
  2541. end = findFirst(function (ch) { return measureCharPrepared(cm, preparedMeasure, ch).top > y; }, begin, end)
  2542. return {begin: begin, end: end}
  2543. }
  2544. function wrappedLineExtentChar(cm, lineObj, preparedMeasure, target) {
  2545. if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj) }
  2546. var targetTop = intoCoordSystem(cm, lineObj, measureCharPrepared(cm, preparedMeasure, target), "line").top
  2547. return wrappedLineExtent(cm, lineObj, preparedMeasure, targetTop)
  2548. }
  2549. // Returns true if the given side of a box is after the given
  2550. // coordinates, in top-to-bottom, left-to-right order.
  2551. function boxIsAfter(box, x, y, left) {
  2552. return box.bottom <= y ? false : box.top > y ? true : (left ? box.left : box.right) > x
  2553. }
  2554. function coordsCharInner(cm, lineObj, lineNo, x, y) {
  2555. // Move y into line-local coordinate space
  2556. y -= heightAtLine(lineObj)
  2557. var preparedMeasure = prepareMeasureForLine(cm, lineObj)
  2558. // When directly calling `measureCharPrepared`, we have to adjust
  2559. // for the widgets at this line.
  2560. var widgetHeight = widgetTopHeight(lineObj)
  2561. var begin = 0, end = lineObj.text.length, ltr = true
  2562. var order = getOrder(lineObj, cm.doc.direction)
  2563. // If the line isn't plain left-to-right text, first figure out
  2564. // which bidi section the coordinates fall into.
  2565. if (order) {
  2566. var part = (cm.options.lineWrapping ? coordsBidiPartWrapped : coordsBidiPart)
  2567. (cm, lineObj, lineNo, preparedMeasure, order, x, y)
  2568. ltr = part.level != 1
  2569. // The awkward -1 offsets are needed because findFirst (called
  2570. // on these below) will treat its first bound as inclusive,
  2571. // second as exclusive, but we want to actually address the
  2572. // characters in the part's range
  2573. begin = ltr ? part.from : part.to - 1
  2574. end = ltr ? part.to : part.from - 1
  2575. }
  2576. // A binary search to find the first character whose bounding box
  2577. // starts after the coordinates. If we run across any whose box wrap
  2578. // the coordinates, store that.
  2579. var chAround = null, boxAround = null
  2580. var ch = findFirst(function (ch) {
  2581. var box = measureCharPrepared(cm, preparedMeasure, ch)
  2582. box.top += widgetHeight; box.bottom += widgetHeight
  2583. if (!boxIsAfter(box, x, y, false)) { return false }
  2584. if (box.top <= y && box.left <= x) {
  2585. chAround = ch
  2586. boxAround = box
  2587. }
  2588. return true
  2589. }, begin, end)
  2590. var baseX, sticky, outside = false
  2591. // If a box around the coordinates was found, use that
  2592. if (boxAround) {
  2593. // Distinguish coordinates nearer to the left or right side of the box
  2594. var atLeft = x - boxAround.left < boxAround.right - x, atStart = atLeft == ltr
  2595. ch = chAround + (atStart ? 0 : 1)
  2596. sticky = atStart ? "after" : "before"
  2597. baseX = atLeft ? boxAround.left : boxAround.right
  2598. } else {
  2599. // (Adjust for extended bound, if necessary.)
  2600. if (!ltr && (ch == end || ch == begin)) { ch++ }
  2601. // To determine which side to associate with, get the box to the
  2602. // left of the character and compare it's vertical position to the
  2603. // coordinates
  2604. sticky = ch == 0 ? "after" : ch == lineObj.text.length ? "before" :
  2605. (measureCharPrepared(cm, preparedMeasure, ch - (ltr ? 1 : 0)).bottom + widgetHeight <= y) == ltr ?
  2606. "after" : "before"
  2607. // Now get accurate coordinates for this place, in order to get a
  2608. // base X position
  2609. var coords = cursorCoords(cm, Pos(lineNo, ch, sticky), "line", lineObj, preparedMeasure)
  2610. baseX = coords.left
  2611. outside = y < coords.top || y >= coords.bottom
  2612. }
  2613. ch = skipExtendingChars(lineObj.text, ch, 1)
  2614. return PosWithInfo(lineNo, ch, sticky, outside, x - baseX)
  2615. }
  2616. function coordsBidiPart(cm, lineObj, lineNo, preparedMeasure, order, x, y) {
  2617. // Bidi parts are sorted left-to-right, and in a non-line-wrapping
  2618. // situation, we can take this ordering to correspond to the visual
  2619. // ordering. This finds the first part whose end is after the given
  2620. // coordinates.
  2621. var index = findFirst(function (i) {
  2622. var part = order[i], ltr = part.level != 1
  2623. return boxIsAfter(cursorCoords(cm, Pos(lineNo, ltr ? part.to : part.from, ltr ? "before" : "after"),
  2624. "line", lineObj, preparedMeasure), x, y, true)
  2625. }, 0, order.length - 1)
  2626. var part = order[index]
  2627. // If this isn't the first part, the part's start is also after
  2628. // the coordinates, and the coordinates aren't on the same line as
  2629. // that start, move one part back.
  2630. if (index > 0) {
  2631. var ltr = part.level != 1
  2632. var start = cursorCoords(cm, Pos(lineNo, ltr ? part.from : part.to, ltr ? "after" : "before"),
  2633. "line", lineObj, preparedMeasure)
  2634. if (boxIsAfter(start, x, y, true) && start.top > y)
  2635. { part = order[index - 1] }
  2636. }
  2637. return part
  2638. }
  2639. function coordsBidiPartWrapped(cm, lineObj, _lineNo, preparedMeasure, order, x, y) {
  2640. // In a wrapped line, rtl text on wrapping boundaries can do things
  2641. // that don't correspond to the ordering in our `order` array at
  2642. // all, so a binary search doesn't work, and we want to return a
  2643. // part that only spans one line so that the binary search in
  2644. // coordsCharInner is safe. As such, we first find the extent of the
  2645. // wrapped line, and then do a flat search in which we discard any
  2646. // spans that aren't on the line.
  2647. var ref = wrappedLineExtent(cm, lineObj, preparedMeasure, y);
  2648. var begin = ref.begin;
  2649. var end = ref.end;
  2650. if (/\s/.test(lineObj.text.charAt(end - 1))) { end-- }
  2651. var part = null, closestDist = null
  2652. for (var i = 0; i < order.length; i++) {
  2653. var p = order[i]
  2654. if (p.from >= end || p.to <= begin) { continue }
  2655. var ltr = p.level != 1
  2656. var endX = measureCharPrepared(cm, preparedMeasure, ltr ? Math.min(end, p.to) - 1 : Math.max(begin, p.from)).right
  2657. // Weigh against spans ending before this, so that they are only
  2658. // picked if nothing ends after
  2659. var dist = endX < x ? x - endX + 1e9 : endX - x
  2660. if (!part || closestDist > dist) {
  2661. part = p
  2662. closestDist = dist
  2663. }
  2664. }
  2665. if (!part) { part = order[order.length - 1] }
  2666. // Clip the part to the wrapped line.
  2667. if (part.from < begin) { part = {from: begin, to: part.to, level: part.level} }
  2668. if (part.to > end) { part = {from: part.from, to: end, level: part.level} }
  2669. return part
  2670. }
  2671. var measureText
  2672. // Compute the default text height.
  2673. function textHeight(display) {
  2674. if (display.cachedTextHeight != null) { return display.cachedTextHeight }
  2675. if (measureText == null) {
  2676. measureText = elt("pre")
  2677. // Measure a bunch of lines, for browsers that compute
  2678. // fractional heights.
  2679. for (var i = 0; i < 49; ++i) {
  2680. measureText.appendChild(document.createTextNode("x"))
  2681. measureText.appendChild(elt("br"))
  2682. }
  2683. measureText.appendChild(document.createTextNode("x"))
  2684. }
  2685. removeChildrenAndAdd(display.measure, measureText)
  2686. var height = measureText.offsetHeight / 50
  2687. if (height > 3) { display.cachedTextHeight = height }
  2688. removeChildren(display.measure)
  2689. return height || 1
  2690. }
  2691. // Compute the default character width.
  2692. function charWidth(display) {
  2693. if (display.cachedCharWidth != null) { return display.cachedCharWidth }
  2694. var anchor = elt("span", "xxxxxxxxxx")
  2695. var pre = elt("pre", [anchor])
  2696. removeChildrenAndAdd(display.measure, pre)
  2697. var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10
  2698. if (width > 2) { display.cachedCharWidth = width }
  2699. return width || 10
  2700. }
  2701. // Do a bulk-read of the DOM positions and sizes needed to draw the
  2702. // view, so that we don't interleave reading and writing to the DOM.
  2703. function getDimensions(cm) {
  2704. var d = cm.display, left = {}, width = {}
  2705. var gutterLeft = d.gutters.clientLeft
  2706. for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) {
  2707. left[cm.options.gutters[i]] = n.offsetLeft + n.clientLeft + gutterLeft
  2708. width[cm.options.gutters[i]] = n.clientWidth
  2709. }
  2710. return {fixedPos: compensateForHScroll(d),
  2711. gutterTotalWidth: d.gutters.offsetWidth,
  2712. gutterLeft: left,
  2713. gutterWidth: width,
  2714. wrapperWidth: d.wrapper.clientWidth}
  2715. }
  2716. // Computes display.scroller.scrollLeft + display.gutters.offsetWidth,
  2717. // but using getBoundingClientRect to get a sub-pixel-accurate
  2718. // result.
  2719. function compensateForHScroll(display) {
  2720. return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left
  2721. }
  2722. // Returns a function that estimates the height of a line, to use as
  2723. // first approximation until the line becomes visible (and is thus
  2724. // properly measurable).
  2725. function estimateHeight(cm) {
  2726. var th = textHeight(cm.display), wrapping = cm.options.lineWrapping
  2727. var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3)
  2728. return function (line) {
  2729. if (lineIsHidden(cm.doc, line)) { return 0 }
  2730. var widgetsHeight = 0
  2731. if (line.widgets) { for (var i = 0; i < line.widgets.length; i++) {
  2732. if (line.widgets[i].height) { widgetsHeight += line.widgets[i].height }
  2733. } }
  2734. if (wrapping)
  2735. { return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th }
  2736. else
  2737. { return widgetsHeight + th }
  2738. }
  2739. }
  2740. function estimateLineHeights(cm) {
  2741. var doc = cm.doc, est = estimateHeight(cm)
  2742. doc.iter(function (line) {
  2743. var estHeight = est(line)
  2744. if (estHeight != line.height) { updateLineHeight(line, estHeight) }
  2745. })
  2746. }
  2747. // Given a mouse event, find the corresponding position. If liberal
  2748. // is false, it checks whether a gutter or scrollbar was clicked,
  2749. // and returns null if it was. forRect is used by rectangular
  2750. // selections, and tries to estimate a character position even for
  2751. // coordinates beyond the right of the text.
  2752. function posFromMouse(cm, e, liberal, forRect) {
  2753. var display = cm.display
  2754. if (!liberal && e_target(e).getAttribute("cm-not-content") == "true") { return null }
  2755. var x, y, space = display.lineSpace.getBoundingClientRect()
  2756. // Fails unpredictably on IE[67] when mouse is dragged around quickly.
  2757. try { x = e.clientX - space.left; y = e.clientY - space.top }
  2758. catch (e) { return null }
  2759. var coords = coordsChar(cm, x, y), line
  2760. if (forRect && coords.xRel == 1 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) {
  2761. var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length
  2762. coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff))
  2763. }
  2764. return coords
  2765. }
  2766. // Find the view element corresponding to a given line. Return null
  2767. // when the line isn't visible.
  2768. function findViewIndex(cm, n) {
  2769. if (n >= cm.display.viewTo) { return null }
  2770. n -= cm.display.viewFrom
  2771. if (n < 0) { return null }
  2772. var view = cm.display.view
  2773. for (var i = 0; i < view.length; i++) {
  2774. n -= view[i].size
  2775. if (n < 0) { return i }
  2776. }
  2777. }
  2778. function updateSelection(cm) {
  2779. cm.display.input.showSelection(cm.display.input.prepareSelection())
  2780. }
  2781. function prepareSelection(cm, primary) {
  2782. if ( primary === void 0 ) primary = true;
  2783. var doc = cm.doc, result = {}
  2784. var curFragment = result.cursors = document.createDocumentFragment()
  2785. var selFragment = result.selection = document.createDocumentFragment()
  2786. for (var i = 0; i < doc.sel.ranges.length; i++) {
  2787. if (!primary && i == doc.sel.primIndex) { continue }
  2788. var range = doc.sel.ranges[i]
  2789. if (range.from().line >= cm.display.viewTo || range.to().line < cm.display.viewFrom) { continue }
  2790. var collapsed = range.empty()
  2791. if (collapsed || cm.options.showCursorWhenSelecting)
  2792. { drawSelectionCursor(cm, range.head, curFragment) }
  2793. if (!collapsed)
  2794. { drawSelectionRange(cm, range, selFragment) }
  2795. }
  2796. return result
  2797. }
  2798. // Draws a cursor for the given range
  2799. function drawSelectionCursor(cm, head, output) {
  2800. var pos = cursorCoords(cm, head, "div", null, null, !cm.options.singleCursorHeightPerLine)
  2801. var cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor"))
  2802. cursor.style.left = pos.left + "px"
  2803. cursor.style.top = pos.top + "px"
  2804. cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px"
  2805. if (pos.other) {
  2806. // Secondary cursor, shown when on a 'jump' in bi-directional text
  2807. var otherCursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor"))
  2808. otherCursor.style.display = ""
  2809. otherCursor.style.left = pos.other.left + "px"
  2810. otherCursor.style.top = pos.other.top + "px"
  2811. otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px"
  2812. }
  2813. }
  2814. function cmpCoords(a, b) { return a.top - b.top || a.left - b.left }
  2815. // Draws the given range as a highlighted selection
  2816. function drawSelectionRange(cm, range, output) {
  2817. var display = cm.display, doc = cm.doc
  2818. var fragment = document.createDocumentFragment()
  2819. var padding = paddingH(cm.display), leftSide = padding.left
  2820. var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right
  2821. var docLTR = doc.direction == "ltr"
  2822. function add(left, top, width, bottom) {
  2823. if (top < 0) { top = 0 }
  2824. top = Math.round(top)
  2825. bottom = Math.round(bottom)
  2826. 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")))
  2827. }
  2828. function drawForLine(line, fromArg, toArg) {
  2829. var lineObj = getLine(doc, line)
  2830. var lineLen = lineObj.text.length
  2831. var start, end
  2832. function coords(ch, bias) {
  2833. return charCoords(cm, Pos(line, ch), "div", lineObj, bias)
  2834. }
  2835. function wrapX(pos, dir, side) {
  2836. var extent = wrappedLineExtentChar(cm, lineObj, null, pos)
  2837. var prop = (dir == "ltr") == (side == "after") ? "left" : "right"
  2838. var ch = side == "after" ? extent.begin : extent.end - (/\s/.test(lineObj.text.charAt(extent.end - 1)) ? 2 : 1)
  2839. return coords(ch, prop)[prop]
  2840. }
  2841. var order = getOrder(lineObj, doc.direction)
  2842. iterateBidiSections(order, fromArg || 0, toArg == null ? lineLen : toArg, function (from, to, dir, i) {
  2843. var ltr = dir == "ltr"
  2844. var fromPos = coords(from, ltr ? "left" : "right")
  2845. var toPos = coords(to - 1, ltr ? "right" : "left")
  2846. var openStart = fromArg == null && from == 0, openEnd = toArg == null && to == lineLen
  2847. var first = i == 0, last = !order || i == order.length - 1
  2848. if (toPos.top - fromPos.top <= 3) { // Single line
  2849. var openLeft = (docLTR ? openStart : openEnd) && first
  2850. var openRight = (docLTR ? openEnd : openStart) && last
  2851. var left = openLeft ? leftSide : (ltr ? fromPos : toPos).left
  2852. var right = openRight ? rightSide : (ltr ? toPos : fromPos).right
  2853. add(left, fromPos.top, right - left, fromPos.bottom)
  2854. } else { // Multiple lines
  2855. var topLeft, topRight, botLeft, botRight
  2856. if (ltr) {
  2857. topLeft = docLTR && openStart && first ? leftSide : fromPos.left
  2858. topRight = docLTR ? rightSide : wrapX(from, dir, "before")
  2859. botLeft = docLTR ? leftSide : wrapX(to, dir, "after")
  2860. botRight = docLTR && openEnd && last ? rightSide : toPos.right
  2861. } else {
  2862. topLeft = !docLTR ? leftSide : wrapX(from, dir, "before")
  2863. topRight = !docLTR && openStart && first ? rightSide : fromPos.right
  2864. botLeft = !docLTR && openEnd && last ? leftSide : toPos.left
  2865. botRight = !docLTR ? rightSide : wrapX(to, dir, "after")
  2866. }
  2867. add(topLeft, fromPos.top, topRight - topLeft, fromPos.bottom)
  2868. if (fromPos.bottom < toPos.top) { add(leftSide, fromPos.bottom, null, toPos.top) }
  2869. add(botLeft, toPos.top, botRight - botLeft, toPos.bottom)
  2870. }
  2871. if (!start || cmpCoords(fromPos, start) < 0) { start = fromPos }
  2872. if (cmpCoords(toPos, start) < 0) { start = toPos }
  2873. if (!end || cmpCoords(fromPos, end) < 0) { end = fromPos }
  2874. if (cmpCoords(toPos, end) < 0) { end = toPos }
  2875. })
  2876. return {start: start, end: end}
  2877. }
  2878. var sFrom = range.from(), sTo = range.to()
  2879. if (sFrom.line == sTo.line) {
  2880. drawForLine(sFrom.line, sFrom.ch, sTo.ch)
  2881. } else {
  2882. var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line)
  2883. var singleVLine = visualLine(fromLine) == visualLine(toLine)
  2884. var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end
  2885. var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start
  2886. if (singleVLine) {
  2887. if (leftEnd.top < rightStart.top - 2) {
  2888. add(leftEnd.right, leftEnd.top, null, leftEnd.bottom)
  2889. add(leftSide, rightStart.top, rightStart.left, rightStart.bottom)
  2890. } else {
  2891. add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom)
  2892. }
  2893. }
  2894. if (leftEnd.bottom < rightStart.top)
  2895. { add(leftSide, leftEnd.bottom, null, rightStart.top) }
  2896. }
  2897. output.appendChild(fragment)
  2898. }
  2899. // Cursor-blinking
  2900. function restartBlink(cm) {
  2901. if (!cm.state.focused) { return }
  2902. var display = cm.display
  2903. clearInterval(display.blinker)
  2904. var on = true
  2905. display.cursorDiv.style.visibility = ""
  2906. if (cm.options.cursorBlinkRate > 0)
  2907. { display.blinker = setInterval(function () { return display.cursorDiv.style.visibility = (on = !on) ? "" : "hidden"; },
  2908. cm.options.cursorBlinkRate) }
  2909. else if (cm.options.cursorBlinkRate < 0)
  2910. { display.cursorDiv.style.visibility = "hidden" }
  2911. }
  2912. function ensureFocus(cm) {
  2913. if (!cm.state.focused) { cm.display.input.focus(); onFocus(cm) }
  2914. }
  2915. function delayBlurEvent(cm) {
  2916. cm.state.delayingBlurEvent = true
  2917. setTimeout(function () { if (cm.state.delayingBlurEvent) {
  2918. cm.state.delayingBlurEvent = false
  2919. onBlur(cm)
  2920. } }, 100)
  2921. }
  2922. function onFocus(cm, e) {
  2923. if (cm.state.delayingBlurEvent) { cm.state.delayingBlurEvent = false }
  2924. if (cm.options.readOnly == "nocursor") { return }
  2925. if (!cm.state.focused) {
  2926. signal(cm, "focus", cm, e)
  2927. cm.state.focused = true
  2928. addClass(cm.display.wrapper, "CodeMirror-focused")
  2929. // This test prevents this from firing when a context
  2930. // menu is closed (since the input reset would kill the
  2931. // select-all detection hack)
  2932. if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) {
  2933. cm.display.input.reset()
  2934. if (webkit) { setTimeout(function () { return cm.display.input.reset(true); }, 20) } // Issue #1730
  2935. }
  2936. cm.display.input.receivedFocus()
  2937. }
  2938. restartBlink(cm)
  2939. }
  2940. function onBlur(cm, e) {
  2941. if (cm.state.delayingBlurEvent) { return }
  2942. if (cm.state.focused) {
  2943. signal(cm, "blur", cm, e)
  2944. cm.state.focused = false
  2945. rmClass(cm.display.wrapper, "CodeMirror-focused")
  2946. }
  2947. clearInterval(cm.display.blinker)
  2948. setTimeout(function () { if (!cm.state.focused) { cm.display.shift = false } }, 150)
  2949. }
  2950. // Read the actual heights of the rendered lines, and update their
  2951. // stored heights to match.
  2952. function updateHeightsInViewport(cm) {
  2953. var display = cm.display
  2954. var prevBottom = display.lineDiv.offsetTop
  2955. for (var i = 0; i < display.view.length; i++) {
  2956. var cur = display.view[i], height = (void 0)
  2957. if (cur.hidden) { continue }
  2958. if (ie && ie_version < 8) {
  2959. var bot = cur.node.offsetTop + cur.node.offsetHeight
  2960. height = bot - prevBottom
  2961. prevBottom = bot
  2962. } else {
  2963. var box = cur.node.getBoundingClientRect()
  2964. height = box.bottom - box.top
  2965. }
  2966. var diff = cur.line.height - height
  2967. if (height < 2) { height = textHeight(display) }
  2968. if (diff > .005 || diff < -.005) {
  2969. updateLineHeight(cur.line, height)
  2970. updateWidgetHeight(cur.line)
  2971. if (cur.rest) { for (var j = 0; j < cur.rest.length; j++)
  2972. { updateWidgetHeight(cur.rest[j]) } }
  2973. }
  2974. }
  2975. }
  2976. // Read and store the height of line widgets associated with the
  2977. // given line.
  2978. function updateWidgetHeight(line) {
  2979. if (line.widgets) { for (var i = 0; i < line.widgets.length; ++i) {
  2980. var w = line.widgets[i], parent = w.node.parentNode
  2981. if (parent) { w.height = parent.offsetHeight }
  2982. } }
  2983. }
  2984. // Compute the lines that are visible in a given viewport (defaults
  2985. // the the current scroll position). viewport may contain top,
  2986. // height, and ensure (see op.scrollToPos) properties.
  2987. function visibleLines(display, doc, viewport) {
  2988. var top = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop
  2989. top = Math.floor(top - paddingTop(display))
  2990. var bottom = viewport && viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight
  2991. var from = lineAtHeight(doc, top), to = lineAtHeight(doc, bottom)
  2992. // Ensure is a {from: {line, ch}, to: {line, ch}} object, and
  2993. // forces those lines into the viewport (if possible).
  2994. if (viewport && viewport.ensure) {
  2995. var ensureFrom = viewport.ensure.from.line, ensureTo = viewport.ensure.to.line
  2996. if (ensureFrom < from) {
  2997. from = ensureFrom
  2998. to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight)
  2999. } else if (Math.min(ensureTo, doc.lastLine()) >= to) {
  3000. from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight)
  3001. to = ensureTo
  3002. }
  3003. }
  3004. return {from: from, to: Math.max(to, from + 1)}
  3005. }
  3006. // Re-align line numbers and gutter marks to compensate for
  3007. // horizontal scrolling.
  3008. function alignHorizontally(cm) {
  3009. var display = cm.display, view = display.view
  3010. if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) { return }
  3011. var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft
  3012. var gutterW = display.gutters.offsetWidth, left = comp + "px"
  3013. for (var i = 0; i < view.length; i++) { if (!view[i].hidden) {
  3014. if (cm.options.fixedGutter) {
  3015. if (view[i].gutter)
  3016. { view[i].gutter.style.left = left }
  3017. if (view[i].gutterBackground)
  3018. { view[i].gutterBackground.style.left = left }
  3019. }
  3020. var align = view[i].alignable
  3021. if (align) { for (var j = 0; j < align.length; j++)
  3022. { align[j].style.left = left } }
  3023. } }
  3024. if (cm.options.fixedGutter)
  3025. { display.gutters.style.left = (comp + gutterW) + "px" }
  3026. }
  3027. // Used to ensure that the line number gutter is still the right
  3028. // size for the current document size. Returns true when an update
  3029. // is needed.
  3030. function maybeUpdateLineNumberWidth(cm) {
  3031. if (!cm.options.lineNumbers) { return false }
  3032. var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display
  3033. if (last.length != display.lineNumChars) {
  3034. var test = display.measure.appendChild(elt("div", [elt("div", last)],
  3035. "CodeMirror-linenumber CodeMirror-gutter-elt"))
  3036. var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW
  3037. display.lineGutter.style.width = ""
  3038. display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding) + 1
  3039. display.lineNumWidth = display.lineNumInnerWidth + padding
  3040. display.lineNumChars = display.lineNumInnerWidth ? last.length : -1
  3041. display.lineGutter.style.width = display.lineNumWidth + "px"
  3042. updateGutterSpace(cm)
  3043. return true
  3044. }
  3045. return false
  3046. }
  3047. // SCROLLING THINGS INTO VIEW
  3048. // If an editor sits on the top or bottom of the window, partially
  3049. // scrolled out of view, this ensures that the cursor is visible.
  3050. function maybeScrollWindow(cm, rect) {
  3051. if (signalDOMEvent(cm, "scrollCursorIntoView")) { return }
  3052. var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null
  3053. if (rect.top + box.top < 0) { doScroll = true }
  3054. else if (rect.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) { doScroll = false }
  3055. if (doScroll != null && !phantom) {
  3056. 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;"))
  3057. cm.display.lineSpace.appendChild(scrollNode)
  3058. scrollNode.scrollIntoView(doScroll)
  3059. cm.display.lineSpace.removeChild(scrollNode)
  3060. }
  3061. }
  3062. // Scroll a given position into view (immediately), verifying that
  3063. // it actually became visible (as line heights are accurately
  3064. // measured, the position of something may 'drift' during drawing).
  3065. function scrollPosIntoView(cm, pos, end, margin) {
  3066. if (margin == null) { margin = 0 }
  3067. var rect
  3068. if (!cm.options.lineWrapping && pos == end) {
  3069. // Set pos and end to the cursor positions around the character pos sticks to
  3070. // If pos.sticky == "before", that is around pos.ch - 1, otherwise around pos.ch
  3071. // If pos == Pos(_, 0, "before"), pos and end are unchanged
  3072. pos = pos.ch ? Pos(pos.line, pos.sticky == "before" ? pos.ch - 1 : pos.ch, "after") : pos
  3073. end = pos.sticky == "before" ? Pos(pos.line, pos.ch + 1, "before") : pos
  3074. }
  3075. for (var limit = 0; limit < 5; limit++) {
  3076. var changed = false
  3077. var coords = cursorCoords(cm, pos)
  3078. var endCoords = !end || end == pos ? coords : cursorCoords(cm, end)
  3079. rect = {left: Math.min(coords.left, endCoords.left),
  3080. top: Math.min(coords.top, endCoords.top) - margin,
  3081. right: Math.max(coords.left, endCoords.left),
  3082. bottom: Math.max(coords.bottom, endCoords.bottom) + margin}
  3083. var scrollPos = calculateScrollPos(cm, rect)
  3084. var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft
  3085. if (scrollPos.scrollTop != null) {
  3086. updateScrollTop(cm, scrollPos.scrollTop)
  3087. if (Math.abs(cm.doc.scrollTop - startTop) > 1) { changed = true }
  3088. }
  3089. if (scrollPos.scrollLeft != null) {
  3090. setScrollLeft(cm, scrollPos.scrollLeft)
  3091. if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) { changed = true }
  3092. }
  3093. if (!changed) { break }
  3094. }
  3095. return rect
  3096. }
  3097. // Scroll a given set of coordinates into view (immediately).
  3098. function scrollIntoView(cm, rect) {
  3099. var scrollPos = calculateScrollPos(cm, rect)
  3100. if (scrollPos.scrollTop != null) { updateScrollTop(cm, scrollPos.scrollTop) }
  3101. if (scrollPos.scrollLeft != null) { setScrollLeft(cm, scrollPos.scrollLeft) }
  3102. }
  3103. // Calculate a new scroll position needed to scroll the given
  3104. // rectangle into view. Returns an object with scrollTop and
  3105. // scrollLeft properties. When these are undefined, the
  3106. // vertical/horizontal position does not need to be adjusted.
  3107. function calculateScrollPos(cm, rect) {
  3108. var display = cm.display, snapMargin = textHeight(cm.display)
  3109. if (rect.top < 0) { rect.top = 0 }
  3110. var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop
  3111. var screen = displayHeight(cm), result = {}
  3112. if (rect.bottom - rect.top > screen) { rect.bottom = rect.top + screen }
  3113. var docBottom = cm.doc.height + paddingVert(display)
  3114. var atTop = rect.top < snapMargin, atBottom = rect.bottom > docBottom - snapMargin
  3115. if (rect.top < screentop) {
  3116. result.scrollTop = atTop ? 0 : rect.top
  3117. } else if (rect.bottom > screentop + screen) {
  3118. var newTop = Math.min(rect.top, (atBottom ? docBottom : rect.bottom) - screen)
  3119. if (newTop != screentop) { result.scrollTop = newTop }
  3120. }
  3121. var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft
  3122. var screenw = displayWidth(cm) - (cm.options.fixedGutter ? display.gutters.offsetWidth : 0)
  3123. var tooWide = rect.right - rect.left > screenw
  3124. if (tooWide) { rect.right = rect.left + screenw }
  3125. if (rect.left < 10)
  3126. { result.scrollLeft = 0 }
  3127. else if (rect.left < screenleft)
  3128. { result.scrollLeft = Math.max(0, rect.left - (tooWide ? 0 : 10)) }
  3129. else if (rect.right > screenw + screenleft - 3)
  3130. { result.scrollLeft = rect.right + (tooWide ? 0 : 10) - screenw }
  3131. return result
  3132. }
  3133. // Store a relative adjustment to the scroll position in the current
  3134. // operation (to be applied when the operation finishes).
  3135. function addToScrollTop(cm, top) {
  3136. if (top == null) { return }
  3137. resolveScrollToPos(cm)
  3138. cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top
  3139. }
  3140. // Make sure that at the end of the operation the current cursor is
  3141. // shown.
  3142. function ensureCursorVisible(cm) {
  3143. resolveScrollToPos(cm)
  3144. var cur = cm.getCursor()
  3145. cm.curOp.scrollToPos = {from: cur, to: cur, margin: cm.options.cursorScrollMargin}
  3146. }
  3147. function scrollToCoords(cm, x, y) {
  3148. if (x != null || y != null) { resolveScrollToPos(cm) }
  3149. if (x != null) { cm.curOp.scrollLeft = x }
  3150. if (y != null) { cm.curOp.scrollTop = y }
  3151. }
  3152. function scrollToRange(cm, range) {
  3153. resolveScrollToPos(cm)
  3154. cm.curOp.scrollToPos = range
  3155. }
  3156. // When an operation has its scrollToPos property set, and another
  3157. // scroll action is applied before the end of the operation, this
  3158. // 'simulates' scrolling that position into view in a cheap way, so
  3159. // that the effect of intermediate scroll commands is not ignored.
  3160. function resolveScrollToPos(cm) {
  3161. var range = cm.curOp.scrollToPos
  3162. if (range) {
  3163. cm.curOp.scrollToPos = null
  3164. var from = estimateCoords(cm, range.from), to = estimateCoords(cm, range.to)
  3165. scrollToCoordsRange(cm, from, to, range.margin)
  3166. }
  3167. }
  3168. function scrollToCoordsRange(cm, from, to, margin) {
  3169. var sPos = calculateScrollPos(cm, {
  3170. left: Math.min(from.left, to.left),
  3171. top: Math.min(from.top, to.top) - margin,
  3172. right: Math.max(from.right, to.right),
  3173. bottom: Math.max(from.bottom, to.bottom) + margin
  3174. })
  3175. scrollToCoords(cm, sPos.scrollLeft, sPos.scrollTop)
  3176. }
  3177. // Sync the scrollable area and scrollbars, ensure the viewport
  3178. // covers the visible area.
  3179. function updateScrollTop(cm, val) {
  3180. if (Math.abs(cm.doc.scrollTop - val) < 2) { return }
  3181. if (!gecko) { updateDisplaySimple(cm, {top: val}) }
  3182. setScrollTop(cm, val, true)
  3183. if (gecko) { updateDisplaySimple(cm) }
  3184. startWorker(cm, 100)
  3185. }
  3186. function setScrollTop(cm, val, forceScroll) {
  3187. val = Math.min(cm.display.scroller.scrollHeight - cm.display.scroller.clientHeight, val)
  3188. if (cm.display.scroller.scrollTop == val && !forceScroll) { return }
  3189. cm.doc.scrollTop = val
  3190. cm.display.scrollbars.setScrollTop(val)
  3191. if (cm.display.scroller.scrollTop != val) { cm.display.scroller.scrollTop = val }
  3192. }
  3193. // Sync scroller and scrollbar, ensure the gutter elements are
  3194. // aligned.
  3195. function setScrollLeft(cm, val, isScroller, forceScroll) {
  3196. val = Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth)
  3197. if ((isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) && !forceScroll) { return }
  3198. cm.doc.scrollLeft = val
  3199. alignHorizontally(cm)
  3200. if (cm.display.scroller.scrollLeft != val) { cm.display.scroller.scrollLeft = val }
  3201. cm.display.scrollbars.setScrollLeft(val)
  3202. }
  3203. // SCROLLBARS
  3204. // Prepare DOM reads needed to update the scrollbars. Done in one
  3205. // shot to minimize update/measure roundtrips.
  3206. function measureForScrollbars(cm) {
  3207. var d = cm.display, gutterW = d.gutters.offsetWidth
  3208. var docH = Math.round(cm.doc.height + paddingVert(cm.display))
  3209. return {
  3210. clientHeight: d.scroller.clientHeight,
  3211. viewHeight: d.wrapper.clientHeight,
  3212. scrollWidth: d.scroller.scrollWidth, clientWidth: d.scroller.clientWidth,
  3213. viewWidth: d.wrapper.clientWidth,
  3214. barLeft: cm.options.fixedGutter ? gutterW : 0,
  3215. docHeight: docH,
  3216. scrollHeight: docH + scrollGap(cm) + d.barHeight,
  3217. nativeBarWidth: d.nativeBarWidth,
  3218. gutterWidth: gutterW
  3219. }
  3220. }
  3221. var NativeScrollbars = function(place, scroll, cm) {
  3222. this.cm = cm
  3223. var vert = this.vert = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar")
  3224. var horiz = this.horiz = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar")
  3225. place(vert); place(horiz)
  3226. on(vert, "scroll", function () {
  3227. if (vert.clientHeight) { scroll(vert.scrollTop, "vertical") }
  3228. })
  3229. on(horiz, "scroll", function () {
  3230. if (horiz.clientWidth) { scroll(horiz.scrollLeft, "horizontal") }
  3231. })
  3232. this.checkedZeroWidth = false
  3233. // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8).
  3234. if (ie && ie_version < 8) { this.horiz.style.minHeight = this.vert.style.minWidth = "18px" }
  3235. };
  3236. NativeScrollbars.prototype.update = function (measure) {
  3237. var needsH = measure.scrollWidth > measure.clientWidth + 1
  3238. var needsV = measure.scrollHeight > measure.clientHeight + 1
  3239. var sWidth = measure.nativeBarWidth
  3240. if (needsV) {
  3241. this.vert.style.display = "block"
  3242. this.vert.style.bottom = needsH ? sWidth + "px" : "0"
  3243. var totalHeight = measure.viewHeight - (needsH ? sWidth : 0)
  3244. // A bug in IE8 can cause this value to be negative, so guard it.
  3245. this.vert.firstChild.style.height =
  3246. Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + "px"
  3247. } else {
  3248. this.vert.style.display = ""
  3249. this.vert.firstChild.style.height = "0"
  3250. }
  3251. if (needsH) {
  3252. this.horiz.style.display = "block"
  3253. this.horiz.style.right = needsV ? sWidth + "px" : "0"
  3254. this.horiz.style.left = measure.barLeft + "px"
  3255. var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0)
  3256. this.horiz.firstChild.style.width =
  3257. Math.max(0, measure.scrollWidth - measure.clientWidth + totalWidth) + "px"
  3258. } else {
  3259. this.horiz.style.display = ""
  3260. this.horiz.firstChild.style.width = "0"
  3261. }
  3262. if (!this.checkedZeroWidth && measure.clientHeight > 0) {
  3263. if (sWidth == 0) { this.zeroWidthHack() }
  3264. this.checkedZeroWidth = true
  3265. }
  3266. return {right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0}
  3267. };
  3268. NativeScrollbars.prototype.setScrollLeft = function (pos) {
  3269. if (this.horiz.scrollLeft != pos) { this.horiz.scrollLeft = pos }
  3270. if (this.disableHoriz) { this.enableZeroWidthBar(this.horiz, this.disableHoriz, "horiz") }
  3271. };
  3272. NativeScrollbars.prototype.setScrollTop = function (pos) {
  3273. if (this.vert.scrollTop != pos) { this.vert.scrollTop = pos }
  3274. if (this.disableVert) { this.enableZeroWidthBar(this.vert, this.disableVert, "vert") }
  3275. };
  3276. NativeScrollbars.prototype.zeroWidthHack = function () {
  3277. var w = mac && !mac_geMountainLion ? "12px" : "18px"
  3278. this.horiz.style.height = this.vert.style.width = w
  3279. this.horiz.style.pointerEvents = this.vert.style.pointerEvents = "none"
  3280. this.disableHoriz = new Delayed
  3281. this.disableVert = new Delayed
  3282. };
  3283. NativeScrollbars.prototype.enableZeroWidthBar = function (bar, delay, type) {
  3284. bar.style.pointerEvents = "auto"
  3285. function maybeDisable() {
  3286. // To find out whether the scrollbar is still visible, we
  3287. // check whether the element under the pixel in the bottom
  3288. // right corner of the scrollbar box is the scrollbar box
  3289. // itself (when the bar is still visible) or its filler child
  3290. // (when the bar is hidden). If it is still visible, we keep
  3291. // it enabled, if it's hidden, we disable pointer events.
  3292. var box = bar.getBoundingClientRect()
  3293. var elt = type == "vert" ? document.elementFromPoint(box.right - 1, (box.top + box.bottom) / 2)
  3294. : document.elementFromPoint((box.right + box.left) / 2, box.bottom - 1)
  3295. if (elt != bar) { bar.style.pointerEvents = "none" }
  3296. else { delay.set(1000, maybeDisable) }
  3297. }
  3298. delay.set(1000, maybeDisable)
  3299. };
  3300. NativeScrollbars.prototype.clear = function () {
  3301. var parent = this.horiz.parentNode
  3302. parent.removeChild(this.horiz)
  3303. parent.removeChild(this.vert)
  3304. };
  3305. var NullScrollbars = function () {};
  3306. NullScrollbars.prototype.update = function () { return {bottom: 0, right: 0} };
  3307. NullScrollbars.prototype.setScrollLeft = function () {};
  3308. NullScrollbars.prototype.setScrollTop = function () {};
  3309. NullScrollbars.prototype.clear = function () {};
  3310. function updateScrollbars(cm, measure) {
  3311. if (!measure) { measure = measureForScrollbars(cm) }
  3312. var startWidth = cm.display.barWidth, startHeight = cm.display.barHeight
  3313. updateScrollbarsInner(cm, measure)
  3314. for (var i = 0; i < 4 && startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i++) {
  3315. if (startWidth != cm.display.barWidth && cm.options.lineWrapping)
  3316. { updateHeightsInViewport(cm) }
  3317. updateScrollbarsInner(cm, measureForScrollbars(cm))
  3318. startWidth = cm.display.barWidth; startHeight = cm.display.barHeight
  3319. }
  3320. }
  3321. // Re-synchronize the fake scrollbars with the actual size of the
  3322. // content.
  3323. function updateScrollbarsInner(cm, measure) {
  3324. var d = cm.display
  3325. var sizes = d.scrollbars.update(measure)
  3326. d.sizer.style.paddingRight = (d.barWidth = sizes.right) + "px"
  3327. d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + "px"
  3328. d.heightForcer.style.borderBottom = sizes.bottom + "px solid transparent"
  3329. if (sizes.right && sizes.bottom) {
  3330. d.scrollbarFiller.style.display = "block"
  3331. d.scrollbarFiller.style.height = sizes.bottom + "px"
  3332. d.scrollbarFiller.style.width = sizes.right + "px"
  3333. } else { d.scrollbarFiller.style.display = "" }
  3334. if (sizes.bottom && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) {
  3335. d.gutterFiller.style.display = "block"
  3336. d.gutterFiller.style.height = sizes.bottom + "px"
  3337. d.gutterFiller.style.width = measure.gutterWidth + "px"
  3338. } else { d.gutterFiller.style.display = "" }
  3339. }
  3340. var scrollbarModel = {"native": NativeScrollbars, "null": NullScrollbars}
  3341. function initScrollbars(cm) {
  3342. if (cm.display.scrollbars) {
  3343. cm.display.scrollbars.clear()
  3344. if (cm.display.scrollbars.addClass)
  3345. { rmClass(cm.display.wrapper, cm.display.scrollbars.addClass) }
  3346. }
  3347. cm.display.scrollbars = new scrollbarModel[cm.options.scrollbarStyle](function (node) {
  3348. cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller)
  3349. // Prevent clicks in the scrollbars from killing focus
  3350. on(node, "mousedown", function () {
  3351. if (cm.state.focused) { setTimeout(function () { return cm.display.input.focus(); }, 0) }
  3352. })
  3353. node.setAttribute("cm-not-content", "true")
  3354. }, function (pos, axis) {
  3355. if (axis == "horizontal") { setScrollLeft(cm, pos) }
  3356. else { updateScrollTop(cm, pos) }
  3357. }, cm)
  3358. if (cm.display.scrollbars.addClass)
  3359. { addClass(cm.display.wrapper, cm.display.scrollbars.addClass) }
  3360. }
  3361. // Operations are used to wrap a series of changes to the editor
  3362. // state in such a way that each change won't have to update the
  3363. // cursor and display (which would be awkward, slow, and
  3364. // error-prone). Instead, display updates are batched and then all
  3365. // combined and executed at once.
  3366. var nextOpId = 0
  3367. // Start a new operation.
  3368. function startOperation(cm) {
  3369. cm.curOp = {
  3370. cm: cm,
  3371. viewChanged: false, // Flag that indicates that lines might need to be redrawn
  3372. startHeight: cm.doc.height, // Used to detect need to update scrollbar
  3373. forceUpdate: false, // Used to force a redraw
  3374. updateInput: null, // Whether to reset the input textarea
  3375. typing: false, // Whether this reset should be careful to leave existing text (for compositing)
  3376. changeObjs: null, // Accumulated changes, for firing change events
  3377. cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on
  3378. cursorActivityCalled: 0, // Tracks which cursorActivity handlers have been called already
  3379. selectionChanged: false, // Whether the selection needs to be redrawn
  3380. updateMaxLine: false, // Set when the widest line needs to be determined anew
  3381. scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet
  3382. scrollToPos: null, // Used to scroll to a specific position
  3383. focus: false,
  3384. id: ++nextOpId // Unique ID
  3385. }
  3386. pushOperation(cm.curOp)
  3387. }
  3388. // Finish an operation, updating the display and signalling delayed events
  3389. function endOperation(cm) {
  3390. var op = cm.curOp
  3391. finishOperation(op, function (group) {
  3392. for (var i = 0; i < group.ops.length; i++)
  3393. { group.ops[i].cm.curOp = null }
  3394. endOperations(group)
  3395. })
  3396. }
  3397. // The DOM updates done when an operation finishes are batched so
  3398. // that the minimum number of relayouts are required.
  3399. function endOperations(group) {
  3400. var ops = group.ops
  3401. for (var i = 0; i < ops.length; i++) // Read DOM
  3402. { endOperation_R1(ops[i]) }
  3403. for (var i$1 = 0; i$1 < ops.length; i$1++) // Write DOM (maybe)
  3404. { endOperation_W1(ops[i$1]) }
  3405. for (var i$2 = 0; i$2 < ops.length; i$2++) // Read DOM
  3406. { endOperation_R2(ops[i$2]) }
  3407. for (var i$3 = 0; i$3 < ops.length; i$3++) // Write DOM (maybe)
  3408. { endOperation_W2(ops[i$3]) }
  3409. for (var i$4 = 0; i$4 < ops.length; i$4++) // Read DOM
  3410. { endOperation_finish(ops[i$4]) }
  3411. }
  3412. function endOperation_R1(op) {
  3413. var cm = op.cm, display = cm.display
  3414. maybeClipScrollbars(cm)
  3415. if (op.updateMaxLine) { findMaxLine(cm) }
  3416. op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null ||
  3417. op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom ||
  3418. op.scrollToPos.to.line >= display.viewTo) ||
  3419. display.maxLineChanged && cm.options.lineWrapping
  3420. op.update = op.mustUpdate &&
  3421. new DisplayUpdate(cm, op.mustUpdate && {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate)
  3422. }
  3423. function endOperation_W1(op) {
  3424. op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update)
  3425. }
  3426. function endOperation_R2(op) {
  3427. var cm = op.cm, display = cm.display
  3428. if (op.updatedDisplay) { updateHeightsInViewport(cm) }
  3429. op.barMeasure = measureForScrollbars(cm)
  3430. // If the max line changed since it was last measured, measure it,
  3431. // and ensure the document's width matches it.
  3432. // updateDisplay_W2 will use these properties to do the actual resizing
  3433. if (display.maxLineChanged && !cm.options.lineWrapping) {
  3434. op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3
  3435. cm.display.sizerWidth = op.adjustWidthTo
  3436. op.barMeasure.scrollWidth =
  3437. Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth)
  3438. op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm))
  3439. }
  3440. if (op.updatedDisplay || op.selectionChanged)
  3441. { op.preparedSelection = display.input.prepareSelection() }
  3442. }
  3443. function endOperation_W2(op) {
  3444. var cm = op.cm
  3445. if (op.adjustWidthTo != null) {
  3446. cm.display.sizer.style.minWidth = op.adjustWidthTo + "px"
  3447. if (op.maxScrollLeft < cm.doc.scrollLeft)
  3448. { setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true) }
  3449. cm.display.maxLineChanged = false
  3450. }
  3451. var takeFocus = op.focus && op.focus == activeElt()
  3452. if (op.preparedSelection)
  3453. { cm.display.input.showSelection(op.preparedSelection, takeFocus) }
  3454. if (op.updatedDisplay || op.startHeight != cm.doc.height)
  3455. { updateScrollbars(cm, op.barMeasure) }
  3456. if (op.updatedDisplay)
  3457. { setDocumentHeight(cm, op.barMeasure) }
  3458. if (op.selectionChanged) { restartBlink(cm) }
  3459. if (cm.state.focused && op.updateInput)
  3460. { cm.display.input.reset(op.typing) }
  3461. if (takeFocus) { ensureFocus(op.cm) }
  3462. }
  3463. function endOperation_finish(op) {
  3464. var cm = op.cm, display = cm.display, doc = cm.doc
  3465. if (op.updatedDisplay) { postUpdateDisplay(cm, op.update) }
  3466. // Abort mouse wheel delta measurement, when scrolling explicitly
  3467. if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos))
  3468. { display.wheelStartX = display.wheelStartY = null }
  3469. // Propagate the scroll position to the actual DOM scroller
  3470. if (op.scrollTop != null) { setScrollTop(cm, op.scrollTop, op.forceScroll) }
  3471. if (op.scrollLeft != null) { setScrollLeft(cm, op.scrollLeft, true, true) }
  3472. // If we need to scroll a specific position into view, do so.
  3473. if (op.scrollToPos) {
  3474. var rect = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from),
  3475. clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin)
  3476. maybeScrollWindow(cm, rect)
  3477. }
  3478. // Fire events for markers that are hidden/unidden by editing or
  3479. // undoing
  3480. var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers
  3481. if (hidden) { for (var i = 0; i < hidden.length; ++i)
  3482. { if (!hidden[i].lines.length) { signal(hidden[i], "hide") } } }
  3483. if (unhidden) { for (var i$1 = 0; i$1 < unhidden.length; ++i$1)
  3484. { if (unhidden[i$1].lines.length) { signal(unhidden[i$1], "unhide") } } }
  3485. if (display.wrapper.offsetHeight)
  3486. { doc.scrollTop = cm.display.scroller.scrollTop }
  3487. // Fire change events, and delayed event handlers
  3488. if (op.changeObjs)
  3489. { signal(cm, "changes", cm, op.changeObjs) }
  3490. if (op.update)
  3491. { op.update.finish() }
  3492. }
  3493. // Run the given function in an operation
  3494. function runInOp(cm, f) {
  3495. if (cm.curOp) { return f() }
  3496. startOperation(cm)
  3497. try { return f() }
  3498. finally { endOperation(cm) }
  3499. }
  3500. // Wraps a function in an operation. Returns the wrapped function.
  3501. function operation(cm, f) {
  3502. return function() {
  3503. if (cm.curOp) { return f.apply(cm, arguments) }
  3504. startOperation(cm)
  3505. try { return f.apply(cm, arguments) }
  3506. finally { endOperation(cm) }
  3507. }
  3508. }
  3509. // Used to add methods to editor and doc instances, wrapping them in
  3510. // operations.
  3511. function methodOp(f) {
  3512. return function() {
  3513. if (this.curOp) { return f.apply(this, arguments) }
  3514. startOperation(this)
  3515. try { return f.apply(this, arguments) }
  3516. finally { endOperation(this) }
  3517. }
  3518. }
  3519. function docMethodOp(f) {
  3520. return function() {
  3521. var cm = this.cm
  3522. if (!cm || cm.curOp) { return f.apply(this, arguments) }
  3523. startOperation(cm)
  3524. try { return f.apply(this, arguments) }
  3525. finally { endOperation(cm) }
  3526. }
  3527. }
  3528. // Updates the display.view data structure for a given change to the
  3529. // document. From and to are in pre-change coordinates. Lendiff is
  3530. // the amount of lines added or subtracted by the change. This is
  3531. // used for changes that span multiple lines, or change the way
  3532. // lines are divided into visual lines. regLineChange (below)
  3533. // registers single-line changes.
  3534. function regChange(cm, from, to, lendiff) {
  3535. if (from == null) { from = cm.doc.first }
  3536. if (to == null) { to = cm.doc.first + cm.doc.size }
  3537. if (!lendiff) { lendiff = 0 }
  3538. var display = cm.display
  3539. if (lendiff && to < display.viewTo &&
  3540. (display.updateLineNumbers == null || display.updateLineNumbers > from))
  3541. { display.updateLineNumbers = from }
  3542. cm.curOp.viewChanged = true
  3543. if (from >= display.viewTo) { // Change after
  3544. if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo)
  3545. { resetView(cm) }
  3546. } else if (to <= display.viewFrom) { // Change before
  3547. if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) {
  3548. resetView(cm)
  3549. } else {
  3550. display.viewFrom += lendiff
  3551. display.viewTo += lendiff
  3552. }
  3553. } else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap
  3554. resetView(cm)
  3555. } else if (from <= display.viewFrom) { // Top overlap
  3556. var cut = viewCuttingPoint(cm, to, to + lendiff, 1)
  3557. if (cut) {
  3558. display.view = display.view.slice(cut.index)
  3559. display.viewFrom = cut.lineN
  3560. display.viewTo += lendiff
  3561. } else {
  3562. resetView(cm)
  3563. }
  3564. } else if (to >= display.viewTo) { // Bottom overlap
  3565. var cut$1 = viewCuttingPoint(cm, from, from, -1)
  3566. if (cut$1) {
  3567. display.view = display.view.slice(0, cut$1.index)
  3568. display.viewTo = cut$1.lineN
  3569. } else {
  3570. resetView(cm)
  3571. }
  3572. } else { // Gap in the middle
  3573. var cutTop = viewCuttingPoint(cm, from, from, -1)
  3574. var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1)
  3575. if (cutTop && cutBot) {
  3576. display.view = display.view.slice(0, cutTop.index)
  3577. .concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN))
  3578. .concat(display.view.slice(cutBot.index))
  3579. display.viewTo += lendiff
  3580. } else {
  3581. resetView(cm)
  3582. }
  3583. }
  3584. var ext = display.externalMeasured
  3585. if (ext) {
  3586. if (to < ext.lineN)
  3587. { ext.lineN += lendiff }
  3588. else if (from < ext.lineN + ext.size)
  3589. { display.externalMeasured = null }
  3590. }
  3591. }
  3592. // Register a change to a single line. Type must be one of "text",
  3593. // "gutter", "class", "widget"
  3594. function regLineChange(cm, line, type) {
  3595. cm.curOp.viewChanged = true
  3596. var display = cm.display, ext = cm.display.externalMeasured
  3597. if (ext && line >= ext.lineN && line < ext.lineN + ext.size)
  3598. { display.externalMeasured = null }
  3599. if (line < display.viewFrom || line >= display.viewTo) { return }
  3600. var lineView = display.view[findViewIndex(cm, line)]
  3601. if (lineView.node == null) { return }
  3602. var arr = lineView.changes || (lineView.changes = [])
  3603. if (indexOf(arr, type) == -1) { arr.push(type) }
  3604. }
  3605. // Clear the view.
  3606. function resetView(cm) {
  3607. cm.display.viewFrom = cm.display.viewTo = cm.doc.first
  3608. cm.display.view = []
  3609. cm.display.viewOffset = 0
  3610. }
  3611. function viewCuttingPoint(cm, oldN, newN, dir) {
  3612. var index = findViewIndex(cm, oldN), diff, view = cm.display.view
  3613. if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size)
  3614. { return {index: index, lineN: newN} }
  3615. var n = cm.display.viewFrom
  3616. for (var i = 0; i < index; i++)
  3617. { n += view[i].size }
  3618. if (n != oldN) {
  3619. if (dir > 0) {
  3620. if (index == view.length - 1) { return null }
  3621. diff = (n + view[index].size) - oldN
  3622. index++
  3623. } else {
  3624. diff = n - oldN
  3625. }
  3626. oldN += diff; newN += diff
  3627. }
  3628. while (visualLineNo(cm.doc, newN) != newN) {
  3629. if (index == (dir < 0 ? 0 : view.length - 1)) { return null }
  3630. newN += dir * view[index - (dir < 0 ? 1 : 0)].size
  3631. index += dir
  3632. }
  3633. return {index: index, lineN: newN}
  3634. }
  3635. // Force the view to cover a given range, adding empty view element
  3636. // or clipping off existing ones as needed.
  3637. function adjustView(cm, from, to) {
  3638. var display = cm.display, view = display.view
  3639. if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) {
  3640. display.view = buildViewArray(cm, from, to)
  3641. display.viewFrom = from
  3642. } else {
  3643. if (display.viewFrom > from)
  3644. { display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view) }
  3645. else if (display.viewFrom < from)
  3646. { display.view = display.view.slice(findViewIndex(cm, from)) }
  3647. display.viewFrom = from
  3648. if (display.viewTo < to)
  3649. { display.view = display.view.concat(buildViewArray(cm, display.viewTo, to)) }
  3650. else if (display.viewTo > to)
  3651. { display.view = display.view.slice(0, findViewIndex(cm, to)) }
  3652. }
  3653. display.viewTo = to
  3654. }
  3655. // Count the number of lines in the view whose DOM representation is
  3656. // out of date (or nonexistent).
  3657. function countDirtyView(cm) {
  3658. var view = cm.display.view, dirty = 0
  3659. for (var i = 0; i < view.length; i++) {
  3660. var lineView = view[i]
  3661. if (!lineView.hidden && (!lineView.node || lineView.changes)) { ++dirty }
  3662. }
  3663. return dirty
  3664. }
  3665. // HIGHLIGHT WORKER
  3666. function startWorker(cm, time) {
  3667. if (cm.doc.highlightFrontier < cm.display.viewTo)
  3668. { cm.state.highlight.set(time, bind(highlightWorker, cm)) }
  3669. }
  3670. function highlightWorker(cm) {
  3671. var doc = cm.doc
  3672. if (doc.highlightFrontier >= cm.display.viewTo) { return }
  3673. var end = +new Date + cm.options.workTime
  3674. var context = getContextBefore(cm, doc.highlightFrontier)
  3675. var changedLines = []
  3676. doc.iter(context.line, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function (line) {
  3677. if (context.line >= cm.display.viewFrom) { // Visible
  3678. var oldStyles = line.styles
  3679. var resetState = line.text.length > cm.options.maxHighlightLength ? copyState(doc.mode, context.state) : null
  3680. var highlighted = highlightLine(cm, line, context, true)
  3681. if (resetState) { context.state = resetState }
  3682. line.styles = highlighted.styles
  3683. var oldCls = line.styleClasses, newCls = highlighted.classes
  3684. if (newCls) { line.styleClasses = newCls }
  3685. else if (oldCls) { line.styleClasses = null }
  3686. var ischange = !oldStyles || oldStyles.length != line.styles.length ||
  3687. oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass)
  3688. for (var i = 0; !ischange && i < oldStyles.length; ++i) { ischange = oldStyles[i] != line.styles[i] }
  3689. if (ischange) { changedLines.push(context.line) }
  3690. line.stateAfter = context.save()
  3691. context.nextLine()
  3692. } else {
  3693. if (line.text.length <= cm.options.maxHighlightLength)
  3694. { processLine(cm, line.text, context) }
  3695. line.stateAfter = context.line % 5 == 0 ? context.save() : null
  3696. context.nextLine()
  3697. }
  3698. if (+new Date > end) {
  3699. startWorker(cm, cm.options.workDelay)
  3700. return true
  3701. }
  3702. })
  3703. doc.highlightFrontier = context.line
  3704. doc.modeFrontier = Math.max(doc.modeFrontier, context.line)
  3705. if (changedLines.length) { runInOp(cm, function () {
  3706. for (var i = 0; i < changedLines.length; i++)
  3707. { regLineChange(cm, changedLines[i], "text") }
  3708. }) }
  3709. }
  3710. // DISPLAY DRAWING
  3711. var DisplayUpdate = function(cm, viewport, force) {
  3712. var display = cm.display
  3713. this.viewport = viewport
  3714. // Store some values that we'll need later (but don't want to force a relayout for)
  3715. this.visible = visibleLines(display, cm.doc, viewport)
  3716. this.editorIsHidden = !display.wrapper.offsetWidth
  3717. this.wrapperHeight = display.wrapper.clientHeight
  3718. this.wrapperWidth = display.wrapper.clientWidth
  3719. this.oldDisplayWidth = displayWidth(cm)
  3720. this.force = force
  3721. this.dims = getDimensions(cm)
  3722. this.events = []
  3723. };
  3724. DisplayUpdate.prototype.signal = function (emitter, type) {
  3725. if (hasHandler(emitter, type))
  3726. { this.events.push(arguments) }
  3727. };
  3728. DisplayUpdate.prototype.finish = function () {
  3729. var this$1 = this;
  3730. for (var i = 0; i < this.events.length; i++)
  3731. { signal.apply(null, this$1.events[i]) }
  3732. };
  3733. function maybeClipScrollbars(cm) {
  3734. var display = cm.display
  3735. if (!display.scrollbarsClipped && display.scroller.offsetWidth) {
  3736. display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth
  3737. display.heightForcer.style.height = scrollGap(cm) + "px"
  3738. display.sizer.style.marginBottom = -display.nativeBarWidth + "px"
  3739. display.sizer.style.borderRightWidth = scrollGap(cm) + "px"
  3740. display.scrollbarsClipped = true
  3741. }
  3742. }
  3743. function selectionSnapshot(cm) {
  3744. if (cm.hasFocus()) { return null }
  3745. var active = activeElt()
  3746. if (!active || !contains(cm.display.lineDiv, active)) { return null }
  3747. var result = {activeElt: active}
  3748. if (window.getSelection) {
  3749. var sel = window.getSelection()
  3750. if (sel.anchorNode && sel.extend && contains(cm.display.lineDiv, sel.anchorNode)) {
  3751. result.anchorNode = sel.anchorNode
  3752. result.anchorOffset = sel.anchorOffset
  3753. result.focusNode = sel.focusNode
  3754. result.focusOffset = sel.focusOffset
  3755. }
  3756. }
  3757. return result
  3758. }
  3759. function restoreSelection(snapshot) {
  3760. if (!snapshot || !snapshot.activeElt || snapshot.activeElt == activeElt()) { return }
  3761. snapshot.activeElt.focus()
  3762. if (snapshot.anchorNode && contains(document.body, snapshot.anchorNode) && contains(document.body, snapshot.focusNode)) {
  3763. var sel = window.getSelection(), range = document.createRange()
  3764. range.setEnd(snapshot.anchorNode, snapshot.anchorOffset)
  3765. range.collapse(false)
  3766. sel.removeAllRanges()
  3767. sel.addRange(range)
  3768. sel.extend(snapshot.focusNode, snapshot.focusOffset)
  3769. }
  3770. }
  3771. // Does the actual updating of the line display. Bails out
  3772. // (returning false) when there is nothing to be done and forced is
  3773. // false.
  3774. function updateDisplayIfNeeded(cm, update) {
  3775. var display = cm.display, doc = cm.doc
  3776. if (update.editorIsHidden) {
  3777. resetView(cm)
  3778. return false
  3779. }
  3780. // Bail out if the visible area is already rendered and nothing changed.
  3781. if (!update.force &&
  3782. update.visible.from >= display.viewFrom && update.visible.to <= display.viewTo &&
  3783. (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) &&
  3784. display.renderedView == display.view && countDirtyView(cm) == 0)
  3785. { return false }
  3786. if (maybeUpdateLineNumberWidth(cm)) {
  3787. resetView(cm)
  3788. update.dims = getDimensions(cm)
  3789. }
  3790. // Compute a suitable new viewport (from & to)
  3791. var end = doc.first + doc.size
  3792. var from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first)
  3793. var to = Math.min(end, update.visible.to + cm.options.viewportMargin)
  3794. if (display.viewFrom < from && from - display.viewFrom < 20) { from = Math.max(doc.first, display.viewFrom) }
  3795. if (display.viewTo > to && display.viewTo - to < 20) { to = Math.min(end, display.viewTo) }
  3796. if (sawCollapsedSpans) {
  3797. from = visualLineNo(cm.doc, from)
  3798. to = visualLineEndNo(cm.doc, to)
  3799. }
  3800. var different = from != display.viewFrom || to != display.viewTo ||
  3801. display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth
  3802. adjustView(cm, from, to)
  3803. display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom))
  3804. // Position the mover div to align with the current scroll position
  3805. cm.display.mover.style.top = display.viewOffset + "px"
  3806. var toUpdate = countDirtyView(cm)
  3807. if (!different && toUpdate == 0 && !update.force && display.renderedView == display.view &&
  3808. (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo))
  3809. { return false }
  3810. // For big changes, we hide the enclosing element during the
  3811. // update, since that speeds up the operations on most browsers.
  3812. var selSnapshot = selectionSnapshot(cm)
  3813. if (toUpdate > 4) { display.lineDiv.style.display = "none" }
  3814. patchDisplay(cm, display.updateLineNumbers, update.dims)
  3815. if (toUpdate > 4) { display.lineDiv.style.display = "" }
  3816. display.renderedView = display.view
  3817. // There might have been a widget with a focused element that got
  3818. // hidden or updated, if so re-focus it.
  3819. restoreSelection(selSnapshot)
  3820. // Prevent selection and cursors from interfering with the scroll
  3821. // width and height.
  3822. removeChildren(display.cursorDiv)
  3823. removeChildren(display.selectionDiv)
  3824. display.gutters.style.height = display.sizer.style.minHeight = 0
  3825. if (different) {
  3826. display.lastWrapHeight = update.wrapperHeight
  3827. display.lastWrapWidth = update.wrapperWidth
  3828. startWorker(cm, 400)
  3829. }
  3830. display.updateLineNumbers = null
  3831. return true
  3832. }
  3833. function postUpdateDisplay(cm, update) {
  3834. var viewport = update.viewport
  3835. for (var first = true;; first = false) {
  3836. if (!first || !cm.options.lineWrapping || update.oldDisplayWidth == displayWidth(cm)) {
  3837. // Clip forced viewport to actual scrollable area.
  3838. if (viewport && viewport.top != null)
  3839. { viewport = {top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top)} }
  3840. // Updated line heights might result in the drawn area not
  3841. // actually covering the viewport. Keep looping until it does.
  3842. update.visible = visibleLines(cm.display, cm.doc, viewport)
  3843. if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo)
  3844. { break }
  3845. }
  3846. if (!updateDisplayIfNeeded(cm, update)) { break }
  3847. updateHeightsInViewport(cm)
  3848. var barMeasure = measureForScrollbars(cm)
  3849. updateSelection(cm)
  3850. updateScrollbars(cm, barMeasure)
  3851. setDocumentHeight(cm, barMeasure)
  3852. update.force = false
  3853. }
  3854. update.signal(cm, "update", cm)
  3855. if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) {
  3856. update.signal(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo)
  3857. cm.display.reportedViewFrom = cm.display.viewFrom; cm.display.reportedViewTo = cm.display.viewTo
  3858. }
  3859. }
  3860. function updateDisplaySimple(cm, viewport) {
  3861. var update = new DisplayUpdate(cm, viewport)
  3862. if (updateDisplayIfNeeded(cm, update)) {
  3863. updateHeightsInViewport(cm)
  3864. postUpdateDisplay(cm, update)
  3865. var barMeasure = measureForScrollbars(cm)
  3866. updateSelection(cm)
  3867. updateScrollbars(cm, barMeasure)
  3868. setDocumentHeight(cm, barMeasure)
  3869. update.finish()
  3870. }
  3871. }
  3872. // Sync the actual display DOM structure with display.view, removing
  3873. // nodes for lines that are no longer in view, and creating the ones
  3874. // that are not there yet, and updating the ones that are out of
  3875. // date.
  3876. function patchDisplay(cm, updateNumbersFrom, dims) {
  3877. var display = cm.display, lineNumbers = cm.options.lineNumbers
  3878. var container = display.lineDiv, cur = container.firstChild
  3879. function rm(node) {
  3880. var next = node.nextSibling
  3881. // Works around a throw-scroll bug in OS X Webkit
  3882. if (webkit && mac && cm.display.currentWheelTarget == node)
  3883. { node.style.display = "none" }
  3884. else
  3885. { node.parentNode.removeChild(node) }
  3886. return next
  3887. }
  3888. var view = display.view, lineN = display.viewFrom
  3889. // Loop over the elements in the view, syncing cur (the DOM nodes
  3890. // in display.lineDiv) with the view as we go.
  3891. for (var i = 0; i < view.length; i++) {
  3892. var lineView = view[i]
  3893. if (lineView.hidden) {
  3894. } else if (!lineView.node || lineView.node.parentNode != container) { // Not drawn yet
  3895. var node = buildLineElement(cm, lineView, lineN, dims)
  3896. container.insertBefore(node, cur)
  3897. } else { // Already drawn
  3898. while (cur != lineView.node) { cur = rm(cur) }
  3899. var updateNumber = lineNumbers && updateNumbersFrom != null &&
  3900. updateNumbersFrom <= lineN && lineView.lineNumber
  3901. if (lineView.changes) {
  3902. if (indexOf(lineView.changes, "gutter") > -1) { updateNumber = false }
  3903. updateLineForChanges(cm, lineView, lineN, dims)
  3904. }
  3905. if (updateNumber) {
  3906. removeChildren(lineView.lineNumber)
  3907. lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN)))
  3908. }
  3909. cur = lineView.node.nextSibling
  3910. }
  3911. lineN += lineView.size
  3912. }
  3913. while (cur) { cur = rm(cur) }
  3914. }
  3915. function updateGutterSpace(cm) {
  3916. var width = cm.display.gutters.offsetWidth
  3917. cm.display.sizer.style.marginLeft = width + "px"
  3918. }
  3919. function setDocumentHeight(cm, measure) {
  3920. cm.display.sizer.style.minHeight = measure.docHeight + "px"
  3921. cm.display.heightForcer.style.top = measure.docHeight + "px"
  3922. cm.display.gutters.style.height = (measure.docHeight + cm.display.barHeight + scrollGap(cm)) + "px"
  3923. }
  3924. // Rebuild the gutter elements, ensure the margin to the left of the
  3925. // code matches their width.
  3926. function updateGutters(cm) {
  3927. var gutters = cm.display.gutters, specs = cm.options.gutters
  3928. removeChildren(gutters)
  3929. var i = 0
  3930. for (; i < specs.length; ++i) {
  3931. var gutterClass = specs[i]
  3932. var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + gutterClass))
  3933. if (gutterClass == "CodeMirror-linenumbers") {
  3934. cm.display.lineGutter = gElt
  3935. gElt.style.width = (cm.display.lineNumWidth || 1) + "px"
  3936. }
  3937. }
  3938. gutters.style.display = i ? "" : "none"
  3939. updateGutterSpace(cm)
  3940. }
  3941. // Make sure the gutters options contains the element
  3942. // "CodeMirror-linenumbers" when the lineNumbers option is true.
  3943. function setGuttersForLineNumbers(options) {
  3944. var found = indexOf(options.gutters, "CodeMirror-linenumbers")
  3945. if (found == -1 && options.lineNumbers) {
  3946. options.gutters = options.gutters.concat(["CodeMirror-linenumbers"])
  3947. } else if (found > -1 && !options.lineNumbers) {
  3948. options.gutters = options.gutters.slice(0)
  3949. options.gutters.splice(found, 1)
  3950. }
  3951. }
  3952. var wheelSamples = 0;
  3953. var wheelPixelsPerUnit = null;
  3954. // Fill in a browser-detected starting value on browsers where we
  3955. // know one. These don't have to be accurate -- the result of them
  3956. // being wrong would just be a slight flicker on the first wheel
  3957. // scroll (if it is large enough).
  3958. if (ie) { wheelPixelsPerUnit = -.53 }
  3959. else if (gecko) { wheelPixelsPerUnit = 15 }
  3960. else if (chrome) { wheelPixelsPerUnit = -.7 }
  3961. else if (safari) { wheelPixelsPerUnit = -1/3 }
  3962. function wheelEventDelta(e) {
  3963. var dx = e.wheelDeltaX, dy = e.wheelDeltaY
  3964. if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) { dx = e.detail }
  3965. if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) { dy = e.detail }
  3966. else if (dy == null) { dy = e.wheelDelta }
  3967. return {x: dx, y: dy}
  3968. }
  3969. function wheelEventPixels(e) {
  3970. var delta = wheelEventDelta(e)
  3971. delta.x *= wheelPixelsPerUnit
  3972. delta.y *= wheelPixelsPerUnit
  3973. return delta
  3974. }
  3975. function onScrollWheel(cm, e) {
  3976. var delta = wheelEventDelta(e), dx = delta.x, dy = delta.y
  3977. var display = cm.display, scroll = display.scroller
  3978. // Quit if there's nothing to scroll here
  3979. var canScrollX = scroll.scrollWidth > scroll.clientWidth
  3980. var canScrollY = scroll.scrollHeight > scroll.clientHeight
  3981. if (!(dx && canScrollX || dy && canScrollY)) { return }
  3982. // Webkit browsers on OS X abort momentum scrolls when the target
  3983. // of the scroll event is removed from the scrollable element.
  3984. // This hack (see related code in patchDisplay) makes sure the
  3985. // element is kept around.
  3986. if (dy && mac && webkit) {
  3987. outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) {
  3988. for (var i = 0; i < view.length; i++) {
  3989. if (view[i].node == cur) {
  3990. cm.display.currentWheelTarget = cur
  3991. break outer
  3992. }
  3993. }
  3994. }
  3995. }
  3996. // On some browsers, horizontal scrolling will cause redraws to
  3997. // happen before the gutter has been realigned, causing it to
  3998. // wriggle around in a most unseemly way. When we have an
  3999. // estimated pixels/delta value, we just handle horizontal
  4000. // scrolling entirely here. It'll be slightly off from native, but
  4001. // better than glitching out.
  4002. if (dx && !gecko && !presto && wheelPixelsPerUnit != null) {
  4003. if (dy && canScrollY)
  4004. { updateScrollTop(cm, Math.max(0, scroll.scrollTop + dy * wheelPixelsPerUnit)) }
  4005. setScrollLeft(cm, Math.max(0, scroll.scrollLeft + dx * wheelPixelsPerUnit))
  4006. // Only prevent default scrolling if vertical scrolling is
  4007. // actually possible. Otherwise, it causes vertical scroll
  4008. // jitter on OSX trackpads when deltaX is small and deltaY
  4009. // is large (issue #3579)
  4010. if (!dy || (dy && canScrollY))
  4011. { e_preventDefault(e) }
  4012. display.wheelStartX = null // Abort measurement, if in progress
  4013. return
  4014. }
  4015. // 'Project' the visible viewport to cover the area that is being
  4016. // scrolled into view (if we know enough to estimate it).
  4017. if (dy && wheelPixelsPerUnit != null) {
  4018. var pixels = dy * wheelPixelsPerUnit
  4019. var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight
  4020. if (pixels < 0) { top = Math.max(0, top + pixels - 50) }
  4021. else { bot = Math.min(cm.doc.height, bot + pixels + 50) }
  4022. updateDisplaySimple(cm, {top: top, bottom: bot})
  4023. }
  4024. if (wheelSamples < 20) {
  4025. if (display.wheelStartX == null) {
  4026. display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop
  4027. display.wheelDX = dx; display.wheelDY = dy
  4028. setTimeout(function () {
  4029. if (display.wheelStartX == null) { return }
  4030. var movedX = scroll.scrollLeft - display.wheelStartX
  4031. var movedY = scroll.scrollTop - display.wheelStartY
  4032. var sample = (movedY && display.wheelDY && movedY / display.wheelDY) ||
  4033. (movedX && display.wheelDX && movedX / display.wheelDX)
  4034. display.wheelStartX = display.wheelStartY = null
  4035. if (!sample) { return }
  4036. wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1)
  4037. ++wheelSamples
  4038. }, 200)
  4039. } else {
  4040. display.wheelDX += dx; display.wheelDY += dy
  4041. }
  4042. }
  4043. }
  4044. // Selection objects are immutable. A new one is created every time
  4045. // the selection changes. A selection is one or more non-overlapping
  4046. // (and non-touching) ranges, sorted, and an integer that indicates
  4047. // which one is the primary selection (the one that's scrolled into
  4048. // view, that getCursor returns, etc).
  4049. var Selection = function(ranges, primIndex) {
  4050. this.ranges = ranges
  4051. this.primIndex = primIndex
  4052. };
  4053. Selection.prototype.primary = function () { return this.ranges[this.primIndex] };
  4054. Selection.prototype.equals = function (other) {
  4055. var this$1 = this;
  4056. if (other == this) { return true }
  4057. if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) { return false }
  4058. for (var i = 0; i < this.ranges.length; i++) {
  4059. var here = this$1.ranges[i], there = other.ranges[i]
  4060. if (!equalCursorPos(here.anchor, there.anchor) || !equalCursorPos(here.head, there.head)) { return false }
  4061. }
  4062. return true
  4063. };
  4064. Selection.prototype.deepCopy = function () {
  4065. var this$1 = this;
  4066. var out = []
  4067. for (var i = 0; i < this.ranges.length; i++)
  4068. { out[i] = new Range(copyPos(this$1.ranges[i].anchor), copyPos(this$1.ranges[i].head)) }
  4069. return new Selection(out, this.primIndex)
  4070. };
  4071. Selection.prototype.somethingSelected = function () {
  4072. var this$1 = this;
  4073. for (var i = 0; i < this.ranges.length; i++)
  4074. { if (!this$1.ranges[i].empty()) { return true } }
  4075. return false
  4076. };
  4077. Selection.prototype.contains = function (pos, end) {
  4078. var this$1 = this;
  4079. if (!end) { end = pos }
  4080. for (var i = 0; i < this.ranges.length; i++) {
  4081. var range = this$1.ranges[i]
  4082. if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0)
  4083. { return i }
  4084. }
  4085. return -1
  4086. };
  4087. var Range = function(anchor, head) {
  4088. this.anchor = anchor; this.head = head
  4089. };
  4090. Range.prototype.from = function () { return minPos(this.anchor, this.head) };
  4091. Range.prototype.to = function () { return maxPos(this.anchor, this.head) };
  4092. Range.prototype.empty = function () { return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch };
  4093. // Take an unsorted, potentially overlapping set of ranges, and
  4094. // build a selection out of it. 'Consumes' ranges array (modifying
  4095. // it).
  4096. function normalizeSelection(ranges, primIndex) {
  4097. var prim = ranges[primIndex]
  4098. ranges.sort(function (a, b) { return cmp(a.from(), b.from()); })
  4099. primIndex = indexOf(ranges, prim)
  4100. for (var i = 1; i < ranges.length; i++) {
  4101. var cur = ranges[i], prev = ranges[i - 1]
  4102. if (cmp(prev.to(), cur.from()) >= 0) {
  4103. var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to())
  4104. var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head
  4105. if (i <= primIndex) { --primIndex }
  4106. ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to))
  4107. }
  4108. }
  4109. return new Selection(ranges, primIndex)
  4110. }
  4111. function simpleSelection(anchor, head) {
  4112. return new Selection([new Range(anchor, head || anchor)], 0)
  4113. }
  4114. // Compute the position of the end of a change (its 'to' property
  4115. // refers to the pre-change end).
  4116. function changeEnd(change) {
  4117. if (!change.text) { return change.to }
  4118. return Pos(change.from.line + change.text.length - 1,
  4119. lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0))
  4120. }
  4121. // Adjust a position to refer to the post-change position of the
  4122. // same text, or the end of the change if the change covers it.
  4123. function adjustForChange(pos, change) {
  4124. if (cmp(pos, change.from) < 0) { return pos }
  4125. if (cmp(pos, change.to) <= 0) { return changeEnd(change) }
  4126. var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch
  4127. if (pos.line == change.to.line) { ch += changeEnd(change).ch - change.to.ch }
  4128. return Pos(line, ch)
  4129. }
  4130. function computeSelAfterChange(doc, change) {
  4131. var out = []
  4132. for (var i = 0; i < doc.sel.ranges.length; i++) {
  4133. var range = doc.sel.ranges[i]
  4134. out.push(new Range(adjustForChange(range.anchor, change),
  4135. adjustForChange(range.head, change)))
  4136. }
  4137. return normalizeSelection(out, doc.sel.primIndex)
  4138. }
  4139. function offsetPos(pos, old, nw) {
  4140. if (pos.line == old.line)
  4141. { return Pos(nw.line, pos.ch - old.ch + nw.ch) }
  4142. else
  4143. { return Pos(nw.line + (pos.line - old.line), pos.ch) }
  4144. }
  4145. // Used by replaceSelections to allow moving the selection to the
  4146. // start or around the replaced test. Hint may be "start" or "around".
  4147. function computeReplacedSel(doc, changes, hint) {
  4148. var out = []
  4149. var oldPrev = Pos(doc.first, 0), newPrev = oldPrev
  4150. for (var i = 0; i < changes.length; i++) {
  4151. var change = changes[i]
  4152. var from = offsetPos(change.from, oldPrev, newPrev)
  4153. var to = offsetPos(changeEnd(change), oldPrev, newPrev)
  4154. oldPrev = change.to
  4155. newPrev = to
  4156. if (hint == "around") {
  4157. var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) < 0
  4158. out[i] = new Range(inv ? to : from, inv ? from : to)
  4159. } else {
  4160. out[i] = new Range(from, from)
  4161. }
  4162. }
  4163. return new Selection(out, doc.sel.primIndex)
  4164. }
  4165. // Used to get the editor into a consistent state again when options change.
  4166. function loadMode(cm) {
  4167. cm.doc.mode = getMode(cm.options, cm.doc.modeOption)
  4168. resetModeState(cm)
  4169. }
  4170. function resetModeState(cm) {
  4171. cm.doc.iter(function (line) {
  4172. if (line.stateAfter) { line.stateAfter = null }
  4173. if (line.styles) { line.styles = null }
  4174. })
  4175. cm.doc.modeFrontier = cm.doc.highlightFrontier = cm.doc.first
  4176. startWorker(cm, 100)
  4177. cm.state.modeGen++
  4178. if (cm.curOp) { regChange(cm) }
  4179. }
  4180. // DOCUMENT DATA STRUCTURE
  4181. // By default, updates that start and end at the beginning of a line
  4182. // are treated specially, in order to make the association of line
  4183. // widgets and marker elements with the text behave more intuitive.
  4184. function isWholeLineUpdate(doc, change) {
  4185. return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" &&
  4186. (!doc.cm || doc.cm.options.wholeLineUpdateBefore)
  4187. }
  4188. // Perform a change on the document data structure.
  4189. function updateDoc(doc, change, markedSpans, estimateHeight) {
  4190. function spansFor(n) {return markedSpans ? markedSpans[n] : null}
  4191. function update(line, text, spans) {
  4192. updateLine(line, text, spans, estimateHeight)
  4193. signalLater(line, "change", line, change)
  4194. }
  4195. function linesFor(start, end) {
  4196. var result = []
  4197. for (var i = start; i < end; ++i)
  4198. { result.push(new Line(text[i], spansFor(i), estimateHeight)) }
  4199. return result
  4200. }
  4201. var from = change.from, to = change.to, text = change.text
  4202. var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line)
  4203. var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line
  4204. // Adjust the line structure
  4205. if (change.full) {
  4206. doc.insert(0, linesFor(0, text.length))
  4207. doc.remove(text.length, doc.size - text.length)
  4208. } else if (isWholeLineUpdate(doc, change)) {
  4209. // This is a whole-line replace. Treated specially to make
  4210. // sure line objects move the way they are supposed to.
  4211. var added = linesFor(0, text.length - 1)
  4212. update(lastLine, lastLine.text, lastSpans)
  4213. if (nlines) { doc.remove(from.line, nlines) }
  4214. if (added.length) { doc.insert(from.line, added) }
  4215. } else if (firstLine == lastLine) {
  4216. if (text.length == 1) {
  4217. update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans)
  4218. } else {
  4219. var added$1 = linesFor(1, text.length - 1)
  4220. added$1.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight))
  4221. update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0))
  4222. doc.insert(from.line + 1, added$1)
  4223. }
  4224. } else if (text.length == 1) {
  4225. update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0))
  4226. doc.remove(from.line + 1, nlines)
  4227. } else {
  4228. update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0))
  4229. update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans)
  4230. var added$2 = linesFor(1, text.length - 1)
  4231. if (nlines > 1) { doc.remove(from.line + 1, nlines - 1) }
  4232. doc.insert(from.line + 1, added$2)
  4233. }
  4234. signalLater(doc, "change", doc, change)
  4235. }
  4236. // Call f for all linked documents.
  4237. function linkedDocs(doc, f, sharedHistOnly) {
  4238. function propagate(doc, skip, sharedHist) {
  4239. if (doc.linked) { for (var i = 0; i < doc.linked.length; ++i) {
  4240. var rel = doc.linked[i]
  4241. if (rel.doc == skip) { continue }
  4242. var shared = sharedHist && rel.sharedHist
  4243. if (sharedHistOnly && !shared) { continue }
  4244. f(rel.doc, shared)
  4245. propagate(rel.doc, doc, shared)
  4246. } }
  4247. }
  4248. propagate(doc, null, true)
  4249. }
  4250. // Attach a document to an editor.
  4251. function attachDoc(cm, doc) {
  4252. if (doc.cm) { throw new Error("This document is already in use.") }
  4253. cm.doc = doc
  4254. doc.cm = cm
  4255. estimateLineHeights(cm)
  4256. loadMode(cm)
  4257. setDirectionClass(cm)
  4258. if (!cm.options.lineWrapping) { findMaxLine(cm) }
  4259. cm.options.mode = doc.modeOption
  4260. regChange(cm)
  4261. }
  4262. function setDirectionClass(cm) {
  4263. ;(cm.doc.direction == "rtl" ? addClass : rmClass)(cm.display.lineDiv, "CodeMirror-rtl")
  4264. }
  4265. function directionChanged(cm) {
  4266. runInOp(cm, function () {
  4267. setDirectionClass(cm)
  4268. regChange(cm)
  4269. })
  4270. }
  4271. function History(startGen) {
  4272. // Arrays of change events and selections. Doing something adds an
  4273. // event to done and clears undo. Undoing moves events from done
  4274. // to undone, redoing moves them in the other direction.
  4275. this.done = []; this.undone = []
  4276. this.undoDepth = Infinity
  4277. // Used to track when changes can be merged into a single undo
  4278. // event
  4279. this.lastModTime = this.lastSelTime = 0
  4280. this.lastOp = this.lastSelOp = null
  4281. this.lastOrigin = this.lastSelOrigin = null
  4282. // Used by the isClean() method
  4283. this.generation = this.maxGeneration = startGen || 1
  4284. }
  4285. // Create a history change event from an updateDoc-style change
  4286. // object.
  4287. function historyChangeFromChange(doc, change) {
  4288. var histChange = {from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to)}
  4289. attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1)
  4290. linkedDocs(doc, function (doc) { return attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1); }, true)
  4291. return histChange
  4292. }
  4293. // Pop all selection events off the end of a history array. Stop at
  4294. // a change event.
  4295. function clearSelectionEvents(array) {
  4296. while (array.length) {
  4297. var last = lst(array)
  4298. if (last.ranges) { array.pop() }
  4299. else { break }
  4300. }
  4301. }
  4302. // Find the top change event in the history. Pop off selection
  4303. // events that are in the way.
  4304. function lastChangeEvent(hist, force) {
  4305. if (force) {
  4306. clearSelectionEvents(hist.done)
  4307. return lst(hist.done)
  4308. } else if (hist.done.length && !lst(hist.done).ranges) {
  4309. return lst(hist.done)
  4310. } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) {
  4311. hist.done.pop()
  4312. return lst(hist.done)
  4313. }
  4314. }
  4315. // Register a change in the history. Merges changes that are within
  4316. // a single operation, or are close together with an origin that
  4317. // allows merging (starting with "+") into a single event.
  4318. function addChangeToHistory(doc, change, selAfter, opId) {
  4319. var hist = doc.history
  4320. hist.undone.length = 0
  4321. var time = +new Date, cur
  4322. var last
  4323. if ((hist.lastOp == opId ||
  4324. hist.lastOrigin == change.origin && change.origin &&
  4325. ((change.origin.charAt(0) == "+" && doc.cm && hist.lastModTime > time - doc.cm.options.historyEventDelay) ||
  4326. change.origin.charAt(0) == "*")) &&
  4327. (cur = lastChangeEvent(hist, hist.lastOp == opId))) {
  4328. // Merge this change into the last event
  4329. last = lst(cur.changes)
  4330. if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) {
  4331. // Optimized case for simple insertion -- don't want to add
  4332. // new changesets for every character typed
  4333. last.to = changeEnd(change)
  4334. } else {
  4335. // Add new sub-event
  4336. cur.changes.push(historyChangeFromChange(doc, change))
  4337. }
  4338. } else {
  4339. // Can not be merged, start a new event.
  4340. var before = lst(hist.done)
  4341. if (!before || !before.ranges)
  4342. { pushSelectionToHistory(doc.sel, hist.done) }
  4343. cur = {changes: [historyChangeFromChange(doc, change)],
  4344. generation: hist.generation}
  4345. hist.done.push(cur)
  4346. while (hist.done.length > hist.undoDepth) {
  4347. hist.done.shift()
  4348. if (!hist.done[0].ranges) { hist.done.shift() }
  4349. }
  4350. }
  4351. hist.done.push(selAfter)
  4352. hist.generation = ++hist.maxGeneration
  4353. hist.lastModTime = hist.lastSelTime = time
  4354. hist.lastOp = hist.lastSelOp = opId
  4355. hist.lastOrigin = hist.lastSelOrigin = change.origin
  4356. if (!last) { signal(doc, "historyAdded") }
  4357. }
  4358. function selectionEventCanBeMerged(doc, origin, prev, sel) {
  4359. var ch = origin.charAt(0)
  4360. return ch == "*" ||
  4361. ch == "+" &&
  4362. prev.ranges.length == sel.ranges.length &&
  4363. prev.somethingSelected() == sel.somethingSelected() &&
  4364. new Date - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500)
  4365. }
  4366. // Called whenever the selection changes, sets the new selection as
  4367. // the pending selection in the history, and pushes the old pending
  4368. // selection into the 'done' array when it was significantly
  4369. // different (in number of selected ranges, emptiness, or time).
  4370. function addSelectionToHistory(doc, sel, opId, options) {
  4371. var hist = doc.history, origin = options && options.origin
  4372. // A new event is started when the previous origin does not match
  4373. // the current, or the origins don't allow matching. Origins
  4374. // starting with * are always merged, those starting with + are
  4375. // merged when similar and close together in time.
  4376. if (opId == hist.lastSelOp ||
  4377. (origin && hist.lastSelOrigin == origin &&
  4378. (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin ||
  4379. selectionEventCanBeMerged(doc, origin, lst(hist.done), sel))))
  4380. { hist.done[hist.done.length - 1] = sel }
  4381. else
  4382. { pushSelectionToHistory(sel, hist.done) }
  4383. hist.lastSelTime = +new Date
  4384. hist.lastSelOrigin = origin
  4385. hist.lastSelOp = opId
  4386. if (options && options.clearRedo !== false)
  4387. { clearSelectionEvents(hist.undone) }
  4388. }
  4389. function pushSelectionToHistory(sel, dest) {
  4390. var top = lst(dest)
  4391. if (!(top && top.ranges && top.equals(sel)))
  4392. { dest.push(sel) }
  4393. }
  4394. // Used to store marked span information in the history.
  4395. function attachLocalSpans(doc, change, from, to) {
  4396. var existing = change["spans_" + doc.id], n = 0
  4397. doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function (line) {
  4398. if (line.markedSpans)
  4399. { (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans }
  4400. ++n
  4401. })
  4402. }
  4403. // When un/re-doing restores text containing marked spans, those
  4404. // that have been explicitly cleared should not be restored.
  4405. function removeClearedSpans(spans) {
  4406. if (!spans) { return null }
  4407. var out
  4408. for (var i = 0; i < spans.length; ++i) {
  4409. if (spans[i].marker.explicitlyCleared) { if (!out) { out = spans.slice(0, i) } }
  4410. else if (out) { out.push(spans[i]) }
  4411. }
  4412. return !out ? spans : out.length ? out : null
  4413. }
  4414. // Retrieve and filter the old marked spans stored in a change event.
  4415. function getOldSpans(doc, change) {
  4416. var found = change["spans_" + doc.id]
  4417. if (!found) { return null }
  4418. var nw = []
  4419. for (var i = 0; i < change.text.length; ++i)
  4420. { nw.push(removeClearedSpans(found[i])) }
  4421. return nw
  4422. }
  4423. // Used for un/re-doing changes from the history. Combines the
  4424. // result of computing the existing spans with the set of spans that
  4425. // existed in the history (so that deleting around a span and then
  4426. // undoing brings back the span).
  4427. function mergeOldSpans(doc, change) {
  4428. var old = getOldSpans(doc, change)
  4429. var stretched = stretchSpansOverChange(doc, change)
  4430. if (!old) { return stretched }
  4431. if (!stretched) { return old }
  4432. for (var i = 0; i < old.length; ++i) {
  4433. var oldCur = old[i], stretchCur = stretched[i]
  4434. if (oldCur && stretchCur) {
  4435. spans: for (var j = 0; j < stretchCur.length; ++j) {
  4436. var span = stretchCur[j]
  4437. for (var k = 0; k < oldCur.length; ++k)
  4438. { if (oldCur[k].marker == span.marker) { continue spans } }
  4439. oldCur.push(span)
  4440. }
  4441. } else if (stretchCur) {
  4442. old[i] = stretchCur
  4443. }
  4444. }
  4445. return old
  4446. }
  4447. // Used both to provide a JSON-safe object in .getHistory, and, when
  4448. // detaching a document, to split the history in two
  4449. function copyHistoryArray(events, newGroup, instantiateSel) {
  4450. var copy = []
  4451. for (var i = 0; i < events.length; ++i) {
  4452. var event = events[i]
  4453. if (event.ranges) {
  4454. copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event)
  4455. continue
  4456. }
  4457. var changes = event.changes, newChanges = []
  4458. copy.push({changes: newChanges})
  4459. for (var j = 0; j < changes.length; ++j) {
  4460. var change = changes[j], m = (void 0)
  4461. newChanges.push({from: change.from, to: change.to, text: change.text})
  4462. if (newGroup) { for (var prop in change) { if (m = prop.match(/^spans_(\d+)$/)) {
  4463. if (indexOf(newGroup, Number(m[1])) > -1) {
  4464. lst(newChanges)[prop] = change[prop]
  4465. delete change[prop]
  4466. }
  4467. } } }
  4468. }
  4469. }
  4470. return copy
  4471. }
  4472. // The 'scroll' parameter given to many of these indicated whether
  4473. // the new cursor position should be scrolled into view after
  4474. // modifying the selection.
  4475. // If shift is held or the extend flag is set, extends a range to
  4476. // include a given position (and optionally a second position).
  4477. // Otherwise, simply returns the range between the given positions.
  4478. // Used for cursor motion and such.
  4479. function extendRange(range, head, other, extend) {
  4480. if (extend) {
  4481. var anchor = range.anchor
  4482. if (other) {
  4483. var posBefore = cmp(head, anchor) < 0
  4484. if (posBefore != (cmp(other, anchor) < 0)) {
  4485. anchor = head
  4486. head = other
  4487. } else if (posBefore != (cmp(head, other) < 0)) {
  4488. head = other
  4489. }
  4490. }
  4491. return new Range(anchor, head)
  4492. } else {
  4493. return new Range(other || head, head)
  4494. }
  4495. }
  4496. // Extend the primary selection range, discard the rest.
  4497. function extendSelection(doc, head, other, options, extend) {
  4498. if (extend == null) { extend = doc.cm && (doc.cm.display.shift || doc.extend) }
  4499. setSelection(doc, new Selection([extendRange(doc.sel.primary(), head, other, extend)], 0), options)
  4500. }
  4501. // Extend all selections (pos is an array of selections with length
  4502. // equal the number of selections)
  4503. function extendSelections(doc, heads, options) {
  4504. var out = []
  4505. var extend = doc.cm && (doc.cm.display.shift || doc.extend)
  4506. for (var i = 0; i < doc.sel.ranges.length; i++)
  4507. { out[i] = extendRange(doc.sel.ranges[i], heads[i], null, extend) }
  4508. var newSel = normalizeSelection(out, doc.sel.primIndex)
  4509. setSelection(doc, newSel, options)
  4510. }
  4511. // Updates a single range in the selection.
  4512. function replaceOneSelection(doc, i, range, options) {
  4513. var ranges = doc.sel.ranges.slice(0)
  4514. ranges[i] = range
  4515. setSelection(doc, normalizeSelection(ranges, doc.sel.primIndex), options)
  4516. }
  4517. // Reset the selection to a single range.
  4518. function setSimpleSelection(doc, anchor, head, options) {
  4519. setSelection(doc, simpleSelection(anchor, head), options)
  4520. }
  4521. // Give beforeSelectionChange handlers a change to influence a
  4522. // selection update.
  4523. function filterSelectionChange(doc, sel, options) {
  4524. var obj = {
  4525. ranges: sel.ranges,
  4526. update: function(ranges) {
  4527. var this$1 = this;
  4528. this.ranges = []
  4529. for (var i = 0; i < ranges.length; i++)
  4530. { this$1.ranges[i] = new Range(clipPos(doc, ranges[i].anchor),
  4531. clipPos(doc, ranges[i].head)) }
  4532. },
  4533. origin: options && options.origin
  4534. }
  4535. signal(doc, "beforeSelectionChange", doc, obj)
  4536. if (doc.cm) { signal(doc.cm, "beforeSelectionChange", doc.cm, obj) }
  4537. if (obj.ranges != sel.ranges) { return normalizeSelection(obj.ranges, obj.ranges.length - 1) }
  4538. else { return sel }
  4539. }
  4540. function setSelectionReplaceHistory(doc, sel, options) {
  4541. var done = doc.history.done, last = lst(done)
  4542. if (last && last.ranges) {
  4543. done[done.length - 1] = sel
  4544. setSelectionNoUndo(doc, sel, options)
  4545. } else {
  4546. setSelection(doc, sel, options)
  4547. }
  4548. }
  4549. // Set a new selection.
  4550. function setSelection(doc, sel, options) {
  4551. setSelectionNoUndo(doc, sel, options)
  4552. addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options)
  4553. }
  4554. function setSelectionNoUndo(doc, sel, options) {
  4555. if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange"))
  4556. { sel = filterSelectionChange(doc, sel, options) }
  4557. var bias = options && options.bias ||
  4558. (cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1)
  4559. setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true))
  4560. if (!(options && options.scroll === false) && doc.cm)
  4561. { ensureCursorVisible(doc.cm) }
  4562. }
  4563. function setSelectionInner(doc, sel) {
  4564. if (sel.equals(doc.sel)) { return }
  4565. doc.sel = sel
  4566. if (doc.cm) {
  4567. doc.cm.curOp.updateInput = doc.cm.curOp.selectionChanged = true
  4568. signalCursorActivity(doc.cm)
  4569. }
  4570. signalLater(doc, "cursorActivity", doc)
  4571. }
  4572. // Verify that the selection does not partially select any atomic
  4573. // marked ranges.
  4574. function reCheckSelection(doc) {
  4575. setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false))
  4576. }
  4577. // Return a selection that does not partially select any atomic
  4578. // ranges.
  4579. function skipAtomicInSelection(doc, sel, bias, mayClear) {
  4580. var out
  4581. for (var i = 0; i < sel.ranges.length; i++) {
  4582. var range = sel.ranges[i]
  4583. var old = sel.ranges.length == doc.sel.ranges.length && doc.sel.ranges[i]
  4584. var newAnchor = skipAtomic(doc, range.anchor, old && old.anchor, bias, mayClear)
  4585. var newHead = skipAtomic(doc, range.head, old && old.head, bias, mayClear)
  4586. if (out || newAnchor != range.anchor || newHead != range.head) {
  4587. if (!out) { out = sel.ranges.slice(0, i) }
  4588. out[i] = new Range(newAnchor, newHead)
  4589. }
  4590. }
  4591. return out ? normalizeSelection(out, sel.primIndex) : sel
  4592. }
  4593. function skipAtomicInner(doc, pos, oldPos, dir, mayClear) {
  4594. var line = getLine(doc, pos.line)
  4595. if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) {
  4596. var sp = line.markedSpans[i], m = sp.marker
  4597. if ((sp.from == null || (m.inclusiveLeft ? sp.from <= pos.ch : sp.from < pos.ch)) &&
  4598. (sp.to == null || (m.inclusiveRight ? sp.to >= pos.ch : sp.to > pos.ch))) {
  4599. if (mayClear) {
  4600. signal(m, "beforeCursorEnter")
  4601. if (m.explicitlyCleared) {
  4602. if (!line.markedSpans) { break }
  4603. else {--i; continue}
  4604. }
  4605. }
  4606. if (!m.atomic) { continue }
  4607. if (oldPos) {
  4608. var near = m.find(dir < 0 ? 1 : -1), diff = (void 0)
  4609. if (dir < 0 ? m.inclusiveRight : m.inclusiveLeft)
  4610. { near = movePos(doc, near, -dir, near && near.line == pos.line ? line : null) }
  4611. if (near && near.line == pos.line && (diff = cmp(near, oldPos)) && (dir < 0 ? diff < 0 : diff > 0))
  4612. { return skipAtomicInner(doc, near, pos, dir, mayClear) }
  4613. }
  4614. var far = m.find(dir < 0 ? -1 : 1)
  4615. if (dir < 0 ? m.inclusiveLeft : m.inclusiveRight)
  4616. { far = movePos(doc, far, dir, far.line == pos.line ? line : null) }
  4617. return far ? skipAtomicInner(doc, far, pos, dir, mayClear) : null
  4618. }
  4619. } }
  4620. return pos
  4621. }
  4622. // Ensure a given position is not inside an atomic range.
  4623. function skipAtomic(doc, pos, oldPos, bias, mayClear) {
  4624. var dir = bias || 1
  4625. var found = skipAtomicInner(doc, pos, oldPos, dir, mayClear) ||
  4626. (!mayClear && skipAtomicInner(doc, pos, oldPos, dir, true)) ||
  4627. skipAtomicInner(doc, pos, oldPos, -dir, mayClear) ||
  4628. (!mayClear && skipAtomicInner(doc, pos, oldPos, -dir, true))
  4629. if (!found) {
  4630. doc.cantEdit = true
  4631. return Pos(doc.first, 0)
  4632. }
  4633. return found
  4634. }
  4635. function movePos(doc, pos, dir, line) {
  4636. if (dir < 0 && pos.ch == 0) {
  4637. if (pos.line > doc.first) { return clipPos(doc, Pos(pos.line - 1)) }
  4638. else { return null }
  4639. } else if (dir > 0 && pos.ch == (line || getLine(doc, pos.line)).text.length) {
  4640. if (pos.line < doc.first + doc.size - 1) { return Pos(pos.line + 1, 0) }
  4641. else { return null }
  4642. } else {
  4643. return new Pos(pos.line, pos.ch + dir)
  4644. }
  4645. }
  4646. function selectAll(cm) {
  4647. cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll)
  4648. }
  4649. // UPDATING
  4650. // Allow "beforeChange" event handlers to influence a change
  4651. function filterChange(doc, change, update) {
  4652. var obj = {
  4653. canceled: false,
  4654. from: change.from,
  4655. to: change.to,
  4656. text: change.text,
  4657. origin: change.origin,
  4658. cancel: function () { return obj.canceled = true; }
  4659. }
  4660. if (update) { obj.update = function (from, to, text, origin) {
  4661. if (from) { obj.from = clipPos(doc, from) }
  4662. if (to) { obj.to = clipPos(doc, to) }
  4663. if (text) { obj.text = text }
  4664. if (origin !== undefined) { obj.origin = origin }
  4665. } }
  4666. signal(doc, "beforeChange", doc, obj)
  4667. if (doc.cm) { signal(doc.cm, "beforeChange", doc.cm, obj) }
  4668. if (obj.canceled) { return null }
  4669. return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin}
  4670. }
  4671. // Apply a change to a document, and add it to the document's
  4672. // history, and propagating it to all linked documents.
  4673. function makeChange(doc, change, ignoreReadOnly) {
  4674. if (doc.cm) {
  4675. if (!doc.cm.curOp) { return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly) }
  4676. if (doc.cm.state.suppressEdits) { return }
  4677. }
  4678. if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) {
  4679. change = filterChange(doc, change, true)
  4680. if (!change) { return }
  4681. }
  4682. // Possibly split or suppress the update based on the presence
  4683. // of read-only spans in its range.
  4684. var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to)
  4685. if (split) {
  4686. for (var i = split.length - 1; i >= 0; --i)
  4687. { makeChangeInner(doc, {from: split[i].from, to: split[i].to, text: i ? [""] : change.text, origin: change.origin}) }
  4688. } else {
  4689. makeChangeInner(doc, change)
  4690. }
  4691. }
  4692. function makeChangeInner(doc, change) {
  4693. if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) { return }
  4694. var selAfter = computeSelAfterChange(doc, change)
  4695. addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN)
  4696. makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change))
  4697. var rebased = []
  4698. linkedDocs(doc, function (doc, sharedHist) {
  4699. if (!sharedHist && indexOf(rebased, doc.history) == -1) {
  4700. rebaseHist(doc.history, change)
  4701. rebased.push(doc.history)
  4702. }
  4703. makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change))
  4704. })
  4705. }
  4706. // Revert a change stored in a document's history.
  4707. function makeChangeFromHistory(doc, type, allowSelectionOnly) {
  4708. if (doc.cm && doc.cm.state.suppressEdits && !allowSelectionOnly) { return }
  4709. var hist = doc.history, event, selAfter = doc.sel
  4710. var source = type == "undo" ? hist.done : hist.undone, dest = type == "undo" ? hist.undone : hist.done
  4711. // Verify that there is a useable event (so that ctrl-z won't
  4712. // needlessly clear selection events)
  4713. var i = 0
  4714. for (; i < source.length; i++) {
  4715. event = source[i]
  4716. if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges)
  4717. { break }
  4718. }
  4719. if (i == source.length) { return }
  4720. hist.lastOrigin = hist.lastSelOrigin = null
  4721. for (;;) {
  4722. event = source.pop()
  4723. if (event.ranges) {
  4724. pushSelectionToHistory(event, dest)
  4725. if (allowSelectionOnly && !event.equals(doc.sel)) {
  4726. setSelection(doc, event, {clearRedo: false})
  4727. return
  4728. }
  4729. selAfter = event
  4730. }
  4731. else { break }
  4732. }
  4733. // Build up a reverse change object to add to the opposite history
  4734. // stack (redo when undoing, and vice versa).
  4735. var antiChanges = []
  4736. pushSelectionToHistory(selAfter, dest)
  4737. dest.push({changes: antiChanges, generation: hist.generation})
  4738. hist.generation = event.generation || ++hist.maxGeneration
  4739. var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")
  4740. var loop = function ( i ) {
  4741. var change = event.changes[i]
  4742. change.origin = type
  4743. if (filter && !filterChange(doc, change, false)) {
  4744. source.length = 0
  4745. return {}
  4746. }
  4747. antiChanges.push(historyChangeFromChange(doc, change))
  4748. var after = i ? computeSelAfterChange(doc, change) : lst(source)
  4749. makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change))
  4750. if (!i && doc.cm) { doc.cm.scrollIntoView({from: change.from, to: changeEnd(change)}) }
  4751. var rebased = []
  4752. // Propagate to the linked documents
  4753. linkedDocs(doc, function (doc, sharedHist) {
  4754. if (!sharedHist && indexOf(rebased, doc.history) == -1) {
  4755. rebaseHist(doc.history, change)
  4756. rebased.push(doc.history)
  4757. }
  4758. makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change))
  4759. })
  4760. };
  4761. for (var i$1 = event.changes.length - 1; i$1 >= 0; --i$1) {
  4762. var returned = loop( i$1 );
  4763. if ( returned ) return returned.v;
  4764. }
  4765. }
  4766. // Sub-views need their line numbers shifted when text is added
  4767. // above or below them in the parent document.
  4768. function shiftDoc(doc, distance) {
  4769. if (distance == 0) { return }
  4770. doc.first += distance
  4771. doc.sel = new Selection(map(doc.sel.ranges, function (range) { return new Range(
  4772. Pos(range.anchor.line + distance, range.anchor.ch),
  4773. Pos(range.head.line + distance, range.head.ch)
  4774. ); }), doc.sel.primIndex)
  4775. if (doc.cm) {
  4776. regChange(doc.cm, doc.first, doc.first - distance, distance)
  4777. for (var d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++)
  4778. { regLineChange(doc.cm, l, "gutter") }
  4779. }
  4780. }
  4781. // More lower-level change function, handling only a single document
  4782. // (not linked ones).
  4783. function makeChangeSingleDoc(doc, change, selAfter, spans) {
  4784. if (doc.cm && !doc.cm.curOp)
  4785. { return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans) }
  4786. if (change.to.line < doc.first) {
  4787. shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line))
  4788. return
  4789. }
  4790. if (change.from.line > doc.lastLine()) { return }
  4791. // Clip the change to the size of this doc
  4792. if (change.from.line < doc.first) {
  4793. var shift = change.text.length - 1 - (doc.first - change.from.line)
  4794. shiftDoc(doc, shift)
  4795. change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch),
  4796. text: [lst(change.text)], origin: change.origin}
  4797. }
  4798. var last = doc.lastLine()
  4799. if (change.to.line > last) {
  4800. change = {from: change.from, to: Pos(last, getLine(doc, last).text.length),
  4801. text: [change.text[0]], origin: change.origin}
  4802. }
  4803. change.removed = getBetween(doc, change.from, change.to)
  4804. if (!selAfter) { selAfter = computeSelAfterChange(doc, change) }
  4805. if (doc.cm) { makeChangeSingleDocInEditor(doc.cm, change, spans) }
  4806. else { updateDoc(doc, change, spans) }
  4807. setSelectionNoUndo(doc, selAfter, sel_dontScroll)
  4808. }
  4809. // Handle the interaction of a change to a document with the editor
  4810. // that this document is part of.
  4811. function makeChangeSingleDocInEditor(cm, change, spans) {
  4812. var doc = cm.doc, display = cm.display, from = change.from, to = change.to
  4813. var recomputeMaxLength = false, checkWidthStart = from.line
  4814. if (!cm.options.lineWrapping) {
  4815. checkWidthStart = lineNo(visualLine(getLine(doc, from.line)))
  4816. doc.iter(checkWidthStart, to.line + 1, function (line) {
  4817. if (line == display.maxLine) {
  4818. recomputeMaxLength = true
  4819. return true
  4820. }
  4821. })
  4822. }
  4823. if (doc.sel.contains(change.from, change.to) > -1)
  4824. { signalCursorActivity(cm) }
  4825. updateDoc(doc, change, spans, estimateHeight(cm))
  4826. if (!cm.options.lineWrapping) {
  4827. doc.iter(checkWidthStart, from.line + change.text.length, function (line) {
  4828. var len = lineLength(line)
  4829. if (len > display.maxLineLength) {
  4830. display.maxLine = line
  4831. display.maxLineLength = len
  4832. display.maxLineChanged = true
  4833. recomputeMaxLength = false
  4834. }
  4835. })
  4836. if (recomputeMaxLength) { cm.curOp.updateMaxLine = true }
  4837. }
  4838. retreatFrontier(doc, from.line)
  4839. startWorker(cm, 400)
  4840. var lendiff = change.text.length - (to.line - from.line) - 1
  4841. // Remember that these lines changed, for updating the display
  4842. if (change.full)
  4843. { regChange(cm) }
  4844. else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change))
  4845. { regLineChange(cm, from.line, "text") }
  4846. else
  4847. { regChange(cm, from.line, to.line + 1, lendiff) }
  4848. var changesHandler = hasHandler(cm, "changes"), changeHandler = hasHandler(cm, "change")
  4849. if (changeHandler || changesHandler) {
  4850. var obj = {
  4851. from: from, to: to,
  4852. text: change.text,
  4853. removed: change.removed,
  4854. origin: change.origin
  4855. }
  4856. if (changeHandler) { signalLater(cm, "change", cm, obj) }
  4857. if (changesHandler) { (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj) }
  4858. }
  4859. cm.display.selForContextMenu = null
  4860. }
  4861. function replaceRange(doc, code, from, to, origin) {
  4862. if (!to) { to = from }
  4863. if (cmp(to, from) < 0) { var assign;
  4864. (assign = [to, from], from = assign[0], to = assign[1], assign) }
  4865. if (typeof code == "string") { code = doc.splitLines(code) }
  4866. makeChange(doc, {from: from, to: to, text: code, origin: origin})
  4867. }
  4868. // Rebasing/resetting history to deal with externally-sourced changes
  4869. function rebaseHistSelSingle(pos, from, to, diff) {
  4870. if (to < pos.line) {
  4871. pos.line += diff
  4872. } else if (from < pos.line) {
  4873. pos.line = from
  4874. pos.ch = 0
  4875. }
  4876. }
  4877. // Tries to rebase an array of history events given a change in the
  4878. // document. If the change touches the same lines as the event, the
  4879. // event, and everything 'behind' it, is discarded. If the change is
  4880. // before the event, the event's positions are updated. Uses a
  4881. // copy-on-write scheme for the positions, to avoid having to
  4882. // reallocate them all on every rebase, but also avoid problems with
  4883. // shared position objects being unsafely updated.
  4884. function rebaseHistArray(array, from, to, diff) {
  4885. for (var i = 0; i < array.length; ++i) {
  4886. var sub = array[i], ok = true
  4887. if (sub.ranges) {
  4888. if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true }
  4889. for (var j = 0; j < sub.ranges.length; j++) {
  4890. rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff)
  4891. rebaseHistSelSingle(sub.ranges[j].head, from, to, diff)
  4892. }
  4893. continue
  4894. }
  4895. for (var j$1 = 0; j$1 < sub.changes.length; ++j$1) {
  4896. var cur = sub.changes[j$1]
  4897. if (to < cur.from.line) {
  4898. cur.from = Pos(cur.from.line + diff, cur.from.ch)
  4899. cur.to = Pos(cur.to.line + diff, cur.to.ch)
  4900. } else if (from <= cur.to.line) {
  4901. ok = false
  4902. break
  4903. }
  4904. }
  4905. if (!ok) {
  4906. array.splice(0, i + 1)
  4907. i = 0
  4908. }
  4909. }
  4910. }
  4911. function rebaseHist(hist, change) {
  4912. var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1
  4913. rebaseHistArray(hist.done, from, to, diff)
  4914. rebaseHistArray(hist.undone, from, to, diff)
  4915. }
  4916. // Utility for applying a change to a line by handle or number,
  4917. // returning the number and optionally registering the line as
  4918. // changed.
  4919. function changeLine(doc, handle, changeType, op) {
  4920. var no = handle, line = handle
  4921. if (typeof handle == "number") { line = getLine(doc, clipLine(doc, handle)) }
  4922. else { no = lineNo(handle) }
  4923. if (no == null) { return null }
  4924. if (op(line, no) && doc.cm) { regLineChange(doc.cm, no, changeType) }
  4925. return line
  4926. }
  4927. // The document is represented as a BTree consisting of leaves, with
  4928. // chunk of lines in them, and branches, with up to ten leaves or
  4929. // other branch nodes below them. The top node is always a branch
  4930. // node, and is the document object itself (meaning it has
  4931. // additional methods and properties).
  4932. //
  4933. // All nodes have parent links. The tree is used both to go from
  4934. // line numbers to line objects, and to go from objects to numbers.
  4935. // It also indexes by height, and is used to convert between height
  4936. // and line object, and to find the total height of the document.
  4937. //
  4938. // See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html
  4939. function LeafChunk(lines) {
  4940. var this$1 = this;
  4941. this.lines = lines
  4942. this.parent = null
  4943. var height = 0
  4944. for (var i = 0; i < lines.length; ++i) {
  4945. lines[i].parent = this$1
  4946. height += lines[i].height
  4947. }
  4948. this.height = height
  4949. }
  4950. LeafChunk.prototype = {
  4951. chunkSize: function chunkSize() { return this.lines.length },
  4952. // Remove the n lines at offset 'at'.
  4953. removeInner: function removeInner(at, n) {
  4954. var this$1 = this;
  4955. for (var i = at, e = at + n; i < e; ++i) {
  4956. var line = this$1.lines[i]
  4957. this$1.height -= line.height
  4958. cleanUpLine(line)
  4959. signalLater(line, "delete")
  4960. }
  4961. this.lines.splice(at, n)
  4962. },
  4963. // Helper used to collapse a small branch into a single leaf.
  4964. collapse: function collapse(lines) {
  4965. lines.push.apply(lines, this.lines)
  4966. },
  4967. // Insert the given array of lines at offset 'at', count them as
  4968. // having the given height.
  4969. insertInner: function insertInner(at, lines, height) {
  4970. var this$1 = this;
  4971. this.height += height
  4972. this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at))
  4973. for (var i = 0; i < lines.length; ++i) { lines[i].parent = this$1 }
  4974. },
  4975. // Used to iterate over a part of the tree.
  4976. iterN: function iterN(at, n, op) {
  4977. var this$1 = this;
  4978. for (var e = at + n; at < e; ++at)
  4979. { if (op(this$1.lines[at])) { return true } }
  4980. }
  4981. }
  4982. function BranchChunk(children) {
  4983. var this$1 = this;
  4984. this.children = children
  4985. var size = 0, height = 0
  4986. for (var i = 0; i < children.length; ++i) {
  4987. var ch = children[i]
  4988. size += ch.chunkSize(); height += ch.height
  4989. ch.parent = this$1
  4990. }
  4991. this.size = size
  4992. this.height = height
  4993. this.parent = null
  4994. }
  4995. BranchChunk.prototype = {
  4996. chunkSize: function chunkSize() { return this.size },
  4997. removeInner: function removeInner(at, n) {
  4998. var this$1 = this;
  4999. this.size -= n
  5000. for (var i = 0; i < this.children.length; ++i) {
  5001. var child = this$1.children[i], sz = child.chunkSize()
  5002. if (at < sz) {
  5003. var rm = Math.min(n, sz - at), oldHeight = child.height
  5004. child.removeInner(at, rm)
  5005. this$1.height -= oldHeight - child.height
  5006. if (sz == rm) { this$1.children.splice(i--, 1); child.parent = null }
  5007. if ((n -= rm) == 0) { break }
  5008. at = 0
  5009. } else { at -= sz }
  5010. }
  5011. // If the result is smaller than 25 lines, ensure that it is a
  5012. // single leaf node.
  5013. if (this.size - n < 25 &&
  5014. (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) {
  5015. var lines = []
  5016. this.collapse(lines)
  5017. this.children = [new LeafChunk(lines)]
  5018. this.children[0].parent = this
  5019. }
  5020. },
  5021. collapse: function collapse(lines) {
  5022. var this$1 = this;
  5023. for (var i = 0; i < this.children.length; ++i) { this$1.children[i].collapse(lines) }
  5024. },
  5025. insertInner: function insertInner(at, lines, height) {
  5026. var this$1 = this;
  5027. this.size += lines.length
  5028. this.height += height
  5029. for (var i = 0; i < this.children.length; ++i) {
  5030. var child = this$1.children[i], sz = child.chunkSize()
  5031. if (at <= sz) {
  5032. child.insertInner(at, lines, height)
  5033. if (child.lines && child.lines.length > 50) {
  5034. // To avoid memory thrashing when child.lines is huge (e.g. first view of a large file), it's never spliced.
  5035. // Instead, small slices are taken. They're taken in order because sequential memory accesses are fastest.
  5036. var remaining = child.lines.length % 25 + 25
  5037. for (var pos = remaining; pos < child.lines.length;) {
  5038. var leaf = new LeafChunk(child.lines.slice(pos, pos += 25))
  5039. child.height -= leaf.height
  5040. this$1.children.splice(++i, 0, leaf)
  5041. leaf.parent = this$1
  5042. }
  5043. child.lines = child.lines.slice(0, remaining)
  5044. this$1.maybeSpill()
  5045. }
  5046. break
  5047. }
  5048. at -= sz
  5049. }
  5050. },
  5051. // When a node has grown, check whether it should be split.
  5052. maybeSpill: function maybeSpill() {
  5053. if (this.children.length <= 10) { return }
  5054. var me = this
  5055. do {
  5056. var spilled = me.children.splice(me.children.length - 5, 5)
  5057. var sibling = new BranchChunk(spilled)
  5058. if (!me.parent) { // Become the parent node
  5059. var copy = new BranchChunk(me.children)
  5060. copy.parent = me
  5061. me.children = [copy, sibling]
  5062. me = copy
  5063. } else {
  5064. me.size -= sibling.size
  5065. me.height -= sibling.height
  5066. var myIndex = indexOf(me.parent.children, me)
  5067. me.parent.children.splice(myIndex + 1, 0, sibling)
  5068. }
  5069. sibling.parent = me.parent
  5070. } while (me.children.length > 10)
  5071. me.parent.maybeSpill()
  5072. },
  5073. iterN: function iterN(at, n, op) {
  5074. var this$1 = this;
  5075. for (var i = 0; i < this.children.length; ++i) {
  5076. var child = this$1.children[i], sz = child.chunkSize()
  5077. if (at < sz) {
  5078. var used = Math.min(n, sz - at)
  5079. if (child.iterN(at, used, op)) { return true }
  5080. if ((n -= used) == 0) { break }
  5081. at = 0
  5082. } else { at -= sz }
  5083. }
  5084. }
  5085. }
  5086. // Line widgets are block elements displayed above or below a line.
  5087. var LineWidget = function(doc, node, options) {
  5088. var this$1 = this;
  5089. if (options) { for (var opt in options) { if (options.hasOwnProperty(opt))
  5090. { this$1[opt] = options[opt] } } }
  5091. this.doc = doc
  5092. this.node = node
  5093. };
  5094. LineWidget.prototype.clear = function () {
  5095. var this$1 = this;
  5096. var cm = this.doc.cm, ws = this.line.widgets, line = this.line, no = lineNo(line)
  5097. if (no == null || !ws) { return }
  5098. for (var i = 0; i < ws.length; ++i) { if (ws[i] == this$1) { ws.splice(i--, 1) } }
  5099. if (!ws.length) { line.widgets = null }
  5100. var height = widgetHeight(this)
  5101. updateLineHeight(line, Math.max(0, line.height - height))
  5102. if (cm) {
  5103. runInOp(cm, function () {
  5104. adjustScrollWhenAboveVisible(cm, line, -height)
  5105. regLineChange(cm, no, "widget")
  5106. })
  5107. signalLater(cm, "lineWidgetCleared", cm, this, no)
  5108. }
  5109. };
  5110. LineWidget.prototype.changed = function () {
  5111. var this$1 = this;
  5112. var oldH = this.height, cm = this.doc.cm, line = this.line
  5113. this.height = null
  5114. var diff = widgetHeight(this) - oldH
  5115. if (!diff) { return }
  5116. updateLineHeight(line, line.height + diff)
  5117. if (cm) {
  5118. runInOp(cm, function () {
  5119. cm.curOp.forceUpdate = true
  5120. adjustScrollWhenAboveVisible(cm, line, diff)
  5121. signalLater(cm, "lineWidgetChanged", cm, this$1, lineNo(line))
  5122. })
  5123. }
  5124. };
  5125. eventMixin(LineWidget)
  5126. function adjustScrollWhenAboveVisible(cm, line, diff) {
  5127. if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop))
  5128. { addToScrollTop(cm, diff) }
  5129. }
  5130. function addLineWidget(doc, handle, node, options) {
  5131. var widget = new LineWidget(doc, node, options)
  5132. var cm = doc.cm
  5133. if (cm && widget.noHScroll) { cm.display.alignWidgets = true }
  5134. changeLine(doc, handle, "widget", function (line) {
  5135. var widgets = line.widgets || (line.widgets = [])
  5136. if (widget.insertAt == null) { widgets.push(widget) }
  5137. else { widgets.splice(Math.min(widgets.length - 1, Math.max(0, widget.insertAt)), 0, widget) }
  5138. widget.line = line
  5139. if (cm && !lineIsHidden(doc, line)) {
  5140. var aboveVisible = heightAtLine(line) < doc.scrollTop
  5141. updateLineHeight(line, line.height + widgetHeight(widget))
  5142. if (aboveVisible) { addToScrollTop(cm, widget.height) }
  5143. cm.curOp.forceUpdate = true
  5144. }
  5145. return true
  5146. })
  5147. signalLater(cm, "lineWidgetAdded", cm, widget, typeof handle == "number" ? handle : lineNo(handle))
  5148. return widget
  5149. }
  5150. // TEXTMARKERS
  5151. // Created with markText and setBookmark methods. A TextMarker is a
  5152. // handle that can be used to clear or find a marked position in the
  5153. // document. Line objects hold arrays (markedSpans) containing
  5154. // {from, to, marker} object pointing to such marker objects, and
  5155. // indicating that such a marker is present on that line. Multiple
  5156. // lines may point to the same marker when it spans across lines.
  5157. // The spans will have null for their from/to properties when the
  5158. // marker continues beyond the start/end of the line. Markers have
  5159. // links back to the lines they currently touch.
  5160. // Collapsed markers have unique ids, in order to be able to order
  5161. // them, which is needed for uniquely determining an outer marker
  5162. // when they overlap (they may nest, but not partially overlap).
  5163. var nextMarkerId = 0
  5164. var TextMarker = function(doc, type) {
  5165. this.lines = []
  5166. this.type = type
  5167. this.doc = doc
  5168. this.id = ++nextMarkerId
  5169. };
  5170. // Clear the marker.
  5171. TextMarker.prototype.clear = function () {
  5172. var this$1 = this;
  5173. if (this.explicitlyCleared) { return }
  5174. var cm = this.doc.cm, withOp = cm && !cm.curOp
  5175. if (withOp) { startOperation(cm) }
  5176. if (hasHandler(this, "clear")) {
  5177. var found = this.find()
  5178. if (found) { signalLater(this, "clear", found.from, found.to) }
  5179. }
  5180. var min = null, max = null
  5181. for (var i = 0; i < this.lines.length; ++i) {
  5182. var line = this$1.lines[i]
  5183. var span = getMarkedSpanFor(line.markedSpans, this$1)
  5184. if (cm && !this$1.collapsed) { regLineChange(cm, lineNo(line), "text") }
  5185. else if (cm) {
  5186. if (span.to != null) { max = lineNo(line) }
  5187. if (span.from != null) { min = lineNo(line) }
  5188. }
  5189. line.markedSpans = removeMarkedSpan(line.markedSpans, span)
  5190. if (span.from == null && this$1.collapsed && !lineIsHidden(this$1.doc, line) && cm)
  5191. { updateLineHeight(line, textHeight(cm.display)) }
  5192. }
  5193. if (cm && this.collapsed && !cm.options.lineWrapping) { for (var i$1 = 0; i$1 < this.lines.length; ++i$1) {
  5194. var visual = visualLine(this$1.lines[i$1]), len = lineLength(visual)
  5195. if (len > cm.display.maxLineLength) {
  5196. cm.display.maxLine = visual
  5197. cm.display.maxLineLength = len
  5198. cm.display.maxLineChanged = true
  5199. }
  5200. } }
  5201. if (min != null && cm && this.collapsed) { regChange(cm, min, max + 1) }
  5202. this.lines.length = 0
  5203. this.explicitlyCleared = true
  5204. if (this.atomic && this.doc.cantEdit) {
  5205. this.doc.cantEdit = false
  5206. if (cm) { reCheckSelection(cm.doc) }
  5207. }
  5208. if (cm) { signalLater(cm, "markerCleared", cm, this, min, max) }
  5209. if (withOp) { endOperation(cm) }
  5210. if (this.parent) { this.parent.clear() }
  5211. };
  5212. // Find the position of the marker in the document. Returns a {from,
  5213. // to} object by default. Side can be passed to get a specific side
  5214. // -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the
  5215. // Pos objects returned contain a line object, rather than a line
  5216. // number (used to prevent looking up the same line twice).
  5217. TextMarker.prototype.find = function (side, lineObj) {
  5218. var this$1 = this;
  5219. if (side == null && this.type == "bookmark") { side = 1 }
  5220. var from, to
  5221. for (var i = 0; i < this.lines.length; ++i) {
  5222. var line = this$1.lines[i]
  5223. var span = getMarkedSpanFor(line.markedSpans, this$1)
  5224. if (span.from != null) {
  5225. from = Pos(lineObj ? line : lineNo(line), span.from)
  5226. if (side == -1) { return from }
  5227. }
  5228. if (span.to != null) {
  5229. to = Pos(lineObj ? line : lineNo(line), span.to)
  5230. if (side == 1) { return to }
  5231. }
  5232. }
  5233. return from && {from: from, to: to}
  5234. };
  5235. // Signals that the marker's widget changed, and surrounding layout
  5236. // should be recomputed.
  5237. TextMarker.prototype.changed = function () {
  5238. var this$1 = this;
  5239. var pos = this.find(-1, true), widget = this, cm = this.doc.cm
  5240. if (!pos || !cm) { return }
  5241. runInOp(cm, function () {
  5242. var line = pos.line, lineN = lineNo(pos.line)
  5243. var view = findViewForLine(cm, lineN)
  5244. if (view) {
  5245. clearLineMeasurementCacheFor(view)
  5246. cm.curOp.selectionChanged = cm.curOp.forceUpdate = true
  5247. }
  5248. cm.curOp.updateMaxLine = true
  5249. if (!lineIsHidden(widget.doc, line) && widget.height != null) {
  5250. var oldHeight = widget.height
  5251. widget.height = null
  5252. var dHeight = widgetHeight(widget) - oldHeight
  5253. if (dHeight)
  5254. { updateLineHeight(line, line.height + dHeight) }
  5255. }
  5256. signalLater(cm, "markerChanged", cm, this$1)
  5257. })
  5258. };
  5259. TextMarker.prototype.attachLine = function (line) {
  5260. if (!this.lines.length && this.doc.cm) {
  5261. var op = this.doc.cm.curOp
  5262. if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1)
  5263. { (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this) }
  5264. }
  5265. this.lines.push(line)
  5266. };
  5267. TextMarker.prototype.detachLine = function (line) {
  5268. this.lines.splice(indexOf(this.lines, line), 1)
  5269. if (!this.lines.length && this.doc.cm) {
  5270. var op = this.doc.cm.curOp
  5271. ;(op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this)
  5272. }
  5273. };
  5274. eventMixin(TextMarker)
  5275. // Create a marker, wire it up to the right lines, and
  5276. function markText(doc, from, to, options, type) {
  5277. // Shared markers (across linked documents) are handled separately
  5278. // (markTextShared will call out to this again, once per
  5279. // document).
  5280. if (options && options.shared) { return markTextShared(doc, from, to, options, type) }
  5281. // Ensure we are in an operation.
  5282. if (doc.cm && !doc.cm.curOp) { return operation(doc.cm, markText)(doc, from, to, options, type) }
  5283. var marker = new TextMarker(doc, type), diff = cmp(from, to)
  5284. if (options) { copyObj(options, marker, false) }
  5285. // Don't connect empty markers unless clearWhenEmpty is false
  5286. if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false)
  5287. { return marker }
  5288. if (marker.replacedWith) {
  5289. // Showing up as a widget implies collapsed (widget replaces text)
  5290. marker.collapsed = true
  5291. marker.widgetNode = eltP("span", [marker.replacedWith], "CodeMirror-widget")
  5292. if (!options.handleMouseEvents) { marker.widgetNode.setAttribute("cm-ignore-events", "true") }
  5293. if (options.insertLeft) { marker.widgetNode.insertLeft = true }
  5294. }
  5295. if (marker.collapsed) {
  5296. if (conflictingCollapsedRange(doc, from.line, from, to, marker) ||
  5297. from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker))
  5298. { throw new Error("Inserting collapsed marker partially overlapping an existing one") }
  5299. seeCollapsedSpans()
  5300. }
  5301. if (marker.addToHistory)
  5302. { addChangeToHistory(doc, {from: from, to: to, origin: "markText"}, doc.sel, NaN) }
  5303. var curLine = from.line, cm = doc.cm, updateMaxLine
  5304. doc.iter(curLine, to.line + 1, function (line) {
  5305. if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine)
  5306. { updateMaxLine = true }
  5307. if (marker.collapsed && curLine != from.line) { updateLineHeight(line, 0) }
  5308. addMarkedSpan(line, new MarkedSpan(marker,
  5309. curLine == from.line ? from.ch : null,
  5310. curLine == to.line ? to.ch : null))
  5311. ++curLine
  5312. })
  5313. // lineIsHidden depends on the presence of the spans, so needs a second pass
  5314. if (marker.collapsed) { doc.iter(from.line, to.line + 1, function (line) {
  5315. if (lineIsHidden(doc, line)) { updateLineHeight(line, 0) }
  5316. }) }
  5317. if (marker.clearOnEnter) { on(marker, "beforeCursorEnter", function () { return marker.clear(); }) }
  5318. if (marker.readOnly) {
  5319. seeReadOnlySpans()
  5320. if (doc.history.done.length || doc.history.undone.length)
  5321. { doc.clearHistory() }
  5322. }
  5323. if (marker.collapsed) {
  5324. marker.id = ++nextMarkerId
  5325. marker.atomic = true
  5326. }
  5327. if (cm) {
  5328. // Sync editor state
  5329. if (updateMaxLine) { cm.curOp.updateMaxLine = true }
  5330. if (marker.collapsed)
  5331. { regChange(cm, from.line, to.line + 1) }
  5332. else if (marker.className || marker.title || marker.startStyle || marker.endStyle || marker.css)
  5333. { for (var i = from.line; i <= to.line; i++) { regLineChange(cm, i, "text") } }
  5334. if (marker.atomic) { reCheckSelection(cm.doc) }
  5335. signalLater(cm, "markerAdded", cm, marker)
  5336. }
  5337. return marker
  5338. }
  5339. // SHARED TEXTMARKERS
  5340. // A shared marker spans multiple linked documents. It is
  5341. // implemented as a meta-marker-object controlling multiple normal
  5342. // markers.
  5343. var SharedTextMarker = function(markers, primary) {
  5344. var this$1 = this;
  5345. this.markers = markers
  5346. this.primary = primary
  5347. for (var i = 0; i < markers.length; ++i)
  5348. { markers[i].parent = this$1 }
  5349. };
  5350. SharedTextMarker.prototype.clear = function () {
  5351. var this$1 = this;
  5352. if (this.explicitlyCleared) { return }
  5353. this.explicitlyCleared = true
  5354. for (var i = 0; i < this.markers.length; ++i)
  5355. { this$1.markers[i].clear() }
  5356. signalLater(this, "clear")
  5357. };
  5358. SharedTextMarker.prototype.find = function (side, lineObj) {
  5359. return this.primary.find(side, lineObj)
  5360. };
  5361. eventMixin(SharedTextMarker)
  5362. function markTextShared(doc, from, to, options, type) {
  5363. options = copyObj(options)
  5364. options.shared = false
  5365. var markers = [markText(doc, from, to, options, type)], primary = markers[0]
  5366. var widget = options.widgetNode
  5367. linkedDocs(doc, function (doc) {
  5368. if (widget) { options.widgetNode = widget.cloneNode(true) }
  5369. markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type))
  5370. for (var i = 0; i < doc.linked.length; ++i)
  5371. { if (doc.linked[i].isParent) { return } }
  5372. primary = lst(markers)
  5373. })
  5374. return new SharedTextMarker(markers, primary)
  5375. }
  5376. function findSharedMarkers(doc) {
  5377. return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())), function (m) { return m.parent; })
  5378. }
  5379. function copySharedMarkers(doc, markers) {
  5380. for (var i = 0; i < markers.length; i++) {
  5381. var marker = markers[i], pos = marker.find()
  5382. var mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to)
  5383. if (cmp(mFrom, mTo)) {
  5384. var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type)
  5385. marker.markers.push(subMark)
  5386. subMark.parent = marker
  5387. }
  5388. }
  5389. }
  5390. function detachSharedMarkers(markers) {
  5391. var loop = function ( i ) {
  5392. var marker = markers[i], linked = [marker.primary.doc]
  5393. linkedDocs(marker.primary.doc, function (d) { return linked.push(d); })
  5394. for (var j = 0; j < marker.markers.length; j++) {
  5395. var subMarker = marker.markers[j]
  5396. if (indexOf(linked, subMarker.doc) == -1) {
  5397. subMarker.parent = null
  5398. marker.markers.splice(j--, 1)
  5399. }
  5400. }
  5401. };
  5402. for (var i = 0; i < markers.length; i++) loop( i );
  5403. }
  5404. var nextDocId = 0
  5405. var Doc = function(text, mode, firstLine, lineSep, direction) {
  5406. if (!(this instanceof Doc)) { return new Doc(text, mode, firstLine, lineSep, direction) }
  5407. if (firstLine == null) { firstLine = 0 }
  5408. BranchChunk.call(this, [new LeafChunk([new Line("", null)])])
  5409. this.first = firstLine
  5410. this.scrollTop = this.scrollLeft = 0
  5411. this.cantEdit = false
  5412. this.cleanGeneration = 1
  5413. this.modeFrontier = this.highlightFrontier = firstLine
  5414. var start = Pos(firstLine, 0)
  5415. this.sel = simpleSelection(start)
  5416. this.history = new History(null)
  5417. this.id = ++nextDocId
  5418. this.modeOption = mode
  5419. this.lineSep = lineSep
  5420. this.direction = (direction == "rtl") ? "rtl" : "ltr"
  5421. this.extend = false
  5422. if (typeof text == "string") { text = this.splitLines(text) }
  5423. updateDoc(this, {from: start, to: start, text: text})
  5424. setSelection(this, simpleSelection(start), sel_dontScroll)
  5425. }
  5426. Doc.prototype = createObj(BranchChunk.prototype, {
  5427. constructor: Doc,
  5428. // Iterate over the document. Supports two forms -- with only one
  5429. // argument, it calls that for each line in the document. With
  5430. // three, it iterates over the range given by the first two (with
  5431. // the second being non-inclusive).
  5432. iter: function(from, to, op) {
  5433. if (op) { this.iterN(from - this.first, to - from, op) }
  5434. else { this.iterN(this.first, this.first + this.size, from) }
  5435. },
  5436. // Non-public interface for adding and removing lines.
  5437. insert: function(at, lines) {
  5438. var height = 0
  5439. for (var i = 0; i < lines.length; ++i) { height += lines[i].height }
  5440. this.insertInner(at - this.first, lines, height)
  5441. },
  5442. remove: function(at, n) { this.removeInner(at - this.first, n) },
  5443. // From here, the methods are part of the public interface. Most
  5444. // are also available from CodeMirror (editor) instances.
  5445. getValue: function(lineSep) {
  5446. var lines = getLines(this, this.first, this.first + this.size)
  5447. if (lineSep === false) { return lines }
  5448. return lines.join(lineSep || this.lineSeparator())
  5449. },
  5450. setValue: docMethodOp(function(code) {
  5451. var top = Pos(this.first, 0), last = this.first + this.size - 1
  5452. makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length),
  5453. text: this.splitLines(code), origin: "setValue", full: true}, true)
  5454. if (this.cm) { scrollToCoords(this.cm, 0, 0) }
  5455. setSelection(this, simpleSelection(top), sel_dontScroll)
  5456. }),
  5457. replaceRange: function(code, from, to, origin) {
  5458. from = clipPos(this, from)
  5459. to = to ? clipPos(this, to) : from
  5460. replaceRange(this, code, from, to, origin)
  5461. },
  5462. getRange: function(from, to, lineSep) {
  5463. var lines = getBetween(this, clipPos(this, from), clipPos(this, to))
  5464. if (lineSep === false) { return lines }
  5465. return lines.join(lineSep || this.lineSeparator())
  5466. },
  5467. getLine: function(line) {var l = this.getLineHandle(line); return l && l.text},
  5468. getLineHandle: function(line) {if (isLine(this, line)) { return getLine(this, line) }},
  5469. getLineNumber: function(line) {return lineNo(line)},
  5470. getLineHandleVisualStart: function(line) {
  5471. if (typeof line == "number") { line = getLine(this, line) }
  5472. return visualLine(line)
  5473. },
  5474. lineCount: function() {return this.size},
  5475. firstLine: function() {return this.first},
  5476. lastLine: function() {return this.first + this.size - 1},
  5477. clipPos: function(pos) {return clipPos(this, pos)},
  5478. getCursor: function(start) {
  5479. var range = this.sel.primary(), pos
  5480. if (start == null || start == "head") { pos = range.head }
  5481. else if (start == "anchor") { pos = range.anchor }
  5482. else if (start == "end" || start == "to" || start === false) { pos = range.to() }
  5483. else { pos = range.from() }
  5484. return pos
  5485. },
  5486. listSelections: function() { return this.sel.ranges },
  5487. somethingSelected: function() {return this.sel.somethingSelected()},
  5488. setCursor: docMethodOp(function(line, ch, options) {
  5489. setSimpleSelection(this, clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line), null, options)
  5490. }),
  5491. setSelection: docMethodOp(function(anchor, head, options) {
  5492. setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options)
  5493. }),
  5494. extendSelection: docMethodOp(function(head, other, options) {
  5495. extendSelection(this, clipPos(this, head), other && clipPos(this, other), options)
  5496. }),
  5497. extendSelections: docMethodOp(function(heads, options) {
  5498. extendSelections(this, clipPosArray(this, heads), options)
  5499. }),
  5500. extendSelectionsBy: docMethodOp(function(f, options) {
  5501. var heads = map(this.sel.ranges, f)
  5502. extendSelections(this, clipPosArray(this, heads), options)
  5503. }),
  5504. setSelections: docMethodOp(function(ranges, primary, options) {
  5505. var this$1 = this;
  5506. if (!ranges.length) { return }
  5507. var out = []
  5508. for (var i = 0; i < ranges.length; i++)
  5509. { out[i] = new Range(clipPos(this$1, ranges[i].anchor),
  5510. clipPos(this$1, ranges[i].head)) }
  5511. if (primary == null) { primary = Math.min(ranges.length - 1, this.sel.primIndex) }
  5512. setSelection(this, normalizeSelection(out, primary), options)
  5513. }),
  5514. addSelection: docMethodOp(function(anchor, head, options) {
  5515. var ranges = this.sel.ranges.slice(0)
  5516. ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor)))
  5517. setSelection(this, normalizeSelection(ranges, ranges.length - 1), options)
  5518. }),
  5519. getSelection: function(lineSep) {
  5520. var this$1 = this;
  5521. var ranges = this.sel.ranges, lines
  5522. for (var i = 0; i < ranges.length; i++) {
  5523. var sel = getBetween(this$1, ranges[i].from(), ranges[i].to())
  5524. lines = lines ? lines.concat(sel) : sel
  5525. }
  5526. if (lineSep === false) { return lines }
  5527. else { return lines.join(lineSep || this.lineSeparator()) }
  5528. },
  5529. getSelections: function(lineSep) {
  5530. var this$1 = this;
  5531. var parts = [], ranges = this.sel.ranges
  5532. for (var i = 0; i < ranges.length; i++) {
  5533. var sel = getBetween(this$1, ranges[i].from(), ranges[i].to())
  5534. if (lineSep !== false) { sel = sel.join(lineSep || this$1.lineSeparator()) }
  5535. parts[i] = sel
  5536. }
  5537. return parts
  5538. },
  5539. replaceSelection: function(code, collapse, origin) {
  5540. var dup = []
  5541. for (var i = 0; i < this.sel.ranges.length; i++)
  5542. { dup[i] = code }
  5543. this.replaceSelections(dup, collapse, origin || "+input")
  5544. },
  5545. replaceSelections: docMethodOp(function(code, collapse, origin) {
  5546. var this$1 = this;
  5547. var changes = [], sel = this.sel
  5548. for (var i = 0; i < sel.ranges.length; i++) {
  5549. var range = sel.ranges[i]
  5550. changes[i] = {from: range.from(), to: range.to(), text: this$1.splitLines(code[i]), origin: origin}
  5551. }
  5552. var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse)
  5553. for (var i$1 = changes.length - 1; i$1 >= 0; i$1--)
  5554. { makeChange(this$1, changes[i$1]) }
  5555. if (newSel) { setSelectionReplaceHistory(this, newSel) }
  5556. else if (this.cm) { ensureCursorVisible(this.cm) }
  5557. }),
  5558. undo: docMethodOp(function() {makeChangeFromHistory(this, "undo")}),
  5559. redo: docMethodOp(function() {makeChangeFromHistory(this, "redo")}),
  5560. undoSelection: docMethodOp(function() {makeChangeFromHistory(this, "undo", true)}),
  5561. redoSelection: docMethodOp(function() {makeChangeFromHistory(this, "redo", true)}),
  5562. setExtending: function(val) {this.extend = val},
  5563. getExtending: function() {return this.extend},
  5564. historySize: function() {
  5565. var hist = this.history, done = 0, undone = 0
  5566. for (var i = 0; i < hist.done.length; i++) { if (!hist.done[i].ranges) { ++done } }
  5567. for (var i$1 = 0; i$1 < hist.undone.length; i$1++) { if (!hist.undone[i$1].ranges) { ++undone } }
  5568. return {undo: done, redo: undone}
  5569. },
  5570. clearHistory: function() {this.history = new History(this.history.maxGeneration)},
  5571. markClean: function() {
  5572. this.cleanGeneration = this.changeGeneration(true)
  5573. },
  5574. changeGeneration: function(forceSplit) {
  5575. if (forceSplit)
  5576. { this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null }
  5577. return this.history.generation
  5578. },
  5579. isClean: function (gen) {
  5580. return this.history.generation == (gen || this.cleanGeneration)
  5581. },
  5582. getHistory: function() {
  5583. return {done: copyHistoryArray(this.history.done),
  5584. undone: copyHistoryArray(this.history.undone)}
  5585. },
  5586. setHistory: function(histData) {
  5587. var hist = this.history = new History(this.history.maxGeneration)
  5588. hist.done = copyHistoryArray(histData.done.slice(0), null, true)
  5589. hist.undone = copyHistoryArray(histData.undone.slice(0), null, true)
  5590. },
  5591. setGutterMarker: docMethodOp(function(line, gutterID, value) {
  5592. return changeLine(this, line, "gutter", function (line) {
  5593. var markers = line.gutterMarkers || (line.gutterMarkers = {})
  5594. markers[gutterID] = value
  5595. if (!value && isEmpty(markers)) { line.gutterMarkers = null }
  5596. return true
  5597. })
  5598. }),
  5599. clearGutter: docMethodOp(function(gutterID) {
  5600. var this$1 = this;
  5601. this.iter(function (line) {
  5602. if (line.gutterMarkers && line.gutterMarkers[gutterID]) {
  5603. changeLine(this$1, line, "gutter", function () {
  5604. line.gutterMarkers[gutterID] = null
  5605. if (isEmpty(line.gutterMarkers)) { line.gutterMarkers = null }
  5606. return true
  5607. })
  5608. }
  5609. })
  5610. }),
  5611. lineInfo: function(line) {
  5612. var n
  5613. if (typeof line == "number") {
  5614. if (!isLine(this, line)) { return null }
  5615. n = line
  5616. line = getLine(this, line)
  5617. if (!line) { return null }
  5618. } else {
  5619. n = lineNo(line)
  5620. if (n == null) { return null }
  5621. }
  5622. return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers,
  5623. textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass,
  5624. widgets: line.widgets}
  5625. },
  5626. addLineClass: docMethodOp(function(handle, where, cls) {
  5627. return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) {
  5628. var prop = where == "text" ? "textClass"
  5629. : where == "background" ? "bgClass"
  5630. : where == "gutter" ? "gutterClass" : "wrapClass"
  5631. if (!line[prop]) { line[prop] = cls }
  5632. else if (classTest(cls).test(line[prop])) { return false }
  5633. else { line[prop] += " " + cls }
  5634. return true
  5635. })
  5636. }),
  5637. removeLineClass: docMethodOp(function(handle, where, cls) {
  5638. return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) {
  5639. var prop = where == "text" ? "textClass"
  5640. : where == "background" ? "bgClass"
  5641. : where == "gutter" ? "gutterClass" : "wrapClass"
  5642. var cur = line[prop]
  5643. if (!cur) { return false }
  5644. else if (cls == null) { line[prop] = null }
  5645. else {
  5646. var found = cur.match(classTest(cls))
  5647. if (!found) { return false }
  5648. var end = found.index + found[0].length
  5649. line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null
  5650. }
  5651. return true
  5652. })
  5653. }),
  5654. addLineWidget: docMethodOp(function(handle, node, options) {
  5655. return addLineWidget(this, handle, node, options)
  5656. }),
  5657. removeLineWidget: function(widget) { widget.clear() },
  5658. markText: function(from, to, options) {
  5659. return markText(this, clipPos(this, from), clipPos(this, to), options, options && options.type || "range")
  5660. },
  5661. setBookmark: function(pos, options) {
  5662. var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options),
  5663. insertLeft: options && options.insertLeft,
  5664. clearWhenEmpty: false, shared: options && options.shared,
  5665. handleMouseEvents: options && options.handleMouseEvents}
  5666. pos = clipPos(this, pos)
  5667. return markText(this, pos, pos, realOpts, "bookmark")
  5668. },
  5669. findMarksAt: function(pos) {
  5670. pos = clipPos(this, pos)
  5671. var markers = [], spans = getLine(this, pos.line).markedSpans
  5672. if (spans) { for (var i = 0; i < spans.length; ++i) {
  5673. var span = spans[i]
  5674. if ((span.from == null || span.from <= pos.ch) &&
  5675. (span.to == null || span.to >= pos.ch))
  5676. { markers.push(span.marker.parent || span.marker) }
  5677. } }
  5678. return markers
  5679. },
  5680. findMarks: function(from, to, filter) {
  5681. from = clipPos(this, from); to = clipPos(this, to)
  5682. var found = [], lineNo = from.line
  5683. this.iter(from.line, to.line + 1, function (line) {
  5684. var spans = line.markedSpans
  5685. if (spans) { for (var i = 0; i < spans.length; i++) {
  5686. var span = spans[i]
  5687. if (!(span.to != null && lineNo == from.line && from.ch >= span.to ||
  5688. span.from == null && lineNo != from.line ||
  5689. span.from != null && lineNo == to.line && span.from >= to.ch) &&
  5690. (!filter || filter(span.marker)))
  5691. { found.push(span.marker.parent || span.marker) }
  5692. } }
  5693. ++lineNo
  5694. })
  5695. return found
  5696. },
  5697. getAllMarks: function() {
  5698. var markers = []
  5699. this.iter(function (line) {
  5700. var sps = line.markedSpans
  5701. if (sps) { for (var i = 0; i < sps.length; ++i)
  5702. { if (sps[i].from != null) { markers.push(sps[i].marker) } } }
  5703. })
  5704. return markers
  5705. },
  5706. posFromIndex: function(off) {
  5707. var ch, lineNo = this.first, sepSize = this.lineSeparator().length
  5708. this.iter(function (line) {
  5709. var sz = line.text.length + sepSize
  5710. if (sz > off) { ch = off; return true }
  5711. off -= sz
  5712. ++lineNo
  5713. })
  5714. return clipPos(this, Pos(lineNo, ch))
  5715. },
  5716. indexFromPos: function (coords) {
  5717. coords = clipPos(this, coords)
  5718. var index = coords.ch
  5719. if (coords.line < this.first || coords.ch < 0) { return 0 }
  5720. var sepSize = this.lineSeparator().length
  5721. this.iter(this.first, coords.line, function (line) { // iter aborts when callback returns a truthy value
  5722. index += line.text.length + sepSize
  5723. })
  5724. return index
  5725. },
  5726. copy: function(copyHistory) {
  5727. var doc = new Doc(getLines(this, this.first, this.first + this.size),
  5728. this.modeOption, this.first, this.lineSep, this.direction)
  5729. doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft
  5730. doc.sel = this.sel
  5731. doc.extend = false
  5732. if (copyHistory) {
  5733. doc.history.undoDepth = this.history.undoDepth
  5734. doc.setHistory(this.getHistory())
  5735. }
  5736. return doc
  5737. },
  5738. linkedDoc: function(options) {
  5739. if (!options) { options = {} }
  5740. var from = this.first, to = this.first + this.size
  5741. if (options.from != null && options.from > from) { from = options.from }
  5742. if (options.to != null && options.to < to) { to = options.to }
  5743. var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from, this.lineSep, this.direction)
  5744. if (options.sharedHist) { copy.history = this.history
  5745. ; }(this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist})
  5746. copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}]
  5747. copySharedMarkers(copy, findSharedMarkers(this))
  5748. return copy
  5749. },
  5750. unlinkDoc: function(other) {
  5751. var this$1 = this;
  5752. if (other instanceof CodeMirror) { other = other.doc }
  5753. if (this.linked) { for (var i = 0; i < this.linked.length; ++i) {
  5754. var link = this$1.linked[i]
  5755. if (link.doc != other) { continue }
  5756. this$1.linked.splice(i, 1)
  5757. other.unlinkDoc(this$1)
  5758. detachSharedMarkers(findSharedMarkers(this$1))
  5759. break
  5760. } }
  5761. // If the histories were shared, split them again
  5762. if (other.history == this.history) {
  5763. var splitIds = [other.id]
  5764. linkedDocs(other, function (doc) { return splitIds.push(doc.id); }, true)
  5765. other.history = new History(null)
  5766. other.history.done = copyHistoryArray(this.history.done, splitIds)
  5767. other.history.undone = copyHistoryArray(this.history.undone, splitIds)
  5768. }
  5769. },
  5770. iterLinkedDocs: function(f) {linkedDocs(this, f)},
  5771. getMode: function() {return this.mode},
  5772. getEditor: function() {return this.cm},
  5773. splitLines: function(str) {
  5774. if (this.lineSep) { return str.split(this.lineSep) }
  5775. return splitLinesAuto(str)
  5776. },
  5777. lineSeparator: function() { return this.lineSep || "\n" },
  5778. setDirection: docMethodOp(function (dir) {
  5779. if (dir != "rtl") { dir = "ltr" }
  5780. if (dir == this.direction) { return }
  5781. this.direction = dir
  5782. this.iter(function (line) { return line.order = null; })
  5783. if (this.cm) { directionChanged(this.cm) }
  5784. })
  5785. })
  5786. // Public alias.
  5787. Doc.prototype.eachLine = Doc.prototype.iter
  5788. // Kludge to work around strange IE behavior where it'll sometimes
  5789. // re-fire a series of drag-related events right after the drop (#1551)
  5790. var lastDrop = 0
  5791. function onDrop(e) {
  5792. var cm = this
  5793. clearDragCursor(cm)
  5794. if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e))
  5795. { return }
  5796. e_preventDefault(e)
  5797. if (ie) { lastDrop = +new Date }
  5798. var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files
  5799. if (!pos || cm.isReadOnly()) { return }
  5800. // Might be a file drop, in which case we simply extract the text
  5801. // and insert it.
  5802. if (files && files.length && window.FileReader && window.File) {
  5803. var n = files.length, text = Array(n), read = 0
  5804. var loadFile = function (file, i) {
  5805. if (cm.options.allowDropFileTypes &&
  5806. indexOf(cm.options.allowDropFileTypes, file.type) == -1)
  5807. { return }
  5808. var reader = new FileReader
  5809. reader.onload = operation(cm, function () {
  5810. var content = reader.result
  5811. if (/[\x00-\x08\x0e-\x1f]{2}/.test(content)) { content = "" }
  5812. text[i] = content
  5813. if (++read == n) {
  5814. pos = clipPos(cm.doc, pos)
  5815. var change = {from: pos, to: pos,
  5816. text: cm.doc.splitLines(text.join(cm.doc.lineSeparator())),
  5817. origin: "paste"}
  5818. makeChange(cm.doc, change)
  5819. setSelectionReplaceHistory(cm.doc, simpleSelection(pos, changeEnd(change)))
  5820. }
  5821. })
  5822. reader.readAsText(file)
  5823. }
  5824. for (var i = 0; i < n; ++i) { loadFile(files[i], i) }
  5825. } else { // Normal drop
  5826. // Don't do a replace if the drop happened inside of the selected text.
  5827. if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) {
  5828. cm.state.draggingText(e)
  5829. // Ensure the editor is re-focused
  5830. setTimeout(function () { return cm.display.input.focus(); }, 20)
  5831. return
  5832. }
  5833. try {
  5834. var text$1 = e.dataTransfer.getData("Text")
  5835. if (text$1) {
  5836. var selected
  5837. if (cm.state.draggingText && !cm.state.draggingText.copy)
  5838. { selected = cm.listSelections() }
  5839. setSelectionNoUndo(cm.doc, simpleSelection(pos, pos))
  5840. if (selected) { for (var i$1 = 0; i$1 < selected.length; ++i$1)
  5841. { replaceRange(cm.doc, "", selected[i$1].anchor, selected[i$1].head, "drag") } }
  5842. cm.replaceSelection(text$1, "around", "paste")
  5843. cm.display.input.focus()
  5844. }
  5845. }
  5846. catch(e){}
  5847. }
  5848. }
  5849. function onDragStart(cm, e) {
  5850. if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return }
  5851. if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) { return }
  5852. e.dataTransfer.setData("Text", cm.getSelection())
  5853. e.dataTransfer.effectAllowed = "copyMove"
  5854. // Use dummy image instead of default browsers image.
  5855. // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there.
  5856. if (e.dataTransfer.setDragImage && !safari) {
  5857. var img = elt("img", null, null, "position: fixed; left: 0; top: 0;")
  5858. img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="
  5859. if (presto) {
  5860. img.width = img.height = 1
  5861. cm.display.wrapper.appendChild(img)
  5862. // Force a relayout, or Opera won't use our image for some obscure reason
  5863. img._top = img.offsetTop
  5864. }
  5865. e.dataTransfer.setDragImage(img, 0, 0)
  5866. if (presto) { img.parentNode.removeChild(img) }
  5867. }
  5868. }
  5869. function onDragOver(cm, e) {
  5870. var pos = posFromMouse(cm, e)
  5871. if (!pos) { return }
  5872. var frag = document.createDocumentFragment()
  5873. drawSelectionCursor(cm, pos, frag)
  5874. if (!cm.display.dragCursor) {
  5875. cm.display.dragCursor = elt("div", null, "CodeMirror-cursors CodeMirror-dragcursors")
  5876. cm.display.lineSpace.insertBefore(cm.display.dragCursor, cm.display.cursorDiv)
  5877. }
  5878. removeChildrenAndAdd(cm.display.dragCursor, frag)
  5879. }
  5880. function clearDragCursor(cm) {
  5881. if (cm.display.dragCursor) {
  5882. cm.display.lineSpace.removeChild(cm.display.dragCursor)
  5883. cm.display.dragCursor = null
  5884. }
  5885. }
  5886. // These must be handled carefully, because naively registering a
  5887. // handler for each editor will cause the editors to never be
  5888. // garbage collected.
  5889. function forEachCodeMirror(f) {
  5890. if (!document.getElementsByClassName) { return }
  5891. var byClass = document.getElementsByClassName("CodeMirror")
  5892. for (var i = 0; i < byClass.length; i++) {
  5893. var cm = byClass[i].CodeMirror
  5894. if (cm) { f(cm) }
  5895. }
  5896. }
  5897. var globalsRegistered = false
  5898. function ensureGlobalHandlers() {
  5899. if (globalsRegistered) { return }
  5900. registerGlobalHandlers()
  5901. globalsRegistered = true
  5902. }
  5903. function registerGlobalHandlers() {
  5904. // When the window resizes, we need to refresh active editors.
  5905. var resizeTimer
  5906. on(window, "resize", function () {
  5907. if (resizeTimer == null) { resizeTimer = setTimeout(function () {
  5908. resizeTimer = null
  5909. forEachCodeMirror(onResize)
  5910. }, 100) }
  5911. })
  5912. // When the window loses focus, we want to show the editor as blurred
  5913. on(window, "blur", function () { return forEachCodeMirror(onBlur); })
  5914. }
  5915. // Called when the window resizes
  5916. function onResize(cm) {
  5917. var d = cm.display
  5918. if (d.lastWrapHeight == d.wrapper.clientHeight && d.lastWrapWidth == d.wrapper.clientWidth)
  5919. { return }
  5920. // Might be a text scaling operation, clear size caches.
  5921. d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null
  5922. d.scrollbarsClipped = false
  5923. cm.setSize()
  5924. }
  5925. var keyNames = {
  5926. 3: "Enter", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt",
  5927. 19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End",
  5928. 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert",
  5929. 46: "Delete", 59: ";", 61: "=", 91: "Mod", 92: "Mod", 93: "Mod",
  5930. 106: "*", 107: "=", 109: "-", 110: ".", 111: "/", 127: "Delete",
  5931. 173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\",
  5932. 221: "]", 222: "'", 63232: "Up", 63233: "Down", 63234: "Left", 63235: "Right", 63272: "Delete",
  5933. 63273: "Home", 63275: "End", 63276: "PageUp", 63277: "PageDown", 63302: "Insert"
  5934. }
  5935. // Number keys
  5936. for (var i = 0; i < 10; i++) { keyNames[i + 48] = keyNames[i + 96] = String(i) }
  5937. // Alphabetic keys
  5938. for (var i$1 = 65; i$1 <= 90; i$1++) { keyNames[i$1] = String.fromCharCode(i$1) }
  5939. // Function keys
  5940. for (var i$2 = 1; i$2 <= 12; i$2++) { keyNames[i$2 + 111] = keyNames[i$2 + 63235] = "F" + i$2 }
  5941. var keyMap = {}
  5942. keyMap.basic = {
  5943. "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown",
  5944. "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown",
  5945. "Delete": "delCharAfter", "Backspace": "delCharBefore", "Shift-Backspace": "delCharBefore",
  5946. "Tab": "defaultTab", "Shift-Tab": "indentAuto",
  5947. "Enter": "newlineAndIndent", "Insert": "toggleOverwrite",
  5948. "Esc": "singleSelection"
  5949. }
  5950. // Note that the save and find-related commands aren't defined by
  5951. // default. User code or addons can define them. Unknown commands
  5952. // are simply ignored.
  5953. keyMap.pcDefault = {
  5954. "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo",
  5955. "Ctrl-Home": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Up": "goLineUp", "Ctrl-Down": "goLineDown",
  5956. "Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd",
  5957. "Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find",
  5958. "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll",
  5959. "Ctrl-[": "indentLess", "Ctrl-]": "indentMore",
  5960. "Ctrl-U": "undoSelection", "Shift-Ctrl-U": "redoSelection", "Alt-U": "redoSelection",
  5961. fallthrough: "basic"
  5962. }
  5963. // Very basic readline/emacs-style bindings, which are standard on Mac.
  5964. keyMap.emacsy = {
  5965. "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown",
  5966. "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd",
  5967. "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp", "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore",
  5968. "Alt-D": "delWordAfter", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars",
  5969. "Ctrl-O": "openLine"
  5970. }
  5971. keyMap.macDefault = {
  5972. "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo",
  5973. "Cmd-Home": "goDocStart", "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft",
  5974. "Alt-Right": "goGroupRight", "Cmd-Left": "goLineLeft", "Cmd-Right": "goLineRight", "Alt-Backspace": "delGroupBefore",
  5975. "Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find",
  5976. "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll",
  5977. "Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delWrappedLineLeft", "Cmd-Delete": "delWrappedLineRight",
  5978. "Cmd-U": "undoSelection", "Shift-Cmd-U": "redoSelection", "Ctrl-Up": "goDocStart", "Ctrl-Down": "goDocEnd",
  5979. fallthrough: ["basic", "emacsy"]
  5980. }
  5981. keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault
  5982. // KEYMAP DISPATCH
  5983. function normalizeKeyName(name) {
  5984. var parts = name.split(/-(?!$)/)
  5985. name = parts[parts.length - 1]
  5986. var alt, ctrl, shift, cmd
  5987. for (var i = 0; i < parts.length - 1; i++) {
  5988. var mod = parts[i]
  5989. if (/^(cmd|meta|m)$/i.test(mod)) { cmd = true }
  5990. else if (/^a(lt)?$/i.test(mod)) { alt = true }
  5991. else if (/^(c|ctrl|control)$/i.test(mod)) { ctrl = true }
  5992. else if (/^s(hift)?$/i.test(mod)) { shift = true }
  5993. else { throw new Error("Unrecognized modifier name: " + mod) }
  5994. }
  5995. if (alt) { name = "Alt-" + name }
  5996. if (ctrl) { name = "Ctrl-" + name }
  5997. if (cmd) { name = "Cmd-" + name }
  5998. if (shift) { name = "Shift-" + name }
  5999. return name
  6000. }
  6001. // This is a kludge to keep keymaps mostly working as raw objects
  6002. // (backwards compatibility) while at the same time support features
  6003. // like normalization and multi-stroke key bindings. It compiles a
  6004. // new normalized keymap, and then updates the old object to reflect
  6005. // this.
  6006. function normalizeKeyMap(keymap) {
  6007. var copy = {}
  6008. for (var keyname in keymap) { if (keymap.hasOwnProperty(keyname)) {
  6009. var value = keymap[keyname]
  6010. if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) { continue }
  6011. if (value == "...") { delete keymap[keyname]; continue }
  6012. var keys = map(keyname.split(" "), normalizeKeyName)
  6013. for (var i = 0; i < keys.length; i++) {
  6014. var val = (void 0), name = (void 0)
  6015. if (i == keys.length - 1) {
  6016. name = keys.join(" ")
  6017. val = value
  6018. } else {
  6019. name = keys.slice(0, i + 1).join(" ")
  6020. val = "..."
  6021. }
  6022. var prev = copy[name]
  6023. if (!prev) { copy[name] = val }
  6024. else if (prev != val) { throw new Error("Inconsistent bindings for " + name) }
  6025. }
  6026. delete keymap[keyname]
  6027. } }
  6028. for (var prop in copy) { keymap[prop] = copy[prop] }
  6029. return keymap
  6030. }
  6031. function lookupKey(key, map, handle, context) {
  6032. map = getKeyMap(map)
  6033. var found = map.call ? map.call(key, context) : map[key]
  6034. if (found === false) { return "nothing" }
  6035. if (found === "...") { return "multi" }
  6036. if (found != null && handle(found)) { return "handled" }
  6037. if (map.fallthrough) {
  6038. if (Object.prototype.toString.call(map.fallthrough) != "[object Array]")
  6039. { return lookupKey(key, map.fallthrough, handle, context) }
  6040. for (var i = 0; i < map.fallthrough.length; i++) {
  6041. var result = lookupKey(key, map.fallthrough[i], handle, context)
  6042. if (result) { return result }
  6043. }
  6044. }
  6045. }
  6046. // Modifier key presses don't count as 'real' key presses for the
  6047. // purpose of keymap fallthrough.
  6048. function isModifierKey(value) {
  6049. var name = typeof value == "string" ? value : keyNames[value.keyCode]
  6050. return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod"
  6051. }
  6052. function addModifierNames(name, event, noShift) {
  6053. var base = name
  6054. if (event.altKey && base != "Alt") { name = "Alt-" + name }
  6055. if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != "Ctrl") { name = "Ctrl-" + name }
  6056. if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != "Cmd") { name = "Cmd-" + name }
  6057. if (!noShift && event.shiftKey && base != "Shift") { name = "Shift-" + name }
  6058. return name
  6059. }
  6060. // Look up the name of a key as indicated by an event object.
  6061. function keyName(event, noShift) {
  6062. if (presto && event.keyCode == 34 && event["char"]) { return false }
  6063. var name = keyNames[event.keyCode]
  6064. if (name == null || event.altGraphKey) { return false }
  6065. return addModifierNames(name, event, noShift)
  6066. }
  6067. function getKeyMap(val) {
  6068. return typeof val == "string" ? keyMap[val] : val
  6069. }
  6070. // Helper for deleting text near the selection(s), used to implement
  6071. // backspace, delete, and similar functionality.
  6072. function deleteNearSelection(cm, compute) {
  6073. var ranges = cm.doc.sel.ranges, kill = []
  6074. // Build up a set of ranges to kill first, merging overlapping
  6075. // ranges.
  6076. for (var i = 0; i < ranges.length; i++) {
  6077. var toKill = compute(ranges[i])
  6078. while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) {
  6079. var replaced = kill.pop()
  6080. if (cmp(replaced.from, toKill.from) < 0) {
  6081. toKill.from = replaced.from
  6082. break
  6083. }
  6084. }
  6085. kill.push(toKill)
  6086. }
  6087. // Next, remove those actual ranges.
  6088. runInOp(cm, function () {
  6089. for (var i = kill.length - 1; i >= 0; i--)
  6090. { replaceRange(cm.doc, "", kill[i].from, kill[i].to, "+delete") }
  6091. ensureCursorVisible(cm)
  6092. })
  6093. }
  6094. function moveCharLogically(line, ch, dir) {
  6095. var target = skipExtendingChars(line.text, ch + dir, dir)
  6096. return target < 0 || target > line.text.length ? null : target
  6097. }
  6098. function moveLogically(line, start, dir) {
  6099. var ch = moveCharLogically(line, start.ch, dir)
  6100. return ch == null ? null : new Pos(start.line, ch, dir < 0 ? "after" : "before")
  6101. }
  6102. function endOfLine(visually, cm, lineObj, lineNo, dir) {
  6103. if (visually) {
  6104. var order = getOrder(lineObj, cm.doc.direction)
  6105. if (order) {
  6106. var part = dir < 0 ? lst(order) : order[0]
  6107. var moveInStorageOrder = (dir < 0) == (part.level == 1)
  6108. var sticky = moveInStorageOrder ? "after" : "before"
  6109. var ch
  6110. // With a wrapped rtl chunk (possibly spanning multiple bidi parts),
  6111. // it could be that the last bidi part is not on the last visual line,
  6112. // since visual lines contain content order-consecutive chunks.
  6113. // Thus, in rtl, we are looking for the first (content-order) character
  6114. // in the rtl chunk that is on the last line (that is, the same line
  6115. // as the last (content-order) character).
  6116. if (part.level > 0 || cm.doc.direction == "rtl") {
  6117. var prep = prepareMeasureForLine(cm, lineObj)
  6118. ch = dir < 0 ? lineObj.text.length - 1 : 0
  6119. var targetTop = measureCharPrepared(cm, prep, ch).top
  6120. ch = findFirst(function (ch) { return measureCharPrepared(cm, prep, ch).top == targetTop; }, (dir < 0) == (part.level == 1) ? part.from : part.to - 1, ch)
  6121. if (sticky == "before") { ch = moveCharLogically(lineObj, ch, 1) }
  6122. } else { ch = dir < 0 ? part.to : part.from }
  6123. return new Pos(lineNo, ch, sticky)
  6124. }
  6125. }
  6126. return new Pos(lineNo, dir < 0 ? lineObj.text.length : 0, dir < 0 ? "before" : "after")
  6127. }
  6128. function moveVisually(cm, line, start, dir) {
  6129. var bidi = getOrder(line, cm.doc.direction)
  6130. if (!bidi) { return moveLogically(line, start, dir) }
  6131. if (start.ch >= line.text.length) {
  6132. start.ch = line.text.length
  6133. start.sticky = "before"
  6134. } else if (start.ch <= 0) {
  6135. start.ch = 0
  6136. start.sticky = "after"
  6137. }
  6138. var partPos = getBidiPartAt(bidi, start.ch, start.sticky), part = bidi[partPos]
  6139. if (cm.doc.direction == "ltr" && part.level % 2 == 0 && (dir > 0 ? part.to > start.ch : part.from < start.ch)) {
  6140. // Case 1: We move within an ltr part in an ltr editor. Even with wrapped lines,
  6141. // nothing interesting happens.
  6142. return moveLogically(line, start, dir)
  6143. }
  6144. var mv = function (pos, dir) { return moveCharLogically(line, pos instanceof Pos ? pos.ch : pos, dir); }
  6145. var prep
  6146. var getWrappedLineExtent = function (ch) {
  6147. if (!cm.options.lineWrapping) { return {begin: 0, end: line.text.length} }
  6148. prep = prep || prepareMeasureForLine(cm, line)
  6149. return wrappedLineExtentChar(cm, line, prep, ch)
  6150. }
  6151. var wrappedLineExtent = getWrappedLineExtent(start.sticky == "before" ? mv(start, -1) : start.ch)
  6152. if (cm.doc.direction == "rtl" || part.level == 1) {
  6153. var moveInStorageOrder = (part.level == 1) == (dir < 0)
  6154. var ch = mv(start, moveInStorageOrder ? 1 : -1)
  6155. if (ch != null && (!moveInStorageOrder ? ch >= part.from && ch >= wrappedLineExtent.begin : ch <= part.to && ch <= wrappedLineExtent.end)) {
  6156. // Case 2: We move within an rtl part or in an rtl editor on the same visual line
  6157. var sticky = moveInStorageOrder ? "before" : "after"
  6158. return new Pos(start.line, ch, sticky)
  6159. }
  6160. }
  6161. // Case 3: Could not move within this bidi part in this visual line, so leave
  6162. // the current bidi part
  6163. var searchInVisualLine = function (partPos, dir, wrappedLineExtent) {
  6164. var getRes = function (ch, moveInStorageOrder) { return moveInStorageOrder
  6165. ? new Pos(start.line, mv(ch, 1), "before")
  6166. : new Pos(start.line, ch, "after"); }
  6167. for (; partPos >= 0 && partPos < bidi.length; partPos += dir) {
  6168. var part = bidi[partPos]
  6169. var moveInStorageOrder = (dir > 0) == (part.level != 1)
  6170. var ch = moveInStorageOrder ? wrappedLineExtent.begin : mv(wrappedLineExtent.end, -1)
  6171. if (part.from <= ch && ch < part.to) { return getRes(ch, moveInStorageOrder) }
  6172. ch = moveInStorageOrder ? part.from : mv(part.to, -1)
  6173. if (wrappedLineExtent.begin <= ch && ch < wrappedLineExtent.end) { return getRes(ch, moveInStorageOrder) }
  6174. }
  6175. }
  6176. // Case 3a: Look for other bidi parts on the same visual line
  6177. var res = searchInVisualLine(partPos + dir, dir, wrappedLineExtent)
  6178. if (res) { return res }
  6179. // Case 3b: Look for other bidi parts on the next visual line
  6180. var nextCh = dir > 0 ? wrappedLineExtent.end : mv(wrappedLineExtent.begin, -1)
  6181. if (nextCh != null && !(dir > 0 && nextCh == line.text.length)) {
  6182. res = searchInVisualLine(dir > 0 ? 0 : bidi.length - 1, dir, getWrappedLineExtent(nextCh))
  6183. if (res) { return res }
  6184. }
  6185. // Case 4: Nowhere to move
  6186. return null
  6187. }
  6188. // Commands are parameter-less actions that can be performed on an
  6189. // editor, mostly used for keybindings.
  6190. var commands = {
  6191. selectAll: selectAll,
  6192. singleSelection: function (cm) { return cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll); },
  6193. killLine: function (cm) { return deleteNearSelection(cm, function (range) {
  6194. if (range.empty()) {
  6195. var len = getLine(cm.doc, range.head.line).text.length
  6196. if (range.head.ch == len && range.head.line < cm.lastLine())
  6197. { return {from: range.head, to: Pos(range.head.line + 1, 0)} }
  6198. else
  6199. { return {from: range.head, to: Pos(range.head.line, len)} }
  6200. } else {
  6201. return {from: range.from(), to: range.to()}
  6202. }
  6203. }); },
  6204. deleteLine: function (cm) { return deleteNearSelection(cm, function (range) { return ({
  6205. from: Pos(range.from().line, 0),
  6206. to: clipPos(cm.doc, Pos(range.to().line + 1, 0))
  6207. }); }); },
  6208. delLineLeft: function (cm) { return deleteNearSelection(cm, function (range) { return ({
  6209. from: Pos(range.from().line, 0), to: range.from()
  6210. }); }); },
  6211. delWrappedLineLeft: function (cm) { return deleteNearSelection(cm, function (range) {
  6212. var top = cm.charCoords(range.head, "div").top + 5
  6213. var leftPos = cm.coordsChar({left: 0, top: top}, "div")
  6214. return {from: leftPos, to: range.from()}
  6215. }); },
  6216. delWrappedLineRight: function (cm) { return deleteNearSelection(cm, function (range) {
  6217. var top = cm.charCoords(range.head, "div").top + 5
  6218. var rightPos = cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div")
  6219. return {from: range.from(), to: rightPos }
  6220. }); },
  6221. undo: function (cm) { return cm.undo(); },
  6222. redo: function (cm) { return cm.redo(); },
  6223. undoSelection: function (cm) { return cm.undoSelection(); },
  6224. redoSelection: function (cm) { return cm.redoSelection(); },
  6225. goDocStart: function (cm) { return cm.extendSelection(Pos(cm.firstLine(), 0)); },
  6226. goDocEnd: function (cm) { return cm.extendSelection(Pos(cm.lastLine())); },
  6227. goLineStart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStart(cm, range.head.line); },
  6228. {origin: "+move", bias: 1}
  6229. ); },
  6230. goLineStartSmart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStartSmart(cm, range.head); },
  6231. {origin: "+move", bias: 1}
  6232. ); },
  6233. goLineEnd: function (cm) { return cm.extendSelectionsBy(function (range) { return lineEnd(cm, range.head.line); },
  6234. {origin: "+move", bias: -1}
  6235. ); },
  6236. goLineRight: function (cm) { return cm.extendSelectionsBy(function (range) {
  6237. var top = cm.cursorCoords(range.head, "div").top + 5
  6238. return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div")
  6239. }, sel_move); },
  6240. goLineLeft: function (cm) { return cm.extendSelectionsBy(function (range) {
  6241. var top = cm.cursorCoords(range.head, "div").top + 5
  6242. return cm.coordsChar({left: 0, top: top}, "div")
  6243. }, sel_move); },
  6244. goLineLeftSmart: function (cm) { return cm.extendSelectionsBy(function (range) {
  6245. var top = cm.cursorCoords(range.head, "div").top + 5
  6246. var pos = cm.coordsChar({left: 0, top: top}, "div")
  6247. if (pos.ch < cm.getLine(pos.line).search(/\S/)) { return lineStartSmart(cm, range.head) }
  6248. return pos
  6249. }, sel_move); },
  6250. goLineUp: function (cm) { return cm.moveV(-1, "line"); },
  6251. goLineDown: function (cm) { return cm.moveV(1, "line"); },
  6252. goPageUp: function (cm) { return cm.moveV(-1, "page"); },
  6253. goPageDown: function (cm) { return cm.moveV(1, "page"); },
  6254. goCharLeft: function (cm) { return cm.moveH(-1, "char"); },
  6255. goCharRight: function (cm) { return cm.moveH(1, "char"); },
  6256. goColumnLeft: function (cm) { return cm.moveH(-1, "column"); },
  6257. goColumnRight: function (cm) { return cm.moveH(1, "column"); },
  6258. goWordLeft: function (cm) { return cm.moveH(-1, "word"); },
  6259. goGroupRight: function (cm) { return cm.moveH(1, "group"); },
  6260. goGroupLeft: function (cm) { return cm.moveH(-1, "group"); },
  6261. goWordRight: function (cm) { return cm.moveH(1, "word"); },
  6262. delCharBefore: function (cm) { return cm.deleteH(-1, "char"); },
  6263. delCharAfter: function (cm) { return cm.deleteH(1, "char"); },
  6264. delWordBefore: function (cm) { return cm.deleteH(-1, "word"); },
  6265. delWordAfter: function (cm) { return cm.deleteH(1, "word"); },
  6266. delGroupBefore: function (cm) { return cm.deleteH(-1, "group"); },
  6267. delGroupAfter: function (cm) { return cm.deleteH(1, "group"); },
  6268. indentAuto: function (cm) { return cm.indentSelection("smart"); },
  6269. indentMore: function (cm) { return cm.indentSelection("add"); },
  6270. indentLess: function (cm) { return cm.indentSelection("subtract"); },
  6271. insertTab: function (cm) { return cm.replaceSelection("\t"); },
  6272. insertSoftTab: function (cm) {
  6273. var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize
  6274. for (var i = 0; i < ranges.length; i++) {
  6275. var pos = ranges[i].from()
  6276. var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize)
  6277. spaces.push(spaceStr(tabSize - col % tabSize))
  6278. }
  6279. cm.replaceSelections(spaces)
  6280. },
  6281. defaultTab: function (cm) {
  6282. if (cm.somethingSelected()) { cm.indentSelection("add") }
  6283. else { cm.execCommand("insertTab") }
  6284. },
  6285. // Swap the two chars left and right of each selection's head.
  6286. // Move cursor behind the two swapped characters afterwards.
  6287. //
  6288. // Doesn't consider line feeds a character.
  6289. // Doesn't scan more than one line above to find a character.
  6290. // Doesn't do anything on an empty line.
  6291. // Doesn't do anything with non-empty selections.
  6292. transposeChars: function (cm) { return runInOp(cm, function () {
  6293. var ranges = cm.listSelections(), newSel = []
  6294. for (var i = 0; i < ranges.length; i++) {
  6295. if (!ranges[i].empty()) { continue }
  6296. var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text
  6297. if (line) {
  6298. if (cur.ch == line.length) { cur = new Pos(cur.line, cur.ch - 1) }
  6299. if (cur.ch > 0) {
  6300. cur = new Pos(cur.line, cur.ch + 1)
  6301. cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2),
  6302. Pos(cur.line, cur.ch - 2), cur, "+transpose")
  6303. } else if (cur.line > cm.doc.first) {
  6304. var prev = getLine(cm.doc, cur.line - 1).text
  6305. if (prev) {
  6306. cur = new Pos(cur.line, 1)
  6307. cm.replaceRange(line.charAt(0) + cm.doc.lineSeparator() +
  6308. prev.charAt(prev.length - 1),
  6309. Pos(cur.line - 1, prev.length - 1), cur, "+transpose")
  6310. }
  6311. }
  6312. }
  6313. newSel.push(new Range(cur, cur))
  6314. }
  6315. cm.setSelections(newSel)
  6316. }); },
  6317. newlineAndIndent: function (cm) { return runInOp(cm, function () {
  6318. var sels = cm.listSelections()
  6319. for (var i = sels.length - 1; i >= 0; i--)
  6320. { cm.replaceRange(cm.doc.lineSeparator(), sels[i].anchor, sels[i].head, "+input") }
  6321. sels = cm.listSelections()
  6322. for (var i$1 = 0; i$1 < sels.length; i$1++)
  6323. { cm.indentLine(sels[i$1].from().line, null, true) }
  6324. ensureCursorVisible(cm)
  6325. }); },
  6326. openLine: function (cm) { return cm.replaceSelection("\n", "start"); },
  6327. toggleOverwrite: function (cm) { return cm.toggleOverwrite(); }
  6328. }
  6329. function lineStart(cm, lineN) {
  6330. var line = getLine(cm.doc, lineN)
  6331. var visual = visualLine(line)
  6332. if (visual != line) { lineN = lineNo(visual) }
  6333. return endOfLine(true, cm, visual, lineN, 1)
  6334. }
  6335. function lineEnd(cm, lineN) {
  6336. var line = getLine(cm.doc, lineN)
  6337. var visual = visualLineEnd(line)
  6338. if (visual != line) { lineN = lineNo(visual) }
  6339. return endOfLine(true, cm, line, lineN, -1)
  6340. }
  6341. function lineStartSmart(cm, pos) {
  6342. var start = lineStart(cm, pos.line)
  6343. var line = getLine(cm.doc, start.line)
  6344. var order = getOrder(line, cm.doc.direction)
  6345. if (!order || order[0].level == 0) {
  6346. var firstNonWS = Math.max(0, line.text.search(/\S/))
  6347. var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch
  6348. return Pos(start.line, inWS ? 0 : firstNonWS, start.sticky)
  6349. }
  6350. return start
  6351. }
  6352. // Run a handler that was bound to a key.
  6353. function doHandleBinding(cm, bound, dropShift) {
  6354. if (typeof bound == "string") {
  6355. bound = commands[bound]
  6356. if (!bound) { return false }
  6357. }
  6358. // Ensure previous input has been read, so that the handler sees a
  6359. // consistent view of the document
  6360. cm.display.input.ensurePolled()
  6361. var prevShift = cm.display.shift, done = false
  6362. try {
  6363. if (cm.isReadOnly()) { cm.state.suppressEdits = true }
  6364. if (dropShift) { cm.display.shift = false }
  6365. done = bound(cm) != Pass
  6366. } finally {
  6367. cm.display.shift = prevShift
  6368. cm.state.suppressEdits = false
  6369. }
  6370. return done
  6371. }
  6372. function lookupKeyForEditor(cm, name, handle) {
  6373. for (var i = 0; i < cm.state.keyMaps.length; i++) {
  6374. var result = lookupKey(name, cm.state.keyMaps[i], handle, cm)
  6375. if (result) { return result }
  6376. }
  6377. return (cm.options.extraKeys && lookupKey(name, cm.options.extraKeys, handle, cm))
  6378. || lookupKey(name, cm.options.keyMap, handle, cm)
  6379. }
  6380. // Note that, despite the name, this function is also used to check
  6381. // for bound mouse clicks.
  6382. var stopSeq = new Delayed
  6383. function dispatchKey(cm, name, e, handle) {
  6384. var seq = cm.state.keySeq
  6385. if (seq) {
  6386. if (isModifierKey(name)) { return "handled" }
  6387. if (/\'$/.test(name))
  6388. { cm.state.keySeq = null }
  6389. else
  6390. { stopSeq.set(50, function () {
  6391. if (cm.state.keySeq == seq) {
  6392. cm.state.keySeq = null
  6393. cm.display.input.reset()
  6394. }
  6395. }) }
  6396. if (dispatchKeyInner(cm, seq + " " + name, e, handle)) { return true }
  6397. }
  6398. return dispatchKeyInner(cm, name, e, handle)
  6399. }
  6400. function dispatchKeyInner(cm, name, e, handle) {
  6401. var result = lookupKeyForEditor(cm, name, handle)
  6402. if (result == "multi")
  6403. { cm.state.keySeq = name }
  6404. if (result == "handled")
  6405. { signalLater(cm, "keyHandled", cm, name, e) }
  6406. if (result == "handled" || result == "multi") {
  6407. e_preventDefault(e)
  6408. restartBlink(cm)
  6409. }
  6410. return !!result
  6411. }
  6412. // Handle a key from the keydown event.
  6413. function handleKeyBinding(cm, e) {
  6414. var name = keyName(e, true)
  6415. if (!name) { return false }
  6416. if (e.shiftKey && !cm.state.keySeq) {
  6417. // First try to resolve full name (including 'Shift-'). Failing
  6418. // that, see if there is a cursor-motion command (starting with
  6419. // 'go') bound to the keyname without 'Shift-'.
  6420. return dispatchKey(cm, "Shift-" + name, e, function (b) { return doHandleBinding(cm, b, true); })
  6421. || dispatchKey(cm, name, e, function (b) {
  6422. if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion)
  6423. { return doHandleBinding(cm, b) }
  6424. })
  6425. } else {
  6426. return dispatchKey(cm, name, e, function (b) { return doHandleBinding(cm, b); })
  6427. }
  6428. }
  6429. // Handle a key from the keypress event
  6430. function handleCharBinding(cm, e, ch) {
  6431. return dispatchKey(cm, "'" + ch + "'", e, function (b) { return doHandleBinding(cm, b, true); })
  6432. }
  6433. var lastStoppedKey = null
  6434. function onKeyDown(e) {
  6435. var cm = this
  6436. cm.curOp.focus = activeElt()
  6437. if (signalDOMEvent(cm, e)) { return }
  6438. // IE does strange things with escape.
  6439. if (ie && ie_version < 11 && e.keyCode == 27) { e.returnValue = false }
  6440. var code = e.keyCode
  6441. cm.display.shift = code == 16 || e.shiftKey
  6442. var handled = handleKeyBinding(cm, e)
  6443. if (presto) {
  6444. lastStoppedKey = handled ? code : null
  6445. // Opera has no cut event... we try to at least catch the key combo
  6446. if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey))
  6447. { cm.replaceSelection("", null, "cut") }
  6448. }
  6449. // Turn mouse into crosshair when Alt is held on Mac.
  6450. if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className))
  6451. { showCrossHair(cm) }
  6452. }
  6453. function showCrossHair(cm) {
  6454. var lineDiv = cm.display.lineDiv
  6455. addClass(lineDiv, "CodeMirror-crosshair")
  6456. function up(e) {
  6457. if (e.keyCode == 18 || !e.altKey) {
  6458. rmClass(lineDiv, "CodeMirror-crosshair")
  6459. off(document, "keyup", up)
  6460. off(document, "mouseover", up)
  6461. }
  6462. }
  6463. on(document, "keyup", up)
  6464. on(document, "mouseover", up)
  6465. }
  6466. function onKeyUp(e) {
  6467. if (e.keyCode == 16) { this.doc.sel.shift = false }
  6468. signalDOMEvent(this, e)
  6469. }
  6470. function onKeyPress(e) {
  6471. var cm = this
  6472. if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) { return }
  6473. var keyCode = e.keyCode, charCode = e.charCode
  6474. if (presto && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return}
  6475. if ((presto && (!e.which || e.which < 10)) && handleKeyBinding(cm, e)) { return }
  6476. var ch = String.fromCharCode(charCode == null ? keyCode : charCode)
  6477. // Some browsers fire keypress events for backspace
  6478. if (ch == "\x08") { return }
  6479. if (handleCharBinding(cm, e, ch)) { return }
  6480. cm.display.input.onKeyPress(e)
  6481. }
  6482. var DOUBLECLICK_DELAY = 400
  6483. var PastClick = function(time, pos, button) {
  6484. this.time = time
  6485. this.pos = pos
  6486. this.button = button
  6487. };
  6488. PastClick.prototype.compare = function (time, pos, button) {
  6489. return this.time + DOUBLECLICK_DELAY > time &&
  6490. cmp(pos, this.pos) == 0 && button == this.button
  6491. };
  6492. var lastClick;
  6493. var lastDoubleClick;
  6494. function clickRepeat(pos, button) {
  6495. var now = +new Date
  6496. if (lastDoubleClick && lastDoubleClick.compare(now, pos, button)) {
  6497. lastClick = lastDoubleClick = null
  6498. return "triple"
  6499. } else if (lastClick && lastClick.compare(now, pos, button)) {
  6500. lastDoubleClick = new PastClick(now, pos, button)
  6501. lastClick = null
  6502. return "double"
  6503. } else {
  6504. lastClick = new PastClick(now, pos, button)
  6505. lastDoubleClick = null
  6506. return "single"
  6507. }
  6508. }
  6509. // A mouse down can be a single click, double click, triple click,
  6510. // start of selection drag, start of text drag, new cursor
  6511. // (ctrl-click), rectangle drag (alt-drag), or xwin
  6512. // middle-click-paste. Or it might be a click on something we should
  6513. // not interfere with, such as a scrollbar or widget.
  6514. function onMouseDown(e) {
  6515. var cm = this, display = cm.display
  6516. if (signalDOMEvent(cm, e) || display.activeTouch && display.input.supportsTouch()) { return }
  6517. display.input.ensurePolled()
  6518. display.shift = e.shiftKey
  6519. if (eventInWidget(display, e)) {
  6520. if (!webkit) {
  6521. // Briefly turn off draggability, to allow widgets to do
  6522. // normal dragging things.
  6523. display.scroller.draggable = false
  6524. setTimeout(function () { return display.scroller.draggable = true; }, 100)
  6525. }
  6526. return
  6527. }
  6528. if (clickInGutter(cm, e)) { return }
  6529. var pos = posFromMouse(cm, e), button = e_button(e), repeat = pos ? clickRepeat(pos, button) : "single"
  6530. window.focus()
  6531. // #3261: make sure, that we're not starting a second selection
  6532. if (button == 1 && cm.state.selectingText)
  6533. { cm.state.selectingText(e) }
  6534. if (pos && handleMappedButton(cm, button, pos, repeat, e)) { return }
  6535. if (button == 1) {
  6536. if (pos) { leftButtonDown(cm, pos, repeat, e) }
  6537. else if (e_target(e) == display.scroller) { e_preventDefault(e) }
  6538. } else if (button == 2) {
  6539. if (pos) { extendSelection(cm.doc, pos) }
  6540. setTimeout(function () { return display.input.focus(); }, 20)
  6541. } else if (button == 3) {
  6542. if (captureRightClick) { onContextMenu(cm, e) }
  6543. else { delayBlurEvent(cm) }
  6544. }
  6545. }
  6546. function handleMappedButton(cm, button, pos, repeat, event) {
  6547. var name = "Click"
  6548. if (repeat == "double") { name = "Double" + name }
  6549. else if (repeat == "triple") { name = "Triple" + name }
  6550. name = (button == 1 ? "Left" : button == 2 ? "Middle" : "Right") + name
  6551. return dispatchKey(cm, addModifierNames(name, event), event, function (bound) {
  6552. if (typeof bound == "string") { bound = commands[bound] }
  6553. if (!bound) { return false }
  6554. var done = false
  6555. try {
  6556. if (cm.isReadOnly()) { cm.state.suppressEdits = true }
  6557. done = bound(cm, pos) != Pass
  6558. } finally {
  6559. cm.state.suppressEdits = false
  6560. }
  6561. return done
  6562. })
  6563. }
  6564. function configureMouse(cm, repeat, event) {
  6565. var option = cm.getOption("configureMouse")
  6566. var value = option ? option(cm, repeat, event) : {}
  6567. if (value.unit == null) {
  6568. var rect = chromeOS ? event.shiftKey && event.metaKey : event.altKey
  6569. value.unit = rect ? "rectangle" : repeat == "single" ? "char" : repeat == "double" ? "word" : "line"
  6570. }
  6571. if (value.extend == null || cm.doc.extend) { value.extend = cm.doc.extend || event.shiftKey }
  6572. if (value.addNew == null) { value.addNew = mac ? event.metaKey : event.ctrlKey }
  6573. if (value.moveOnDrag == null) { value.moveOnDrag = !(mac ? event.altKey : event.ctrlKey) }
  6574. return value
  6575. }
  6576. function leftButtonDown(cm, pos, repeat, event) {
  6577. if (ie) { setTimeout(bind(ensureFocus, cm), 0) }
  6578. else { cm.curOp.focus = activeElt() }
  6579. var behavior = configureMouse(cm, repeat, event)
  6580. var sel = cm.doc.sel, contained
  6581. if (cm.options.dragDrop && dragAndDrop && !cm.isReadOnly() &&
  6582. repeat == "single" && (contained = sel.contains(pos)) > -1 &&
  6583. (cmp((contained = sel.ranges[contained]).from(), pos) < 0 || pos.xRel > 0) &&
  6584. (cmp(contained.to(), pos) > 0 || pos.xRel < 0))
  6585. { leftButtonStartDrag(cm, event, pos, behavior) }
  6586. else
  6587. { leftButtonSelect(cm, event, pos, behavior) }
  6588. }
  6589. // Start a text drag. When it ends, see if any dragging actually
  6590. // happen, and treat as a click if it didn't.
  6591. function leftButtonStartDrag(cm, event, pos, behavior) {
  6592. var display = cm.display, moved = false
  6593. var dragEnd = operation(cm, function (e) {
  6594. if (webkit) { display.scroller.draggable = false }
  6595. cm.state.draggingText = false
  6596. off(document, "mouseup", dragEnd)
  6597. off(document, "mousemove", mouseMove)
  6598. off(display.scroller, "dragstart", dragStart)
  6599. off(display.scroller, "drop", dragEnd)
  6600. if (!moved) {
  6601. e_preventDefault(e)
  6602. if (!behavior.addNew)
  6603. { extendSelection(cm.doc, pos, null, null, behavior.extend) }
  6604. // Work around unexplainable focus problem in IE9 (#2127) and Chrome (#3081)
  6605. if (webkit || ie && ie_version == 9)
  6606. { setTimeout(function () {document.body.focus(); display.input.focus()}, 20) }
  6607. else
  6608. { display.input.focus() }
  6609. }
  6610. })
  6611. var mouseMove = function(e2) {
  6612. moved = moved || Math.abs(event.clientX - e2.clientX) + Math.abs(event.clientY - e2.clientY) >= 10
  6613. }
  6614. var dragStart = function () { return moved = true; }
  6615. // Let the drag handler handle this.
  6616. if (webkit) { display.scroller.draggable = true }
  6617. cm.state.draggingText = dragEnd
  6618. dragEnd.copy = !behavior.moveOnDrag
  6619. // IE's approach to draggable
  6620. if (display.scroller.dragDrop) { display.scroller.dragDrop() }
  6621. on(document, "mouseup", dragEnd)
  6622. on(document, "mousemove", mouseMove)
  6623. on(display.scroller, "dragstart", dragStart)
  6624. on(display.scroller, "drop", dragEnd)
  6625. delayBlurEvent(cm)
  6626. setTimeout(function () { return display.input.focus(); }, 20)
  6627. }
  6628. function rangeForUnit(cm, pos, unit) {
  6629. if (unit == "char") { return new Range(pos, pos) }
  6630. if (unit == "word") { return cm.findWordAt(pos) }
  6631. if (unit == "line") { return new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))) }
  6632. var result = unit(cm, pos)
  6633. return new Range(result.from, result.to)
  6634. }
  6635. // Normal selection, as opposed to text dragging.
  6636. function leftButtonSelect(cm, event, start, behavior) {
  6637. var display = cm.display, doc = cm.doc
  6638. e_preventDefault(event)
  6639. var ourRange, ourIndex, startSel = doc.sel, ranges = startSel.ranges
  6640. if (behavior.addNew && !behavior.extend) {
  6641. ourIndex = doc.sel.contains(start)
  6642. if (ourIndex > -1)
  6643. { ourRange = ranges[ourIndex] }
  6644. else
  6645. { ourRange = new Range(start, start) }
  6646. } else {
  6647. ourRange = doc.sel.primary()
  6648. ourIndex = doc.sel.primIndex
  6649. }
  6650. if (behavior.unit == "rectangle") {
  6651. if (!behavior.addNew) { ourRange = new Range(start, start) }
  6652. start = posFromMouse(cm, event, true, true)
  6653. ourIndex = -1
  6654. } else {
  6655. var range = rangeForUnit(cm, start, behavior.unit)
  6656. if (behavior.extend)
  6657. { ourRange = extendRange(ourRange, range.anchor, range.head, behavior.extend) }
  6658. else
  6659. { ourRange = range }
  6660. }
  6661. if (!behavior.addNew) {
  6662. ourIndex = 0
  6663. setSelection(doc, new Selection([ourRange], 0), sel_mouse)
  6664. startSel = doc.sel
  6665. } else if (ourIndex == -1) {
  6666. ourIndex = ranges.length
  6667. setSelection(doc, normalizeSelection(ranges.concat([ourRange]), ourIndex),
  6668. {scroll: false, origin: "*mouse"})
  6669. } else if (ranges.length > 1 && ranges[ourIndex].empty() && behavior.unit == "char" && !behavior.extend) {
  6670. setSelection(doc, normalizeSelection(ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0),
  6671. {scroll: false, origin: "*mouse"})
  6672. startSel = doc.sel
  6673. } else {
  6674. replaceOneSelection(doc, ourIndex, ourRange, sel_mouse)
  6675. }
  6676. var lastPos = start
  6677. function extendTo(pos) {
  6678. if (cmp(lastPos, pos) == 0) { return }
  6679. lastPos = pos
  6680. if (behavior.unit == "rectangle") {
  6681. var ranges = [], tabSize = cm.options.tabSize
  6682. var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize)
  6683. var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize)
  6684. var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol)
  6685. for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line));
  6686. line <= end; line++) {
  6687. var text = getLine(doc, line).text, leftPos = findColumn(text, left, tabSize)
  6688. if (left == right)
  6689. { ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos))) }
  6690. else if (text.length > leftPos)
  6691. { ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize)))) }
  6692. }
  6693. if (!ranges.length) { ranges.push(new Range(start, start)) }
  6694. setSelection(doc, normalizeSelection(startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex),
  6695. {origin: "*mouse", scroll: false})
  6696. cm.scrollIntoView(pos)
  6697. } else {
  6698. var oldRange = ourRange
  6699. var range = rangeForUnit(cm, pos, behavior.unit)
  6700. var anchor = oldRange.anchor, head
  6701. if (cmp(range.anchor, anchor) > 0) {
  6702. head = range.head
  6703. anchor = minPos(oldRange.from(), range.anchor)
  6704. } else {
  6705. head = range.anchor
  6706. anchor = maxPos(oldRange.to(), range.head)
  6707. }
  6708. var ranges$1 = startSel.ranges.slice(0)
  6709. ranges$1[ourIndex] = bidiSimplify(cm, new Range(clipPos(doc, anchor), head))
  6710. setSelection(doc, normalizeSelection(ranges$1, ourIndex), sel_mouse)
  6711. }
  6712. }
  6713. var editorSize = display.wrapper.getBoundingClientRect()
  6714. // Used to ensure timeout re-tries don't fire when another extend
  6715. // happened in the meantime (clearTimeout isn't reliable -- at
  6716. // least on Chrome, the timeouts still happen even when cleared,
  6717. // if the clear happens after their scheduled firing time).
  6718. var counter = 0
  6719. function extend(e) {
  6720. var curCount = ++counter
  6721. var cur = posFromMouse(cm, e, true, behavior.unit == "rectangle")
  6722. if (!cur) { return }
  6723. if (cmp(cur, lastPos) != 0) {
  6724. cm.curOp.focus = activeElt()
  6725. extendTo(cur)
  6726. var visible = visibleLines(display, doc)
  6727. if (cur.line >= visible.to || cur.line < visible.from)
  6728. { setTimeout(operation(cm, function () {if (counter == curCount) { extend(e) }}), 150) }
  6729. } else {
  6730. var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0
  6731. if (outside) { setTimeout(operation(cm, function () {
  6732. if (counter != curCount) { return }
  6733. display.scroller.scrollTop += outside
  6734. extend(e)
  6735. }), 50) }
  6736. }
  6737. }
  6738. function done(e) {
  6739. cm.state.selectingText = false
  6740. counter = Infinity
  6741. e_preventDefault(e)
  6742. display.input.focus()
  6743. off(document, "mousemove", move)
  6744. off(document, "mouseup", up)
  6745. doc.history.lastSelOrigin = null
  6746. }
  6747. var move = operation(cm, function (e) {
  6748. if (!e_button(e)) { done(e) }
  6749. else { extend(e) }
  6750. })
  6751. var up = operation(cm, done)
  6752. cm.state.selectingText = up
  6753. on(document, "mousemove", move)
  6754. on(document, "mouseup", up)
  6755. }
  6756. // Used when mouse-selecting to adjust the anchor to the proper side
  6757. // of a bidi jump depending on the visual position of the head.
  6758. function bidiSimplify(cm, range) {
  6759. var anchor = range.anchor;
  6760. var head = range.head;
  6761. var anchorLine = getLine(cm.doc, anchor.line)
  6762. if (cmp(anchor, head) == 0 && anchor.sticky == head.sticky) { return range }
  6763. var order = getOrder(anchorLine)
  6764. if (!order) { return range }
  6765. var index = getBidiPartAt(order, anchor.ch, anchor.sticky), part = order[index]
  6766. if (part.from != anchor.ch && part.to != anchor.ch) { return range }
  6767. var boundary = index + ((part.from == anchor.ch) == (part.level != 1) ? 0 : 1)
  6768. if (boundary == 0 || boundary == order.length) { return range }
  6769. // Compute the relative visual position of the head compared to the
  6770. // anchor (<0 is to the left, >0 to the right)
  6771. var leftSide
  6772. if (head.line != anchor.line) {
  6773. leftSide = (head.line - anchor.line) * (cm.doc.direction == "ltr" ? 1 : -1) > 0
  6774. } else {
  6775. var headIndex = getBidiPartAt(order, head.ch, head.sticky)
  6776. var dir = headIndex - index || (head.ch - anchor.ch) * (part.level == 1 ? -1 : 1)
  6777. if (headIndex == boundary - 1 || headIndex == boundary)
  6778. { leftSide = dir < 0 }
  6779. else
  6780. { leftSide = dir > 0 }
  6781. }
  6782. var usePart = order[boundary + (leftSide ? -1 : 0)]
  6783. var from = leftSide == (usePart.level == 1)
  6784. var ch = from ? usePart.from : usePart.to, sticky = from ? "after" : "before"
  6785. return anchor.ch == ch && anchor.sticky == sticky ? range : new Range(new Pos(anchor.line, ch, sticky), head)
  6786. }
  6787. // Determines whether an event happened in the gutter, and fires the
  6788. // handlers for the corresponding event.
  6789. function gutterEvent(cm, e, type, prevent) {
  6790. var mX, mY
  6791. if (e.touches) {
  6792. mX = e.touches[0].clientX
  6793. mY = e.touches[0].clientY
  6794. } else {
  6795. try { mX = e.clientX; mY = e.clientY }
  6796. catch(e) { return false }
  6797. }
  6798. if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) { return false }
  6799. if (prevent) { e_preventDefault(e) }
  6800. var display = cm.display
  6801. var lineBox = display.lineDiv.getBoundingClientRect()
  6802. if (mY > lineBox.bottom || !hasHandler(cm, type)) { return e_defaultPrevented(e) }
  6803. mY -= lineBox.top - display.viewOffset
  6804. for (var i = 0; i < cm.options.gutters.length; ++i) {
  6805. var g = display.gutters.childNodes[i]
  6806. if (g && g.getBoundingClientRect().right >= mX) {
  6807. var line = lineAtHeight(cm.doc, mY)
  6808. var gutter = cm.options.gutters[i]
  6809. signal(cm, type, cm, line, gutter, e)
  6810. return e_defaultPrevented(e)
  6811. }
  6812. }
  6813. }
  6814. function clickInGutter(cm, e) {
  6815. return gutterEvent(cm, e, "gutterClick", true)
  6816. }
  6817. // CONTEXT MENU HANDLING
  6818. // To make the context menu work, we need to briefly unhide the
  6819. // textarea (making it as unobtrusive as possible) to let the
  6820. // right-click take effect on it.
  6821. function onContextMenu(cm, e) {
  6822. if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) { return }
  6823. if (signalDOMEvent(cm, e, "contextmenu")) { return }
  6824. cm.display.input.onContextMenu(e)
  6825. }
  6826. function contextMenuInGutter(cm, e) {
  6827. if (!hasHandler(cm, "gutterContextMenu")) { return false }
  6828. return gutterEvent(cm, e, "gutterContextMenu", false)
  6829. }
  6830. function themeChanged(cm) {
  6831. cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") +
  6832. cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-")
  6833. clearCaches(cm)
  6834. }
  6835. var Init = {toString: function(){return "CodeMirror.Init"}}
  6836. var defaults = {}
  6837. var optionHandlers = {}
  6838. function defineOptions(CodeMirror) {
  6839. var optionHandlers = CodeMirror.optionHandlers
  6840. function option(name, deflt, handle, notOnInit) {
  6841. CodeMirror.defaults[name] = deflt
  6842. if (handle) { optionHandlers[name] =
  6843. notOnInit ? function (cm, val, old) {if (old != Init) { handle(cm, val, old) }} : handle }
  6844. }
  6845. CodeMirror.defineOption = option
  6846. // Passed to option handlers when there is no old value.
  6847. CodeMirror.Init = Init
  6848. // These two are, on init, called from the constructor because they
  6849. // have to be initialized before the editor can start at all.
  6850. option("value", "", function (cm, val) { return cm.setValue(val); }, true)
  6851. option("mode", null, function (cm, val) {
  6852. cm.doc.modeOption = val
  6853. loadMode(cm)
  6854. }, true)
  6855. option("indentUnit", 2, loadMode, true)
  6856. option("indentWithTabs", false)
  6857. option("smartIndent", true)
  6858. option("tabSize", 4, function (cm) {
  6859. resetModeState(cm)
  6860. clearCaches(cm)
  6861. regChange(cm)
  6862. }, true)
  6863. option("lineSeparator", null, function (cm, val) {
  6864. cm.doc.lineSep = val
  6865. if (!val) { return }
  6866. var newBreaks = [], lineNo = cm.doc.first
  6867. cm.doc.iter(function (line) {
  6868. for (var pos = 0;;) {
  6869. var found = line.text.indexOf(val, pos)
  6870. if (found == -1) { break }
  6871. pos = found + val.length
  6872. newBreaks.push(Pos(lineNo, found))
  6873. }
  6874. lineNo++
  6875. })
  6876. for (var i = newBreaks.length - 1; i >= 0; i--)
  6877. { replaceRange(cm.doc, val, newBreaks[i], Pos(newBreaks[i].line, newBreaks[i].ch + val.length)) }
  6878. })
  6879. option("specialChars", /[\u0000-\u001f\u007f-\u009f\u00ad\u061c\u200b-\u200f\u2028\u2029\ufeff]/g, function (cm, val, old) {
  6880. cm.state.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g")
  6881. if (old != Init) { cm.refresh() }
  6882. })
  6883. option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function (cm) { return cm.refresh(); }, true)
  6884. option("electricChars", true)
  6885. option("inputStyle", mobile ? "contenteditable" : "textarea", function () {
  6886. throw new Error("inputStyle can not (yet) be changed in a running editor") // FIXME
  6887. }, true)
  6888. option("spellcheck", false, function (cm, val) { return cm.getInputField().spellcheck = val; }, true)
  6889. option("rtlMoveVisually", !windows)
  6890. option("wholeLineUpdateBefore", true)
  6891. option("theme", "default", function (cm) {
  6892. themeChanged(cm)
  6893. guttersChanged(cm)
  6894. }, true)
  6895. option("keyMap", "default", function (cm, val, old) {
  6896. var next = getKeyMap(val)
  6897. var prev = old != Init && getKeyMap(old)
  6898. if (prev && prev.detach) { prev.detach(cm, next) }
  6899. if (next.attach) { next.attach(cm, prev || null) }
  6900. })
  6901. option("extraKeys", null)
  6902. option("configureMouse", null)
  6903. option("lineWrapping", false, wrappingChanged, true)
  6904. option("gutters", [], function (cm) {
  6905. setGuttersForLineNumbers(cm.options)
  6906. guttersChanged(cm)
  6907. }, true)
  6908. option("fixedGutter", true, function (cm, val) {
  6909. cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0"
  6910. cm.refresh()
  6911. }, true)
  6912. option("coverGutterNextToScrollbar", false, function (cm) { return updateScrollbars(cm); }, true)
  6913. option("scrollbarStyle", "native", function (cm) {
  6914. initScrollbars(cm)
  6915. updateScrollbars(cm)
  6916. cm.display.scrollbars.setScrollTop(cm.doc.scrollTop)
  6917. cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft)
  6918. }, true)
  6919. option("lineNumbers", false, function (cm) {
  6920. setGuttersForLineNumbers(cm.options)
  6921. guttersChanged(cm)
  6922. }, true)
  6923. option("firstLineNumber", 1, guttersChanged, true)
  6924. option("lineNumberFormatter", function (integer) { return integer; }, guttersChanged, true)
  6925. option("showCursorWhenSelecting", false, updateSelection, true)
  6926. option("resetSelectionOnContextMenu", true)
  6927. option("lineWiseCopyCut", true)
  6928. option("pasteLinesPerSelection", true)
  6929. option("readOnly", false, function (cm, val) {
  6930. if (val == "nocursor") {
  6931. onBlur(cm)
  6932. cm.display.input.blur()
  6933. }
  6934. cm.display.input.readOnlyChanged(val)
  6935. })
  6936. option("disableInput", false, function (cm, val) {if (!val) { cm.display.input.reset() }}, true)
  6937. option("dragDrop", true, dragDropChanged)
  6938. option("allowDropFileTypes", null)
  6939. option("cursorBlinkRate", 530)
  6940. option("cursorScrollMargin", 0)
  6941. option("cursorHeight", 1, updateSelection, true)
  6942. option("singleCursorHeightPerLine", true, updateSelection, true)
  6943. option("workTime", 100)
  6944. option("workDelay", 100)
  6945. option("flattenSpans", true, resetModeState, true)
  6946. option("addModeClass", false, resetModeState, true)
  6947. option("pollInterval", 100)
  6948. option("undoDepth", 200, function (cm, val) { return cm.doc.history.undoDepth = val; })
  6949. option("historyEventDelay", 1250)
  6950. option("viewportMargin", 10, function (cm) { return cm.refresh(); }, true)
  6951. option("maxHighlightLength", 10000, resetModeState, true)
  6952. option("moveInputWithCursor", true, function (cm, val) {
  6953. if (!val) { cm.display.input.resetPosition() }
  6954. })
  6955. option("tabindex", null, function (cm, val) { return cm.display.input.getField().tabIndex = val || ""; })
  6956. option("autofocus", null)
  6957. option("direction", "ltr", function (cm, val) { return cm.doc.setDirection(val); }, true)
  6958. }
  6959. function guttersChanged(cm) {
  6960. updateGutters(cm)
  6961. regChange(cm)
  6962. alignHorizontally(cm)
  6963. }
  6964. function dragDropChanged(cm, value, old) {
  6965. var wasOn = old && old != Init
  6966. if (!value != !wasOn) {
  6967. var funcs = cm.display.dragFunctions
  6968. var toggle = value ? on : off
  6969. toggle(cm.display.scroller, "dragstart", funcs.start)
  6970. toggle(cm.display.scroller, "dragenter", funcs.enter)
  6971. toggle(cm.display.scroller, "dragover", funcs.over)
  6972. toggle(cm.display.scroller, "dragleave", funcs.leave)
  6973. toggle(cm.display.scroller, "drop", funcs.drop)
  6974. }
  6975. }
  6976. function wrappingChanged(cm) {
  6977. if (cm.options.lineWrapping) {
  6978. addClass(cm.display.wrapper, "CodeMirror-wrap")
  6979. cm.display.sizer.style.minWidth = ""
  6980. cm.display.sizerWidth = null
  6981. } else {
  6982. rmClass(cm.display.wrapper, "CodeMirror-wrap")
  6983. findMaxLine(cm)
  6984. }
  6985. estimateLineHeights(cm)
  6986. regChange(cm)
  6987. clearCaches(cm)
  6988. setTimeout(function () { return updateScrollbars(cm); }, 100)
  6989. }
  6990. // A CodeMirror instance represents an editor. This is the object
  6991. // that user code is usually dealing with.
  6992. function CodeMirror(place, options) {
  6993. var this$1 = this;
  6994. if (!(this instanceof CodeMirror)) { return new CodeMirror(place, options) }
  6995. this.options = options = options ? copyObj(options) : {}
  6996. // Determine effective options based on given values and defaults.
  6997. copyObj(defaults, options, false)
  6998. setGuttersForLineNumbers(options)
  6999. var doc = options.value
  7000. if (typeof doc == "string") { doc = new Doc(doc, options.mode, null, options.lineSeparator, options.direction) }
  7001. this.doc = doc
  7002. var input = new CodeMirror.inputStyles[options.inputStyle](this)
  7003. var display = this.display = new Display(place, doc, input)
  7004. display.wrapper.CodeMirror = this
  7005. updateGutters(this)
  7006. themeChanged(this)
  7007. if (options.lineWrapping)
  7008. { this.display.wrapper.className += " CodeMirror-wrap" }
  7009. initScrollbars(this)
  7010. this.state = {
  7011. keyMaps: [], // stores maps added by addKeyMap
  7012. overlays: [], // highlighting overlays, as added by addOverlay
  7013. modeGen: 0, // bumped when mode/overlay changes, used to invalidate highlighting info
  7014. overwrite: false,
  7015. delayingBlurEvent: false,
  7016. focused: false,
  7017. suppressEdits: false, // used to disable editing during key handlers when in readOnly mode
  7018. pasteIncoming: false, cutIncoming: false, // help recognize paste/cut edits in input.poll
  7019. selectingText: false,
  7020. draggingText: false,
  7021. highlight: new Delayed(), // stores highlight worker timeout
  7022. keySeq: null, // Unfinished key sequence
  7023. specialChars: null
  7024. }
  7025. if (options.autofocus && !mobile) { display.input.focus() }
  7026. // Override magic textarea content restore that IE sometimes does
  7027. // on our hidden textarea on reload
  7028. if (ie && ie_version < 11) { setTimeout(function () { return this$1.display.input.reset(true); }, 20) }
  7029. registerEventHandlers(this)
  7030. ensureGlobalHandlers()
  7031. startOperation(this)
  7032. this.curOp.forceUpdate = true
  7033. attachDoc(this, doc)
  7034. if ((options.autofocus && !mobile) || this.hasFocus())
  7035. { setTimeout(bind(onFocus, this), 20) }
  7036. else
  7037. { onBlur(this) }
  7038. for (var opt in optionHandlers) { if (optionHandlers.hasOwnProperty(opt))
  7039. { optionHandlers[opt](this$1, options[opt], Init) } }
  7040. maybeUpdateLineNumberWidth(this)
  7041. if (options.finishInit) { options.finishInit(this) }
  7042. for (var i = 0; i < initHooks.length; ++i) { initHooks[i](this$1) }
  7043. endOperation(this)
  7044. // Suppress optimizelegibility in Webkit, since it breaks text
  7045. // measuring on line wrapping boundaries.
  7046. if (webkit && options.lineWrapping &&
  7047. getComputedStyle(display.lineDiv).textRendering == "optimizelegibility")
  7048. { display.lineDiv.style.textRendering = "auto" }
  7049. }
  7050. // The default configuration options.
  7051. CodeMirror.defaults = defaults
  7052. // Functions to run when options are changed.
  7053. CodeMirror.optionHandlers = optionHandlers
  7054. // Attach the necessary event handlers when initializing the editor
  7055. function registerEventHandlers(cm) {
  7056. var d = cm.display
  7057. on(d.scroller, "mousedown", operation(cm, onMouseDown))
  7058. // Older IE's will not fire a second mousedown for a double click
  7059. if (ie && ie_version < 11)
  7060. { on(d.scroller, "dblclick", operation(cm, function (e) {
  7061. if (signalDOMEvent(cm, e)) { return }
  7062. var pos = posFromMouse(cm, e)
  7063. if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) { return }
  7064. e_preventDefault(e)
  7065. var word = cm.findWordAt(pos)
  7066. extendSelection(cm.doc, word.anchor, word.head)
  7067. })) }
  7068. else
  7069. { on(d.scroller, "dblclick", function (e) { return signalDOMEvent(cm, e) || e_preventDefault(e); }) }
  7070. // Some browsers fire contextmenu *after* opening the menu, at
  7071. // which point we can't mess with it anymore. Context menu is
  7072. // handled in onMouseDown for these browsers.
  7073. if (!captureRightClick) { on(d.scroller, "contextmenu", function (e) { return onContextMenu(cm, e); }) }
  7074. // Used to suppress mouse event handling when a touch happens
  7075. var touchFinished, prevTouch = {end: 0}
  7076. function finishTouch() {
  7077. if (d.activeTouch) {
  7078. touchFinished = setTimeout(function () { return d.activeTouch = null; }, 1000)
  7079. prevTouch = d.activeTouch
  7080. prevTouch.end = +new Date
  7081. }
  7082. }
  7083. function isMouseLikeTouchEvent(e) {
  7084. if (e.touches.length != 1) { return false }
  7085. var touch = e.touches[0]
  7086. return touch.radiusX <= 1 && touch.radiusY <= 1
  7087. }
  7088. function farAway(touch, other) {
  7089. if (other.left == null) { return true }
  7090. var dx = other.left - touch.left, dy = other.top - touch.top
  7091. return dx * dx + dy * dy > 20 * 20
  7092. }
  7093. on(d.scroller, "touchstart", function (e) {
  7094. if (!signalDOMEvent(cm, e) && !isMouseLikeTouchEvent(e) && !clickInGutter(cm, e)) {
  7095. d.input.ensurePolled()
  7096. clearTimeout(touchFinished)
  7097. var now = +new Date
  7098. d.activeTouch = {start: now, moved: false,
  7099. prev: now - prevTouch.end <= 300 ? prevTouch : null}
  7100. if (e.touches.length == 1) {
  7101. d.activeTouch.left = e.touches[0].pageX
  7102. d.activeTouch.top = e.touches[0].pageY
  7103. }
  7104. }
  7105. })
  7106. on(d.scroller, "touchmove", function () {
  7107. if (d.activeTouch) { d.activeTouch.moved = true }
  7108. })
  7109. on(d.scroller, "touchend", function (e) {
  7110. var touch = d.activeTouch
  7111. if (touch && !eventInWidget(d, e) && touch.left != null &&
  7112. !touch.moved && new Date - touch.start < 300) {
  7113. var pos = cm.coordsChar(d.activeTouch, "page"), range
  7114. if (!touch.prev || farAway(touch, touch.prev)) // Single tap
  7115. { range = new Range(pos, pos) }
  7116. else if (!touch.prev.prev || farAway(touch, touch.prev.prev)) // Double tap
  7117. { range = cm.findWordAt(pos) }
  7118. else // Triple tap
  7119. { range = new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))) }
  7120. cm.setSelection(range.anchor, range.head)
  7121. cm.focus()
  7122. e_preventDefault(e)
  7123. }
  7124. finishTouch()
  7125. })
  7126. on(d.scroller, "touchcancel", finishTouch)
  7127. // Sync scrolling between fake scrollbars and real scrollable
  7128. // area, ensure viewport is updated when scrolling.
  7129. on(d.scroller, "scroll", function () {
  7130. if (d.scroller.clientHeight) {
  7131. updateScrollTop(cm, d.scroller.scrollTop)
  7132. setScrollLeft(cm, d.scroller.scrollLeft, true)
  7133. signal(cm, "scroll", cm)
  7134. }
  7135. })
  7136. // Listen to wheel events in order to try and update the viewport on time.
  7137. on(d.scroller, "mousewheel", function (e) { return onScrollWheel(cm, e); })
  7138. on(d.scroller, "DOMMouseScroll", function (e) { return onScrollWheel(cm, e); })
  7139. // Prevent wrapper from ever scrolling
  7140. on(d.wrapper, "scroll", function () { return d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; })
  7141. d.dragFunctions = {
  7142. enter: function (e) {if (!signalDOMEvent(cm, e)) { e_stop(e) }},
  7143. over: function (e) {if (!signalDOMEvent(cm, e)) { onDragOver(cm, e); e_stop(e) }},
  7144. start: function (e) { return onDragStart(cm, e); },
  7145. drop: operation(cm, onDrop),
  7146. leave: function (e) {if (!signalDOMEvent(cm, e)) { clearDragCursor(cm) }}
  7147. }
  7148. var inp = d.input.getField()
  7149. on(inp, "keyup", function (e) { return onKeyUp.call(cm, e); })
  7150. on(inp, "keydown", operation(cm, onKeyDown))
  7151. on(inp, "keypress", operation(cm, onKeyPress))
  7152. on(inp, "focus", function (e) { return onFocus(cm, e); })
  7153. on(inp, "blur", function (e) { return onBlur(cm, e); })
  7154. }
  7155. var initHooks = []
  7156. CodeMirror.defineInitHook = function (f) { return initHooks.push(f); }
  7157. // Indent the given line. The how parameter can be "smart",
  7158. // "add"/null, "subtract", or "prev". When aggressive is false
  7159. // (typically set to true for forced single-line indents), empty
  7160. // lines are not indented, and places where the mode returns Pass
  7161. // are left alone.
  7162. function indentLine(cm, n, how, aggressive) {
  7163. var doc = cm.doc, state
  7164. if (how == null) { how = "add" }
  7165. if (how == "smart") {
  7166. // Fall back to "prev" when the mode doesn't have an indentation
  7167. // method.
  7168. if (!doc.mode.indent) { how = "prev" }
  7169. else { state = getContextBefore(cm, n).state }
  7170. }
  7171. var tabSize = cm.options.tabSize
  7172. var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize)
  7173. if (line.stateAfter) { line.stateAfter = null }
  7174. var curSpaceString = line.text.match(/^\s*/)[0], indentation
  7175. if (!aggressive && !/\S/.test(line.text)) {
  7176. indentation = 0
  7177. how = "not"
  7178. } else if (how == "smart") {
  7179. indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text)
  7180. if (indentation == Pass || indentation > 150) {
  7181. if (!aggressive) { return }
  7182. how = "prev"
  7183. }
  7184. }
  7185. if (how == "prev") {
  7186. if (n > doc.first) { indentation = countColumn(getLine(doc, n-1).text, null, tabSize) }
  7187. else { indentation = 0 }
  7188. } else if (how == "add") {
  7189. indentation = curSpace + cm.options.indentUnit
  7190. } else if (how == "subtract") {
  7191. indentation = curSpace - cm.options.indentUnit
  7192. } else if (typeof how == "number") {
  7193. indentation = curSpace + how
  7194. }
  7195. indentation = Math.max(0, indentation)
  7196. var indentString = "", pos = 0
  7197. if (cm.options.indentWithTabs)
  7198. { for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t"} }
  7199. if (pos < indentation) { indentString += spaceStr(indentation - pos) }
  7200. if (indentString != curSpaceString) {
  7201. replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input")
  7202. line.stateAfter = null
  7203. return true
  7204. } else {
  7205. // Ensure that, if the cursor was in the whitespace at the start
  7206. // of the line, it is moved to the end of that space.
  7207. for (var i$1 = 0; i$1 < doc.sel.ranges.length; i$1++) {
  7208. var range = doc.sel.ranges[i$1]
  7209. if (range.head.line == n && range.head.ch < curSpaceString.length) {
  7210. var pos$1 = Pos(n, curSpaceString.length)
  7211. replaceOneSelection(doc, i$1, new Range(pos$1, pos$1))
  7212. break
  7213. }
  7214. }
  7215. }
  7216. }
  7217. // This will be set to a {lineWise: bool, text: [string]} object, so
  7218. // that, when pasting, we know what kind of selections the copied
  7219. // text was made out of.
  7220. var lastCopied = null
  7221. function setLastCopied(newLastCopied) {
  7222. lastCopied = newLastCopied
  7223. }
  7224. function applyTextInput(cm, inserted, deleted, sel, origin) {
  7225. var doc = cm.doc
  7226. cm.display.shift = false
  7227. if (!sel) { sel = doc.sel }
  7228. var paste = cm.state.pasteIncoming || origin == "paste"
  7229. var textLines = splitLinesAuto(inserted), multiPaste = null
  7230. // When pasing N lines into N selections, insert one line per selection
  7231. if (paste && sel.ranges.length > 1) {
  7232. if (lastCopied && lastCopied.text.join("\n") == inserted) {
  7233. if (sel.ranges.length % lastCopied.text.length == 0) {
  7234. multiPaste = []
  7235. for (var i = 0; i < lastCopied.text.length; i++)
  7236. { multiPaste.push(doc.splitLines(lastCopied.text[i])) }
  7237. }
  7238. } else if (textLines.length == sel.ranges.length && cm.options.pasteLinesPerSelection) {
  7239. multiPaste = map(textLines, function (l) { return [l]; })
  7240. }
  7241. }
  7242. var updateInput
  7243. // Normal behavior is to insert the new text into every selection
  7244. for (var i$1 = sel.ranges.length - 1; i$1 >= 0; i$1--) {
  7245. var range = sel.ranges[i$1]
  7246. var from = range.from(), to = range.to()
  7247. if (range.empty()) {
  7248. if (deleted && deleted > 0) // Handle deletion
  7249. { from = Pos(from.line, from.ch - deleted) }
  7250. else if (cm.state.overwrite && !paste) // Handle overwrite
  7251. { to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length)) }
  7252. else if (lastCopied && lastCopied.lineWise && lastCopied.text.join("\n") == inserted)
  7253. { from = to = Pos(from.line, 0) }
  7254. }
  7255. updateInput = cm.curOp.updateInput
  7256. var changeEvent = {from: from, to: to, text: multiPaste ? multiPaste[i$1 % multiPaste.length] : textLines,
  7257. origin: origin || (paste ? "paste" : cm.state.cutIncoming ? "cut" : "+input")}
  7258. makeChange(cm.doc, changeEvent)
  7259. signalLater(cm, "inputRead", cm, changeEvent)
  7260. }
  7261. if (inserted && !paste)
  7262. { triggerElectric(cm, inserted) }
  7263. ensureCursorVisible(cm)
  7264. cm.curOp.updateInput = updateInput
  7265. cm.curOp.typing = true
  7266. cm.state.pasteIncoming = cm.state.cutIncoming = false
  7267. }
  7268. function handlePaste(e, cm) {
  7269. var pasted = e.clipboardData && e.clipboardData.getData("Text")
  7270. if (pasted) {
  7271. e.preventDefault()
  7272. if (!cm.isReadOnly() && !cm.options.disableInput)
  7273. { runInOp(cm, function () { return applyTextInput(cm, pasted, 0, null, "paste"); }) }
  7274. return true
  7275. }
  7276. }
  7277. function triggerElectric(cm, inserted) {
  7278. // When an 'electric' character is inserted, immediately trigger a reindent
  7279. if (!cm.options.electricChars || !cm.options.smartIndent) { return }
  7280. var sel = cm.doc.sel
  7281. for (var i = sel.ranges.length - 1; i >= 0; i--) {
  7282. var range = sel.ranges[i]
  7283. if (range.head.ch > 100 || (i && sel.ranges[i - 1].head.line == range.head.line)) { continue }
  7284. var mode = cm.getModeAt(range.head)
  7285. var indented = false
  7286. if (mode.electricChars) {
  7287. for (var j = 0; j < mode.electricChars.length; j++)
  7288. { if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) {
  7289. indented = indentLine(cm, range.head.line, "smart")
  7290. break
  7291. } }
  7292. } else if (mode.electricInput) {
  7293. if (mode.electricInput.test(getLine(cm.doc, range.head.line).text.slice(0, range.head.ch)))
  7294. { indented = indentLine(cm, range.head.line, "smart") }
  7295. }
  7296. if (indented) { signalLater(cm, "electricInput", cm, range.head.line) }
  7297. }
  7298. }
  7299. function copyableRanges(cm) {
  7300. var text = [], ranges = []
  7301. for (var i = 0; i < cm.doc.sel.ranges.length; i++) {
  7302. var line = cm.doc.sel.ranges[i].head.line
  7303. var lineRange = {anchor: Pos(line, 0), head: Pos(line + 1, 0)}
  7304. ranges.push(lineRange)
  7305. text.push(cm.getRange(lineRange.anchor, lineRange.head))
  7306. }
  7307. return {text: text, ranges: ranges}
  7308. }
  7309. function disableBrowserMagic(field, spellcheck) {
  7310. field.setAttribute("autocorrect", "off")
  7311. field.setAttribute("autocapitalize", "off")
  7312. field.setAttribute("spellcheck", !!spellcheck)
  7313. }
  7314. function hiddenTextarea() {
  7315. var te = elt("textarea", null, null, "position: absolute; bottom: -1em; padding: 0; width: 1px; height: 1em; outline: none")
  7316. var div = elt("div", [te], null, "overflow: hidden; position: relative; width: 3px; height: 0px;")
  7317. // The textarea is kept positioned near the cursor to prevent the
  7318. // fact that it'll be scrolled into view on input from scrolling
  7319. // our fake cursor out of view. On webkit, when wrap=off, paste is
  7320. // very slow. So make the area wide instead.
  7321. if (webkit) { te.style.width = "1000px" }
  7322. else { te.setAttribute("wrap", "off") }
  7323. // If border: 0; -- iOS fails to open keyboard (issue #1287)
  7324. if (ios) { te.style.border = "1px solid black" }
  7325. disableBrowserMagic(te)
  7326. return div
  7327. }
  7328. // The publicly visible API. Note that methodOp(f) means
  7329. // 'wrap f in an operation, performed on its `this` parameter'.
  7330. // This is not the complete set of editor methods. Most of the
  7331. // methods defined on the Doc type are also injected into
  7332. // CodeMirror.prototype, for backwards compatibility and
  7333. // convenience.
  7334. function addEditorMethods(CodeMirror) {
  7335. var optionHandlers = CodeMirror.optionHandlers
  7336. var helpers = CodeMirror.helpers = {}
  7337. CodeMirror.prototype = {
  7338. constructor: CodeMirror,
  7339. focus: function(){window.focus(); this.display.input.focus()},
  7340. setOption: function(option, value) {
  7341. var options = this.options, old = options[option]
  7342. if (options[option] == value && option != "mode") { return }
  7343. options[option] = value
  7344. if (optionHandlers.hasOwnProperty(option))
  7345. { operation(this, optionHandlers[option])(this, value, old) }
  7346. signal(this, "optionChange", this, option)
  7347. },
  7348. getOption: function(option) {return this.options[option]},
  7349. getDoc: function() {return this.doc},
  7350. addKeyMap: function(map, bottom) {
  7351. this.state.keyMaps[bottom ? "push" : "unshift"](getKeyMap(map))
  7352. },
  7353. removeKeyMap: function(map) {
  7354. var maps = this.state.keyMaps
  7355. for (var i = 0; i < maps.length; ++i)
  7356. { if (maps[i] == map || maps[i].name == map) {
  7357. maps.splice(i, 1)
  7358. return true
  7359. } }
  7360. },
  7361. addOverlay: methodOp(function(spec, options) {
  7362. var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec)
  7363. if (mode.startState) { throw new Error("Overlays may not be stateful.") }
  7364. insertSorted(this.state.overlays,
  7365. {mode: mode, modeSpec: spec, opaque: options && options.opaque,
  7366. priority: (options && options.priority) || 0},
  7367. function (overlay) { return overlay.priority; })
  7368. this.state.modeGen++
  7369. regChange(this)
  7370. }),
  7371. removeOverlay: methodOp(function(spec) {
  7372. var this$1 = this;
  7373. var overlays = this.state.overlays
  7374. for (var i = 0; i < overlays.length; ++i) {
  7375. var cur = overlays[i].modeSpec
  7376. if (cur == spec || typeof spec == "string" && cur.name == spec) {
  7377. overlays.splice(i, 1)
  7378. this$1.state.modeGen++
  7379. regChange(this$1)
  7380. return
  7381. }
  7382. }
  7383. }),
  7384. indentLine: methodOp(function(n, dir, aggressive) {
  7385. if (typeof dir != "string" && typeof dir != "number") {
  7386. if (dir == null) { dir = this.options.smartIndent ? "smart" : "prev" }
  7387. else { dir = dir ? "add" : "subtract" }
  7388. }
  7389. if (isLine(this.doc, n)) { indentLine(this, n, dir, aggressive) }
  7390. }),
  7391. indentSelection: methodOp(function(how) {
  7392. var this$1 = this;
  7393. var ranges = this.doc.sel.ranges, end = -1
  7394. for (var i = 0; i < ranges.length; i++) {
  7395. var range = ranges[i]
  7396. if (!range.empty()) {
  7397. var from = range.from(), to = range.to()
  7398. var start = Math.max(end, from.line)
  7399. end = Math.min(this$1.lastLine(), to.line - (to.ch ? 0 : 1)) + 1
  7400. for (var j = start; j < end; ++j)
  7401. { indentLine(this$1, j, how) }
  7402. var newRanges = this$1.doc.sel.ranges
  7403. if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i].from().ch > 0)
  7404. { replaceOneSelection(this$1.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll) }
  7405. } else if (range.head.line > end) {
  7406. indentLine(this$1, range.head.line, how, true)
  7407. end = range.head.line
  7408. if (i == this$1.doc.sel.primIndex) { ensureCursorVisible(this$1) }
  7409. }
  7410. }
  7411. }),
  7412. // Fetch the parser token for a given character. Useful for hacks
  7413. // that want to inspect the mode state (say, for completion).
  7414. getTokenAt: function(pos, precise) {
  7415. return takeToken(this, pos, precise)
  7416. },
  7417. getLineTokens: function(line, precise) {
  7418. return takeToken(this, Pos(line), precise, true)
  7419. },
  7420. getTokenTypeAt: function(pos) {
  7421. pos = clipPos(this.doc, pos)
  7422. var styles = getLineStyles(this, getLine(this.doc, pos.line))
  7423. var before = 0, after = (styles.length - 1) / 2, ch = pos.ch
  7424. var type
  7425. if (ch == 0) { type = styles[2] }
  7426. else { for (;;) {
  7427. var mid = (before + after) >> 1
  7428. if ((mid ? styles[mid * 2 - 1] : 0) >= ch) { after = mid }
  7429. else if (styles[mid * 2 + 1] < ch) { before = mid + 1 }
  7430. else { type = styles[mid * 2 + 2]; break }
  7431. } }
  7432. var cut = type ? type.indexOf("overlay ") : -1
  7433. return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1)
  7434. },
  7435. getModeAt: function(pos) {
  7436. var mode = this.doc.mode
  7437. if (!mode.innerMode) { return mode }
  7438. return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode
  7439. },
  7440. getHelper: function(pos, type) {
  7441. return this.getHelpers(pos, type)[0]
  7442. },
  7443. getHelpers: function(pos, type) {
  7444. var this$1 = this;
  7445. var found = []
  7446. if (!helpers.hasOwnProperty(type)) { return found }
  7447. var help = helpers[type], mode = this.getModeAt(pos)
  7448. if (typeof mode[type] == "string") {
  7449. if (help[mode[type]]) { found.push(help[mode[type]]) }
  7450. } else if (mode[type]) {
  7451. for (var i = 0; i < mode[type].length; i++) {
  7452. var val = help[mode[type][i]]
  7453. if (val) { found.push(val) }
  7454. }
  7455. } else if (mode.helperType && help[mode.helperType]) {
  7456. found.push(help[mode.helperType])
  7457. } else if (help[mode.name]) {
  7458. found.push(help[mode.name])
  7459. }
  7460. for (var i$1 = 0; i$1 < help._global.length; i$1++) {
  7461. var cur = help._global[i$1]
  7462. if (cur.pred(mode, this$1) && indexOf(found, cur.val) == -1)
  7463. { found.push(cur.val) }
  7464. }
  7465. return found
  7466. },
  7467. getStateAfter: function(line, precise) {
  7468. var doc = this.doc
  7469. line = clipLine(doc, line == null ? doc.first + doc.size - 1: line)
  7470. return getContextBefore(this, line + 1, precise).state
  7471. },
  7472. cursorCoords: function(start, mode) {
  7473. var pos, range = this.doc.sel.primary()
  7474. if (start == null) { pos = range.head }
  7475. else if (typeof start == "object") { pos = clipPos(this.doc, start) }
  7476. else { pos = start ? range.from() : range.to() }
  7477. return cursorCoords(this, pos, mode || "page")
  7478. },
  7479. charCoords: function(pos, mode) {
  7480. return charCoords(this, clipPos(this.doc, pos), mode || "page")
  7481. },
  7482. coordsChar: function(coords, mode) {
  7483. coords = fromCoordSystem(this, coords, mode || "page")
  7484. return coordsChar(this, coords.left, coords.top)
  7485. },
  7486. lineAtHeight: function(height, mode) {
  7487. height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top
  7488. return lineAtHeight(this.doc, height + this.display.viewOffset)
  7489. },
  7490. heightAtLine: function(line, mode, includeWidgets) {
  7491. var end = false, lineObj
  7492. if (typeof line == "number") {
  7493. var last = this.doc.first + this.doc.size - 1
  7494. if (line < this.doc.first) { line = this.doc.first }
  7495. else if (line > last) { line = last; end = true }
  7496. lineObj = getLine(this.doc, line)
  7497. } else {
  7498. lineObj = line
  7499. }
  7500. return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || "page", includeWidgets || end).top +
  7501. (end ? this.doc.height - heightAtLine(lineObj) : 0)
  7502. },
  7503. defaultTextHeight: function() { return textHeight(this.display) },
  7504. defaultCharWidth: function() { return charWidth(this.display) },
  7505. getViewport: function() { return {from: this.display.viewFrom, to: this.display.viewTo}},
  7506. addWidget: function(pos, node, scroll, vert, horiz) {
  7507. var display = this.display
  7508. pos = cursorCoords(this, clipPos(this.doc, pos))
  7509. var top = pos.bottom, left = pos.left
  7510. node.style.position = "absolute"
  7511. node.setAttribute("cm-ignore-events", "true")
  7512. this.display.input.setUneditable(node)
  7513. display.sizer.appendChild(node)
  7514. if (vert == "over") {
  7515. top = pos.top
  7516. } else if (vert == "above" || vert == "near") {
  7517. var vspace = Math.max(display.wrapper.clientHeight, this.doc.height),
  7518. hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth)
  7519. // Default to positioning above (if specified and possible); otherwise default to positioning below
  7520. if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight)
  7521. { top = pos.top - node.offsetHeight }
  7522. else if (pos.bottom + node.offsetHeight <= vspace)
  7523. { top = pos.bottom }
  7524. if (left + node.offsetWidth > hspace)
  7525. { left = hspace - node.offsetWidth }
  7526. }
  7527. node.style.top = top + "px"
  7528. node.style.left = node.style.right = ""
  7529. if (horiz == "right") {
  7530. left = display.sizer.clientWidth - node.offsetWidth
  7531. node.style.right = "0px"
  7532. } else {
  7533. if (horiz == "left") { left = 0 }
  7534. else if (horiz == "middle") { left = (display.sizer.clientWidth - node.offsetWidth) / 2 }
  7535. node.style.left = left + "px"
  7536. }
  7537. if (scroll)
  7538. { scrollIntoView(this, {left: left, top: top, right: left + node.offsetWidth, bottom: top + node.offsetHeight}) }
  7539. },
  7540. triggerOnKeyDown: methodOp(onKeyDown),
  7541. triggerOnKeyPress: methodOp(onKeyPress),
  7542. triggerOnKeyUp: onKeyUp,
  7543. triggerOnMouseDown: methodOp(onMouseDown),
  7544. execCommand: function(cmd) {
  7545. if (commands.hasOwnProperty(cmd))
  7546. { return commands[cmd].call(null, this) }
  7547. },
  7548. triggerElectric: methodOp(function(text) { triggerElectric(this, text) }),
  7549. findPosH: function(from, amount, unit, visually) {
  7550. var this$1 = this;
  7551. var dir = 1
  7552. if (amount < 0) { dir = -1; amount = -amount }
  7553. var cur = clipPos(this.doc, from)
  7554. for (var i = 0; i < amount; ++i) {
  7555. cur = findPosH(this$1.doc, cur, dir, unit, visually)
  7556. if (cur.hitSide) { break }
  7557. }
  7558. return cur
  7559. },
  7560. moveH: methodOp(function(dir, unit) {
  7561. var this$1 = this;
  7562. this.extendSelectionsBy(function (range) {
  7563. if (this$1.display.shift || this$1.doc.extend || range.empty())
  7564. { return findPosH(this$1.doc, range.head, dir, unit, this$1.options.rtlMoveVisually) }
  7565. else
  7566. { return dir < 0 ? range.from() : range.to() }
  7567. }, sel_move)
  7568. }),
  7569. deleteH: methodOp(function(dir, unit) {
  7570. var sel = this.doc.sel, doc = this.doc
  7571. if (sel.somethingSelected())
  7572. { doc.replaceSelection("", null, "+delete") }
  7573. else
  7574. { deleteNearSelection(this, function (range) {
  7575. var other = findPosH(doc, range.head, dir, unit, false)
  7576. return dir < 0 ? {from: other, to: range.head} : {from: range.head, to: other}
  7577. }) }
  7578. }),
  7579. findPosV: function(from, amount, unit, goalColumn) {
  7580. var this$1 = this;
  7581. var dir = 1, x = goalColumn
  7582. if (amount < 0) { dir = -1; amount = -amount }
  7583. var cur = clipPos(this.doc, from)
  7584. for (var i = 0; i < amount; ++i) {
  7585. var coords = cursorCoords(this$1, cur, "div")
  7586. if (x == null) { x = coords.left }
  7587. else { coords.left = x }
  7588. cur = findPosV(this$1, coords, dir, unit)
  7589. if (cur.hitSide) { break }
  7590. }
  7591. return cur
  7592. },
  7593. moveV: methodOp(function(dir, unit) {
  7594. var this$1 = this;
  7595. var doc = this.doc, goals = []
  7596. var collapse = !this.display.shift && !doc.extend && doc.sel.somethingSelected()
  7597. doc.extendSelectionsBy(function (range) {
  7598. if (collapse)
  7599. { return dir < 0 ? range.from() : range.to() }
  7600. var headPos = cursorCoords(this$1, range.head, "div")
  7601. if (range.goalColumn != null) { headPos.left = range.goalColumn }
  7602. goals.push(headPos.left)
  7603. var pos = findPosV(this$1, headPos, dir, unit)
  7604. if (unit == "page" && range == doc.sel.primary())
  7605. { addToScrollTop(this$1, charCoords(this$1, pos, "div").top - headPos.top) }
  7606. return pos
  7607. }, sel_move)
  7608. if (goals.length) { for (var i = 0; i < doc.sel.ranges.length; i++)
  7609. { doc.sel.ranges[i].goalColumn = goals[i] } }
  7610. }),
  7611. // Find the word at the given position (as returned by coordsChar).
  7612. findWordAt: function(pos) {
  7613. var doc = this.doc, line = getLine(doc, pos.line).text
  7614. var start = pos.ch, end = pos.ch
  7615. if (line) {
  7616. var helper = this.getHelper(pos, "wordChars")
  7617. if ((pos.sticky == "before" || end == line.length) && start) { --start; } else { ++end }
  7618. var startChar = line.charAt(start)
  7619. var check = isWordChar(startChar, helper)
  7620. ? function (ch) { return isWordChar(ch, helper); }
  7621. : /\s/.test(startChar) ? function (ch) { return /\s/.test(ch); }
  7622. : function (ch) { return (!/\s/.test(ch) && !isWordChar(ch)); }
  7623. while (start > 0 && check(line.charAt(start - 1))) { --start }
  7624. while (end < line.length && check(line.charAt(end))) { ++end }
  7625. }
  7626. return new Range(Pos(pos.line, start), Pos(pos.line, end))
  7627. },
  7628. toggleOverwrite: function(value) {
  7629. if (value != null && value == this.state.overwrite) { return }
  7630. if (this.state.overwrite = !this.state.overwrite)
  7631. { addClass(this.display.cursorDiv, "CodeMirror-overwrite") }
  7632. else
  7633. { rmClass(this.display.cursorDiv, "CodeMirror-overwrite") }
  7634. signal(this, "overwriteToggle", this, this.state.overwrite)
  7635. },
  7636. hasFocus: function() { return this.display.input.getField() == activeElt() },
  7637. isReadOnly: function() { return !!(this.options.readOnly || this.doc.cantEdit) },
  7638. scrollTo: methodOp(function (x, y) { scrollToCoords(this, x, y) }),
  7639. getScrollInfo: function() {
  7640. var scroller = this.display.scroller
  7641. return {left: scroller.scrollLeft, top: scroller.scrollTop,
  7642. height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight,
  7643. width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth,
  7644. clientHeight: displayHeight(this), clientWidth: displayWidth(this)}
  7645. },
  7646. scrollIntoView: methodOp(function(range, margin) {
  7647. if (range == null) {
  7648. range = {from: this.doc.sel.primary().head, to: null}
  7649. if (margin == null) { margin = this.options.cursorScrollMargin }
  7650. } else if (typeof range == "number") {
  7651. range = {from: Pos(range, 0), to: null}
  7652. } else if (range.from == null) {
  7653. range = {from: range, to: null}
  7654. }
  7655. if (!range.to) { range.to = range.from }
  7656. range.margin = margin || 0
  7657. if (range.from.line != null) {
  7658. scrollToRange(this, range)
  7659. } else {
  7660. scrollToCoordsRange(this, range.from, range.to, range.margin)
  7661. }
  7662. }),
  7663. setSize: methodOp(function(width, height) {
  7664. var this$1 = this;
  7665. var interpret = function (val) { return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val; }
  7666. if (width != null) { this.display.wrapper.style.width = interpret(width) }
  7667. if (height != null) { this.display.wrapper.style.height = interpret(height) }
  7668. if (this.options.lineWrapping) { clearLineMeasurementCache(this) }
  7669. var lineNo = this.display.viewFrom
  7670. this.doc.iter(lineNo, this.display.viewTo, function (line) {
  7671. if (line.widgets) { for (var i = 0; i < line.widgets.length; i++)
  7672. { if (line.widgets[i].noHScroll) { regLineChange(this$1, lineNo, "widget"); break } } }
  7673. ++lineNo
  7674. })
  7675. this.curOp.forceUpdate = true
  7676. signal(this, "refresh", this)
  7677. }),
  7678. operation: function(f){return runInOp(this, f)},
  7679. startOperation: function(){return startOperation(this)},
  7680. endOperation: function(){return endOperation(this)},
  7681. refresh: methodOp(function() {
  7682. var oldHeight = this.display.cachedTextHeight
  7683. regChange(this)
  7684. this.curOp.forceUpdate = true
  7685. clearCaches(this)
  7686. scrollToCoords(this, this.doc.scrollLeft, this.doc.scrollTop)
  7687. updateGutterSpace(this)
  7688. if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5)
  7689. { estimateLineHeights(this) }
  7690. signal(this, "refresh", this)
  7691. }),
  7692. swapDoc: methodOp(function(doc) {
  7693. var old = this.doc
  7694. old.cm = null
  7695. attachDoc(this, doc)
  7696. clearCaches(this)
  7697. this.display.input.reset()
  7698. scrollToCoords(this, doc.scrollLeft, doc.scrollTop)
  7699. this.curOp.forceScroll = true
  7700. signalLater(this, "swapDoc", this, old)
  7701. return old
  7702. }),
  7703. getInputField: function(){return this.display.input.getField()},
  7704. getWrapperElement: function(){return this.display.wrapper},
  7705. getScrollerElement: function(){return this.display.scroller},
  7706. getGutterElement: function(){return this.display.gutters}
  7707. }
  7708. eventMixin(CodeMirror)
  7709. CodeMirror.registerHelper = function(type, name, value) {
  7710. if (!helpers.hasOwnProperty(type)) { helpers[type] = CodeMirror[type] = {_global: []} }
  7711. helpers[type][name] = value
  7712. }
  7713. CodeMirror.registerGlobalHelper = function(type, name, predicate, value) {
  7714. CodeMirror.registerHelper(type, name, value)
  7715. helpers[type]._global.push({pred: predicate, val: value})
  7716. }
  7717. }
  7718. // Used for horizontal relative motion. Dir is -1 or 1 (left or
  7719. // right), unit can be "char", "column" (like char, but doesn't
  7720. // cross line boundaries), "word" (across next word), or "group" (to
  7721. // the start of next group of word or non-word-non-whitespace
  7722. // chars). The visually param controls whether, in right-to-left
  7723. // text, direction 1 means to move towards the next index in the
  7724. // string, or towards the character to the right of the current
  7725. // position. The resulting position will have a hitSide=true
  7726. // property if it reached the end of the document.
  7727. function findPosH(doc, pos, dir, unit, visually) {
  7728. var oldPos = pos
  7729. var origDir = dir
  7730. var lineObj = getLine(doc, pos.line)
  7731. function findNextLine() {
  7732. var l = pos.line + dir
  7733. if (l < doc.first || l >= doc.first + doc.size) { return false }
  7734. pos = new Pos(l, pos.ch, pos.sticky)
  7735. return lineObj = getLine(doc, l)
  7736. }
  7737. function moveOnce(boundToLine) {
  7738. var next
  7739. if (visually) {
  7740. next = moveVisually(doc.cm, lineObj, pos, dir)
  7741. } else {
  7742. next = moveLogically(lineObj, pos, dir)
  7743. }
  7744. if (next == null) {
  7745. if (!boundToLine && findNextLine())
  7746. { pos = endOfLine(visually, doc.cm, lineObj, pos.line, dir) }
  7747. else
  7748. { return false }
  7749. } else {
  7750. pos = next
  7751. }
  7752. return true
  7753. }
  7754. if (unit == "char") {
  7755. moveOnce()
  7756. } else if (unit == "column") {
  7757. moveOnce(true)
  7758. } else if (unit == "word" || unit == "group") {
  7759. var sawType = null, group = unit == "group"
  7760. var helper = doc.cm && doc.cm.getHelper(pos, "wordChars")
  7761. for (var first = true;; first = false) {
  7762. if (dir < 0 && !moveOnce(!first)) { break }
  7763. var cur = lineObj.text.charAt(pos.ch) || "\n"
  7764. var type = isWordChar(cur, helper) ? "w"
  7765. : group && cur == "\n" ? "n"
  7766. : !group || /\s/.test(cur) ? null
  7767. : "p"
  7768. if (group && !first && !type) { type = "s" }
  7769. if (sawType && sawType != type) {
  7770. if (dir < 0) {dir = 1; moveOnce(); pos.sticky = "after"}
  7771. break
  7772. }
  7773. if (type) { sawType = type }
  7774. if (dir > 0 && !moveOnce(!first)) { break }
  7775. }
  7776. }
  7777. var result = skipAtomic(doc, pos, oldPos, origDir, true)
  7778. if (equalCursorPos(oldPos, result)) { result.hitSide = true }
  7779. return result
  7780. }
  7781. // For relative vertical movement. Dir may be -1 or 1. Unit can be
  7782. // "page" or "line". The resulting position will have a hitSide=true
  7783. // property if it reached the end of the document.
  7784. function findPosV(cm, pos, dir, unit) {
  7785. var doc = cm.doc, x = pos.left, y
  7786. if (unit == "page") {
  7787. var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight)
  7788. var moveAmount = Math.max(pageSize - .5 * textHeight(cm.display), 3)
  7789. y = (dir > 0 ? pos.bottom : pos.top) + dir * moveAmount
  7790. } else if (unit == "line") {
  7791. y = dir > 0 ? pos.bottom + 3 : pos.top - 3
  7792. }
  7793. var target
  7794. for (;;) {
  7795. target = coordsChar(cm, x, y)
  7796. if (!target.outside) { break }
  7797. if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break }
  7798. y += dir * 5
  7799. }
  7800. return target
  7801. }
  7802. // CONTENTEDITABLE INPUT STYLE
  7803. var ContentEditableInput = function(cm) {
  7804. this.cm = cm
  7805. this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null
  7806. this.polling = new Delayed()
  7807. this.composing = null
  7808. this.gracePeriod = false
  7809. this.readDOMTimeout = null
  7810. };
  7811. ContentEditableInput.prototype.init = function (display) {
  7812. var this$1 = this;
  7813. var input = this, cm = input.cm
  7814. var div = input.div = display.lineDiv
  7815. disableBrowserMagic(div, cm.options.spellcheck)
  7816. on(div, "paste", function (e) {
  7817. if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { return }
  7818. // IE doesn't fire input events, so we schedule a read for the pasted content in this way
  7819. if (ie_version <= 11) { setTimeout(operation(cm, function () { return this$1.updateFromDOM(); }), 20) }
  7820. })
  7821. on(div, "compositionstart", function (e) {
  7822. this$1.composing = {data: e.data, done: false}
  7823. })
  7824. on(div, "compositionupdate", function (e) {
  7825. if (!this$1.composing) { this$1.composing = {data: e.data, done: false} }
  7826. })
  7827. on(div, "compositionend", function (e) {
  7828. if (this$1.composing) {
  7829. if (e.data != this$1.composing.data) { this$1.readFromDOMSoon() }
  7830. this$1.composing.done = true
  7831. }
  7832. })
  7833. on(div, "touchstart", function () { return input.forceCompositionEnd(); })
  7834. on(div, "input", function () {
  7835. if (!this$1.composing) { this$1.readFromDOMSoon() }
  7836. })
  7837. function onCopyCut(e) {
  7838. if (signalDOMEvent(cm, e)) { return }
  7839. if (cm.somethingSelected()) {
  7840. setLastCopied({lineWise: false, text: cm.getSelections()})
  7841. if (e.type == "cut") { cm.replaceSelection("", null, "cut") }
  7842. } else if (!cm.options.lineWiseCopyCut) {
  7843. return
  7844. } else {
  7845. var ranges = copyableRanges(cm)
  7846. setLastCopied({lineWise: true, text: ranges.text})
  7847. if (e.type == "cut") {
  7848. cm.operation(function () {
  7849. cm.setSelections(ranges.ranges, 0, sel_dontScroll)
  7850. cm.replaceSelection("", null, "cut")
  7851. })
  7852. }
  7853. }
  7854. if (e.clipboardData) {
  7855. e.clipboardData.clearData()
  7856. var content = lastCopied.text.join("\n")
  7857. // iOS exposes the clipboard API, but seems to discard content inserted into it
  7858. e.clipboardData.setData("Text", content)
  7859. if (e.clipboardData.getData("Text") == content) {
  7860. e.preventDefault()
  7861. return
  7862. }
  7863. }
  7864. // Old-fashioned briefly-focus-a-textarea hack
  7865. var kludge = hiddenTextarea(), te = kludge.firstChild
  7866. cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild)
  7867. te.value = lastCopied.text.join("\n")
  7868. var hadFocus = document.activeElement
  7869. selectInput(te)
  7870. setTimeout(function () {
  7871. cm.display.lineSpace.removeChild(kludge)
  7872. hadFocus.focus()
  7873. if (hadFocus == div) { input.showPrimarySelection() }
  7874. }, 50)
  7875. }
  7876. on(div, "copy", onCopyCut)
  7877. on(div, "cut", onCopyCut)
  7878. };
  7879. ContentEditableInput.prototype.prepareSelection = function () {
  7880. var result = prepareSelection(this.cm, false)
  7881. result.focus = this.cm.state.focused
  7882. return result
  7883. };
  7884. ContentEditableInput.prototype.showSelection = function (info, takeFocus) {
  7885. if (!info || !this.cm.display.view.length) { return }
  7886. if (info.focus || takeFocus) { this.showPrimarySelection() }
  7887. this.showMultipleSelections(info)
  7888. };
  7889. ContentEditableInput.prototype.showPrimarySelection = function () {
  7890. var sel = window.getSelection(), cm = this.cm, prim = cm.doc.sel.primary()
  7891. var from = prim.from(), to = prim.to()
  7892. if (cm.display.viewTo == cm.display.viewFrom || from.line >= cm.display.viewTo || to.line < cm.display.viewFrom) {
  7893. sel.removeAllRanges()
  7894. return
  7895. }
  7896. var curAnchor = domToPos(cm, sel.anchorNode, sel.anchorOffset)
  7897. var curFocus = domToPos(cm, sel.focusNode, sel.focusOffset)
  7898. if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad &&
  7899. cmp(minPos(curAnchor, curFocus), from) == 0 &&
  7900. cmp(maxPos(curAnchor, curFocus), to) == 0)
  7901. { return }
  7902. var view = cm.display.view
  7903. var start = (from.line >= cm.display.viewFrom && posToDOM(cm, from)) ||
  7904. {node: view[0].measure.map[2], offset: 0}
  7905. var end = to.line < cm.display.viewTo && posToDOM(cm, to)
  7906. if (!end) {
  7907. var measure = view[view.length - 1].measure
  7908. var map = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map
  7909. end = {node: map[map.length - 1], offset: map[map.length - 2] - map[map.length - 3]}
  7910. }
  7911. if (!start || !end) {
  7912. sel.removeAllRanges()
  7913. return
  7914. }
  7915. var old = sel.rangeCount && sel.getRangeAt(0), rng
  7916. try { rng = range(start.node, start.offset, end.offset, end.node) }
  7917. catch(e) {} // Our model of the DOM might be outdated, in which case the range we try to set can be impossible
  7918. if (rng) {
  7919. if (!gecko && cm.state.focused) {
  7920. sel.collapse(start.node, start.offset)
  7921. if (!rng.collapsed) {
  7922. sel.removeAllRanges()
  7923. sel.addRange(rng)
  7924. }
  7925. } else {
  7926. sel.removeAllRanges()
  7927. sel.addRange(rng)
  7928. }
  7929. if (old && sel.anchorNode == null) { sel.addRange(old) }
  7930. else if (gecko) { this.startGracePeriod() }
  7931. }
  7932. this.rememberSelection()
  7933. };
  7934. ContentEditableInput.prototype.startGracePeriod = function () {
  7935. var this$1 = this;
  7936. clearTimeout(this.gracePeriod)
  7937. this.gracePeriod = setTimeout(function () {
  7938. this$1.gracePeriod = false
  7939. if (this$1.selectionChanged())
  7940. { this$1.cm.operation(function () { return this$1.cm.curOp.selectionChanged = true; }) }
  7941. }, 20)
  7942. };
  7943. ContentEditableInput.prototype.showMultipleSelections = function (info) {
  7944. removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors)
  7945. removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection)
  7946. };
  7947. ContentEditableInput.prototype.rememberSelection = function () {
  7948. var sel = window.getSelection()
  7949. this.lastAnchorNode = sel.anchorNode; this.lastAnchorOffset = sel.anchorOffset
  7950. this.lastFocusNode = sel.focusNode; this.lastFocusOffset = sel.focusOffset
  7951. };
  7952. ContentEditableInput.prototype.selectionInEditor = function () {
  7953. var sel = window.getSelection()
  7954. if (!sel.rangeCount) { return false }
  7955. var node = sel.getRangeAt(0).commonAncestorContainer
  7956. return contains(this.div, node)
  7957. };
  7958. ContentEditableInput.prototype.focus = function () {
  7959. if (this.cm.options.readOnly != "nocursor") {
  7960. if (!this.selectionInEditor())
  7961. { this.showSelection(this.prepareSelection(), true) }
  7962. this.div.focus()
  7963. }
  7964. };
  7965. ContentEditableInput.prototype.blur = function () { this.div.blur() };
  7966. ContentEditableInput.prototype.getField = function () { return this.div };
  7967. ContentEditableInput.prototype.supportsTouch = function () { return true };
  7968. ContentEditableInput.prototype.receivedFocus = function () {
  7969. var input = this
  7970. if (this.selectionInEditor())
  7971. { this.pollSelection() }
  7972. else
  7973. { runInOp(this.cm, function () { return input.cm.curOp.selectionChanged = true; }) }
  7974. function poll() {
  7975. if (input.cm.state.focused) {
  7976. input.pollSelection()
  7977. input.polling.set(input.cm.options.pollInterval, poll)
  7978. }
  7979. }
  7980. this.polling.set(this.cm.options.pollInterval, poll)
  7981. };
  7982. ContentEditableInput.prototype.selectionChanged = function () {
  7983. var sel = window.getSelection()
  7984. return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset ||
  7985. sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset
  7986. };
  7987. ContentEditableInput.prototype.pollSelection = function () {
  7988. if (this.readDOMTimeout != null || this.gracePeriod || !this.selectionChanged()) { return }
  7989. var sel = window.getSelection(), cm = this.cm
  7990. // On Android Chrome (version 56, at least), backspacing into an
  7991. // uneditable block element will put the cursor in that element,
  7992. // and then, because it's not editable, hide the virtual keyboard.
  7993. // Because Android doesn't allow us to actually detect backspace
  7994. // presses in a sane way, this code checks for when that happens
  7995. // and simulates a backspace press in this case.
  7996. if (android && chrome && this.cm.options.gutters.length && isInGutter(sel.anchorNode)) {
  7997. this.cm.triggerOnKeyDown({type: "keydown", keyCode: 8, preventDefault: Math.abs})
  7998. this.blur()
  7999. this.focus()
  8000. return
  8001. }
  8002. if (this.composing) { return }
  8003. this.rememberSelection()
  8004. var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset)
  8005. var head = domToPos(cm, sel.focusNode, sel.focusOffset)
  8006. if (anchor && head) { runInOp(cm, function () {
  8007. setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll)
  8008. if (anchor.bad || head.bad) { cm.curOp.selectionChanged = true }
  8009. }) }
  8010. };
  8011. ContentEditableInput.prototype.pollContent = function () {
  8012. if (this.readDOMTimeout != null) {
  8013. clearTimeout(this.readDOMTimeout)
  8014. this.readDOMTimeout = null
  8015. }
  8016. var cm = this.cm, display = cm.display, sel = cm.doc.sel.primary()
  8017. var from = sel.from(), to = sel.to()
  8018. if (from.ch == 0 && from.line > cm.firstLine())
  8019. { from = Pos(from.line - 1, getLine(cm.doc, from.line - 1).length) }
  8020. if (to.ch == getLine(cm.doc, to.line).text.length && to.line < cm.lastLine())
  8021. { to = Pos(to.line + 1, 0) }
  8022. if (from.line < display.viewFrom || to.line > display.viewTo - 1) { return false }
  8023. var fromIndex, fromLine, fromNode
  8024. if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) {
  8025. fromLine = lineNo(display.view[0].line)
  8026. fromNode = display.view[0].node
  8027. } else {
  8028. fromLine = lineNo(display.view[fromIndex].line)
  8029. fromNode = display.view[fromIndex - 1].node.nextSibling
  8030. }
  8031. var toIndex = findViewIndex(cm, to.line)
  8032. var toLine, toNode
  8033. if (toIndex == display.view.length - 1) {
  8034. toLine = display.viewTo - 1
  8035. toNode = display.lineDiv.lastChild
  8036. } else {
  8037. toLine = lineNo(display.view[toIndex + 1].line) - 1
  8038. toNode = display.view[toIndex + 1].node.previousSibling
  8039. }
  8040. if (!fromNode) { return false }
  8041. var newText = cm.doc.splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine))
  8042. var oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length))
  8043. while (newText.length > 1 && oldText.length > 1) {
  8044. if (lst(newText) == lst(oldText)) { newText.pop(); oldText.pop(); toLine-- }
  8045. else if (newText[0] == oldText[0]) { newText.shift(); oldText.shift(); fromLine++ }
  8046. else { break }
  8047. }
  8048. var cutFront = 0, cutEnd = 0
  8049. var newTop = newText[0], oldTop = oldText[0], maxCutFront = Math.min(newTop.length, oldTop.length)
  8050. while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront))
  8051. { ++cutFront }
  8052. var newBot = lst(newText), oldBot = lst(oldText)
  8053. var maxCutEnd = Math.min(newBot.length - (newText.length == 1 ? cutFront : 0),
  8054. oldBot.length - (oldText.length == 1 ? cutFront : 0))
  8055. while (cutEnd < maxCutEnd &&
  8056. newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1))
  8057. { ++cutEnd }
  8058. // Try to move start of change to start of selection if ambiguous
  8059. if (newText.length == 1 && oldText.length == 1 && fromLine == from.line) {
  8060. while (cutFront && cutFront > from.ch &&
  8061. newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) {
  8062. cutFront--
  8063. cutEnd++
  8064. }
  8065. }
  8066. newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd).replace(/^\u200b+/, "")
  8067. newText[0] = newText[0].slice(cutFront).replace(/\u200b+$/, "")
  8068. var chFrom = Pos(fromLine, cutFront)
  8069. var chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0)
  8070. if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) {
  8071. replaceRange(cm.doc, newText, chFrom, chTo, "+input")
  8072. return true
  8073. }
  8074. };
  8075. ContentEditableInput.prototype.ensurePolled = function () {
  8076. this.forceCompositionEnd()
  8077. };
  8078. ContentEditableInput.prototype.reset = function () {
  8079. this.forceCompositionEnd()
  8080. };
  8081. ContentEditableInput.prototype.forceCompositionEnd = function () {
  8082. if (!this.composing) { return }
  8083. clearTimeout(this.readDOMTimeout)
  8084. this.composing = null
  8085. this.updateFromDOM()
  8086. this.div.blur()
  8087. this.div.focus()
  8088. };
  8089. ContentEditableInput.prototype.readFromDOMSoon = function () {
  8090. var this$1 = this;
  8091. if (this.readDOMTimeout != null) { return }
  8092. this.readDOMTimeout = setTimeout(function () {
  8093. this$1.readDOMTimeout = null
  8094. if (this$1.composing) {
  8095. if (this$1.composing.done) { this$1.composing = null }
  8096. else { return }
  8097. }
  8098. this$1.updateFromDOM()
  8099. }, 80)
  8100. };
  8101. ContentEditableInput.prototype.updateFromDOM = function () {
  8102. var this$1 = this;
  8103. if (this.cm.isReadOnly() || !this.pollContent())
  8104. { runInOp(this.cm, function () { return regChange(this$1.cm); }) }
  8105. };
  8106. ContentEditableInput.prototype.setUneditable = function (node) {
  8107. node.contentEditable = "false"
  8108. };
  8109. ContentEditableInput.prototype.onKeyPress = function (e) {
  8110. if (e.charCode == 0) { return }
  8111. e.preventDefault()
  8112. if (!this.cm.isReadOnly())
  8113. { operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0) }
  8114. };
  8115. ContentEditableInput.prototype.readOnlyChanged = function (val) {
  8116. this.div.contentEditable = String(val != "nocursor")
  8117. };
  8118. ContentEditableInput.prototype.onContextMenu = function () {};
  8119. ContentEditableInput.prototype.resetPosition = function () {};
  8120. ContentEditableInput.prototype.needsContentAttribute = true
  8121. function posToDOM(cm, pos) {
  8122. var view = findViewForLine(cm, pos.line)
  8123. if (!view || view.hidden) { return null }
  8124. var line = getLine(cm.doc, pos.line)
  8125. var info = mapFromLineView(view, line, pos.line)
  8126. var order = getOrder(line, cm.doc.direction), side = "left"
  8127. if (order) {
  8128. var partPos = getBidiPartAt(order, pos.ch)
  8129. side = partPos % 2 ? "right" : "left"
  8130. }
  8131. var result = nodeAndOffsetInLineMap(info.map, pos.ch, side)
  8132. result.offset = result.collapse == "right" ? result.end : result.start
  8133. return result
  8134. }
  8135. function isInGutter(node) {
  8136. for (var scan = node; scan; scan = scan.parentNode)
  8137. { if (/CodeMirror-gutter-wrapper/.test(scan.className)) { return true } }
  8138. return false
  8139. }
  8140. function badPos(pos, bad) { if (bad) { pos.bad = true; } return pos }
  8141. function domTextBetween(cm, from, to, fromLine, toLine) {
  8142. var text = "", closing = false, lineSep = cm.doc.lineSeparator()
  8143. function recognizeMarker(id) { return function (marker) { return marker.id == id; } }
  8144. function close() {
  8145. if (closing) {
  8146. text += lineSep
  8147. closing = false
  8148. }
  8149. }
  8150. function addText(str) {
  8151. if (str) {
  8152. close()
  8153. text += str
  8154. }
  8155. }
  8156. function walk(node) {
  8157. if (node.nodeType == 1) {
  8158. var cmText = node.getAttribute("cm-text")
  8159. if (cmText != null) {
  8160. addText(cmText || node.textContent.replace(/\u200b/g, ""))
  8161. return
  8162. }
  8163. var markerID = node.getAttribute("cm-marker"), range
  8164. if (markerID) {
  8165. var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID))
  8166. if (found.length && (range = found[0].find(0)))
  8167. { addText(getBetween(cm.doc, range.from, range.to).join(lineSep)) }
  8168. return
  8169. }
  8170. if (node.getAttribute("contenteditable") == "false") { return }
  8171. var isBlock = /^(pre|div|p)$/i.test(node.nodeName)
  8172. if (isBlock) { close() }
  8173. for (var i = 0; i < node.childNodes.length; i++)
  8174. { walk(node.childNodes[i]) }
  8175. if (isBlock) { closing = true }
  8176. } else if (node.nodeType == 3) {
  8177. addText(node.nodeValue)
  8178. }
  8179. }
  8180. for (;;) {
  8181. walk(from)
  8182. if (from == to) { break }
  8183. from = from.nextSibling
  8184. }
  8185. return text
  8186. }
  8187. function domToPos(cm, node, offset) {
  8188. var lineNode
  8189. if (node == cm.display.lineDiv) {
  8190. lineNode = cm.display.lineDiv.childNodes[offset]
  8191. if (!lineNode) { return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true) }
  8192. node = null; offset = 0
  8193. } else {
  8194. for (lineNode = node;; lineNode = lineNode.parentNode) {
  8195. if (!lineNode || lineNode == cm.display.lineDiv) { return null }
  8196. if (lineNode.parentNode && lineNode.parentNode == cm.display.lineDiv) { break }
  8197. }
  8198. }
  8199. for (var i = 0; i < cm.display.view.length; i++) {
  8200. var lineView = cm.display.view[i]
  8201. if (lineView.node == lineNode)
  8202. { return locateNodeInLineView(lineView, node, offset) }
  8203. }
  8204. }
  8205. function locateNodeInLineView(lineView, node, offset) {
  8206. var wrapper = lineView.text.firstChild, bad = false
  8207. if (!node || !contains(wrapper, node)) { return badPos(Pos(lineNo(lineView.line), 0), true) }
  8208. if (node == wrapper) {
  8209. bad = true
  8210. node = wrapper.childNodes[offset]
  8211. offset = 0
  8212. if (!node) {
  8213. var line = lineView.rest ? lst(lineView.rest) : lineView.line
  8214. return badPos(Pos(lineNo(line), line.text.length), bad)
  8215. }
  8216. }
  8217. var textNode = node.nodeType == 3 ? node : null, topNode = node
  8218. if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) {
  8219. textNode = node.firstChild
  8220. if (offset) { offset = textNode.nodeValue.length }
  8221. }
  8222. while (topNode.parentNode != wrapper) { topNode = topNode.parentNode }
  8223. var measure = lineView.measure, maps = measure.maps
  8224. function find(textNode, topNode, offset) {
  8225. for (var i = -1; i < (maps ? maps.length : 0); i++) {
  8226. var map = i < 0 ? measure.map : maps[i]
  8227. for (var j = 0; j < map.length; j += 3) {
  8228. var curNode = map[j + 2]
  8229. if (curNode == textNode || curNode == topNode) {
  8230. var line = lineNo(i < 0 ? lineView.line : lineView.rest[i])
  8231. var ch = map[j] + offset
  8232. if (offset < 0 || curNode != textNode) { ch = map[j + (offset ? 1 : 0)] }
  8233. return Pos(line, ch)
  8234. }
  8235. }
  8236. }
  8237. }
  8238. var found = find(textNode, topNode, offset)
  8239. if (found) { return badPos(found, bad) }
  8240. // FIXME this is all really shaky. might handle the few cases it needs to handle, but likely to cause problems
  8241. for (var after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) {
  8242. found = find(after, after.firstChild, 0)
  8243. if (found)
  8244. { return badPos(Pos(found.line, found.ch - dist), bad) }
  8245. else
  8246. { dist += after.textContent.length }
  8247. }
  8248. for (var before = topNode.previousSibling, dist$1 = offset; before; before = before.previousSibling) {
  8249. found = find(before, before.firstChild, -1)
  8250. if (found)
  8251. { return badPos(Pos(found.line, found.ch + dist$1), bad) }
  8252. else
  8253. { dist$1 += before.textContent.length }
  8254. }
  8255. }
  8256. // TEXTAREA INPUT STYLE
  8257. var TextareaInput = function(cm) {
  8258. this.cm = cm
  8259. // See input.poll and input.reset
  8260. this.prevInput = ""
  8261. // Flag that indicates whether we expect input to appear real soon
  8262. // now (after some event like 'keypress' or 'input') and are
  8263. // polling intensively.
  8264. this.pollingFast = false
  8265. // Self-resetting timeout for the poller
  8266. this.polling = new Delayed()
  8267. // Used to work around IE issue with selection being forgotten when focus moves away from textarea
  8268. this.hasSelection = false
  8269. this.composing = null
  8270. };
  8271. TextareaInput.prototype.init = function (display) {
  8272. var this$1 = this;
  8273. var input = this, cm = this.cm
  8274. // Wraps and hides input textarea
  8275. var div = this.wrapper = hiddenTextarea()
  8276. // The semihidden textarea that is focused when the editor is
  8277. // focused, and receives input.
  8278. var te = this.textarea = div.firstChild
  8279. display.wrapper.insertBefore(div, display.wrapper.firstChild)
  8280. // Needed to hide big blue blinking cursor on Mobile Safari (doesn't seem to work in iOS 8 anymore)
  8281. if (ios) { te.style.width = "0px" }
  8282. on(te, "input", function () {
  8283. if (ie && ie_version >= 9 && this$1.hasSelection) { this$1.hasSelection = null }
  8284. input.poll()
  8285. })
  8286. on(te, "paste", function (e) {
  8287. if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { return }
  8288. cm.state.pasteIncoming = true
  8289. input.fastPoll()
  8290. })
  8291. function prepareCopyCut(e) {
  8292. if (signalDOMEvent(cm, e)) { return }
  8293. if (cm.somethingSelected()) {
  8294. setLastCopied({lineWise: false, text: cm.getSelections()})
  8295. } else if (!cm.options.lineWiseCopyCut) {
  8296. return
  8297. } else {
  8298. var ranges = copyableRanges(cm)
  8299. setLastCopied({lineWise: true, text: ranges.text})
  8300. if (e.type == "cut") {
  8301. cm.setSelections(ranges.ranges, null, sel_dontScroll)
  8302. } else {
  8303. input.prevInput = ""
  8304. te.value = ranges.text.join("\n")
  8305. selectInput(te)
  8306. }
  8307. }
  8308. if (e.type == "cut") { cm.state.cutIncoming = true }
  8309. }
  8310. on(te, "cut", prepareCopyCut)
  8311. on(te, "copy", prepareCopyCut)
  8312. on(display.scroller, "paste", function (e) {
  8313. if (eventInWidget(display, e) || signalDOMEvent(cm, e)) { return }
  8314. cm.state.pasteIncoming = true
  8315. input.focus()
  8316. })
  8317. // Prevent normal selection in the editor (we handle our own)
  8318. on(display.lineSpace, "selectstart", function (e) {
  8319. if (!eventInWidget(display, e)) { e_preventDefault(e) }
  8320. })
  8321. on(te, "compositionstart", function () {
  8322. var start = cm.getCursor("from")
  8323. if (input.composing) { input.composing.range.clear() }
  8324. input.composing = {
  8325. start: start,
  8326. range: cm.markText(start, cm.getCursor("to"), {className: "CodeMirror-composing"})
  8327. }
  8328. })
  8329. on(te, "compositionend", function () {
  8330. if (input.composing) {
  8331. input.poll()
  8332. input.composing.range.clear()
  8333. input.composing = null
  8334. }
  8335. })
  8336. };
  8337. TextareaInput.prototype.prepareSelection = function () {
  8338. // Redraw the selection and/or cursor
  8339. var cm = this.cm, display = cm.display, doc = cm.doc
  8340. var result = prepareSelection(cm)
  8341. // Move the hidden textarea near the cursor to prevent scrolling artifacts
  8342. if (cm.options.moveInputWithCursor) {
  8343. var headPos = cursorCoords(cm, doc.sel.primary().head, "div")
  8344. var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect()
  8345. result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10,
  8346. headPos.top + lineOff.top - wrapOff.top))
  8347. result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10,
  8348. headPos.left + lineOff.left - wrapOff.left))
  8349. }
  8350. return result
  8351. };
  8352. TextareaInput.prototype.showSelection = function (drawn) {
  8353. var cm = this.cm, display = cm.display
  8354. removeChildrenAndAdd(display.cursorDiv, drawn.cursors)
  8355. removeChildrenAndAdd(display.selectionDiv, drawn.selection)
  8356. if (drawn.teTop != null) {
  8357. this.wrapper.style.top = drawn.teTop + "px"
  8358. this.wrapper.style.left = drawn.teLeft + "px"
  8359. }
  8360. };
  8361. // Reset the input to correspond to the selection (or to be empty,
  8362. // when not typing and nothing is selected)
  8363. TextareaInput.prototype.reset = function (typing) {
  8364. if (this.contextMenuPending || this.composing) { return }
  8365. var cm = this.cm
  8366. if (cm.somethingSelected()) {
  8367. this.prevInput = ""
  8368. var content = cm.getSelection()
  8369. this.textarea.value = content
  8370. if (cm.state.focused) { selectInput(this.textarea) }
  8371. if (ie && ie_version >= 9) { this.hasSelection = content }
  8372. } else if (!typing) {
  8373. this.prevInput = this.textarea.value = ""
  8374. if (ie && ie_version >= 9) { this.hasSelection = null }
  8375. }
  8376. };
  8377. TextareaInput.prototype.getField = function () { return this.textarea };
  8378. TextareaInput.prototype.supportsTouch = function () { return false };
  8379. TextareaInput.prototype.focus = function () {
  8380. if (this.cm.options.readOnly != "nocursor" && (!mobile || activeElt() != this.textarea)) {
  8381. try { this.textarea.focus() }
  8382. catch (e) {} // IE8 will throw if the textarea is display: none or not in DOM
  8383. }
  8384. };
  8385. TextareaInput.prototype.blur = function () { this.textarea.blur() };
  8386. TextareaInput.prototype.resetPosition = function () {
  8387. this.wrapper.style.top = this.wrapper.style.left = 0
  8388. };
  8389. TextareaInput.prototype.receivedFocus = function () { this.slowPoll() };
  8390. // Poll for input changes, using the normal rate of polling. This
  8391. // runs as long as the editor is focused.
  8392. TextareaInput.prototype.slowPoll = function () {
  8393. var this$1 = this;
  8394. if (this.pollingFast) { return }
  8395. this.polling.set(this.cm.options.pollInterval, function () {
  8396. this$1.poll()
  8397. if (this$1.cm.state.focused) { this$1.slowPoll() }
  8398. })
  8399. };
  8400. // When an event has just come in that is likely to add or change
  8401. // something in the input textarea, we poll faster, to ensure that
  8402. // the change appears on the screen quickly.
  8403. TextareaInput.prototype.fastPoll = function () {
  8404. var missed = false, input = this
  8405. input.pollingFast = true
  8406. function p() {
  8407. var changed = input.poll()
  8408. if (!changed && !missed) {missed = true; input.polling.set(60, p)}
  8409. else {input.pollingFast = false; input.slowPoll()}
  8410. }
  8411. input.polling.set(20, p)
  8412. };
  8413. // Read input from the textarea, and update the document to match.
  8414. // When something is selected, it is present in the textarea, and
  8415. // selected (unless it is huge, in which case a placeholder is
  8416. // used). When nothing is selected, the cursor sits after previously
  8417. // seen text (can be empty), which is stored in prevInput (we must
  8418. // not reset the textarea when typing, because that breaks IME).
  8419. TextareaInput.prototype.poll = function () {
  8420. var this$1 = this;
  8421. var cm = this.cm, input = this.textarea, prevInput = this.prevInput
  8422. // Since this is called a *lot*, try to bail out as cheaply as
  8423. // possible when it is clear that nothing happened. hasSelection
  8424. // will be the case when there is a lot of text in the textarea,
  8425. // in which case reading its value would be expensive.
  8426. if (this.contextMenuPending || !cm.state.focused ||
  8427. (hasSelection(input) && !prevInput && !this.composing) ||
  8428. cm.isReadOnly() || cm.options.disableInput || cm.state.keySeq)
  8429. { return false }
  8430. var text = input.value
  8431. // If nothing changed, bail.
  8432. if (text == prevInput && !cm.somethingSelected()) { return false }
  8433. // Work around nonsensical selection resetting in IE9/10, and
  8434. // inexplicable appearance of private area unicode characters on
  8435. // some key combos in Mac (#2689).
  8436. if (ie && ie_version >= 9 && this.hasSelection === text ||
  8437. mac && /[\uf700-\uf7ff]/.test(text)) {
  8438. cm.display.input.reset()
  8439. return false
  8440. }
  8441. if (cm.doc.sel == cm.display.selForContextMenu) {
  8442. var first = text.charCodeAt(0)
  8443. if (first == 0x200b && !prevInput) { prevInput = "\u200b" }
  8444. if (first == 0x21da) { this.reset(); return this.cm.execCommand("undo") }
  8445. }
  8446. // Find the part of the input that is actually new
  8447. var same = 0, l = Math.min(prevInput.length, text.length)
  8448. while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) { ++same }
  8449. runInOp(cm, function () {
  8450. applyTextInput(cm, text.slice(same), prevInput.length - same,
  8451. null, this$1.composing ? "*compose" : null)
  8452. // Don't leave long text in the textarea, since it makes further polling slow
  8453. if (text.length > 1000 || text.indexOf("\n") > -1) { input.value = this$1.prevInput = "" }
  8454. else { this$1.prevInput = text }
  8455. if (this$1.composing) {
  8456. this$1.composing.range.clear()
  8457. this$1.composing.range = cm.markText(this$1.composing.start, cm.getCursor("to"),
  8458. {className: "CodeMirror-composing"})
  8459. }
  8460. })
  8461. return true
  8462. };
  8463. TextareaInput.prototype.ensurePolled = function () {
  8464. if (this.pollingFast && this.poll()) { this.pollingFast = false }
  8465. };
  8466. TextareaInput.prototype.onKeyPress = function () {
  8467. if (ie && ie_version >= 9) { this.hasSelection = null }
  8468. this.fastPoll()
  8469. };
  8470. TextareaInput.prototype.onContextMenu = function (e) {
  8471. var input = this, cm = input.cm, display = cm.display, te = input.textarea
  8472. var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop
  8473. if (!pos || presto) { return } // Opera is difficult.
  8474. // Reset the current text selection only if the click is done outside of the selection
  8475. // and 'resetSelectionOnContextMenu' option is true.
  8476. var reset = cm.options.resetSelectionOnContextMenu
  8477. if (reset && cm.doc.sel.contains(pos) == -1)
  8478. { operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll) }
  8479. var oldCSS = te.style.cssText, oldWrapperCSS = input.wrapper.style.cssText
  8480. input.wrapper.style.cssText = "position: absolute"
  8481. var wrapperBox = input.wrapper.getBoundingClientRect()
  8482. 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);"
  8483. var oldScrollY
  8484. if (webkit) { oldScrollY = window.scrollY } // Work around Chrome issue (#2712)
  8485. display.input.focus()
  8486. if (webkit) { window.scrollTo(null, oldScrollY) }
  8487. display.input.reset()
  8488. // Adds "Select all" to context menu in FF
  8489. if (!cm.somethingSelected()) { te.value = input.prevInput = " " }
  8490. input.contextMenuPending = true
  8491. display.selForContextMenu = cm.doc.sel
  8492. clearTimeout(display.detectingSelectAll)
  8493. // Select-all will be greyed out if there's nothing to select, so
  8494. // this adds a zero-width space so that we can later check whether
  8495. // it got selected.
  8496. function prepareSelectAllHack() {
  8497. if (te.selectionStart != null) {
  8498. var selected = cm.somethingSelected()
  8499. var extval = "\u200b" + (selected ? te.value : "")
  8500. te.value = "\u21da" // Used to catch context-menu undo
  8501. te.value = extval
  8502. input.prevInput = selected ? "" : "\u200b"
  8503. te.selectionStart = 1; te.selectionEnd = extval.length
  8504. // Re-set this, in case some other handler touched the
  8505. // selection in the meantime.
  8506. display.selForContextMenu = cm.doc.sel
  8507. }
  8508. }
  8509. function rehide() {
  8510. input.contextMenuPending = false
  8511. input.wrapper.style.cssText = oldWrapperCSS
  8512. te.style.cssText = oldCSS
  8513. if (ie && ie_version < 9) { display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos) }
  8514. // Try to detect the user choosing select-all
  8515. if (te.selectionStart != null) {
  8516. if (!ie || (ie && ie_version < 9)) { prepareSelectAllHack() }
  8517. var i = 0, poll = function () {
  8518. if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0 &&
  8519. te.selectionEnd > 0 && input.prevInput == "\u200b") {
  8520. operation(cm, selectAll)(cm)
  8521. } else if (i++ < 10) {
  8522. display.detectingSelectAll = setTimeout(poll, 500)
  8523. } else {
  8524. display.selForContextMenu = null
  8525. display.input.reset()
  8526. }
  8527. }
  8528. display.detectingSelectAll = setTimeout(poll, 200)
  8529. }
  8530. }
  8531. if (ie && ie_version >= 9) { prepareSelectAllHack() }
  8532. if (captureRightClick) {
  8533. e_stop(e)
  8534. var mouseup = function () {
  8535. off(window, "mouseup", mouseup)
  8536. setTimeout(rehide, 20)
  8537. }
  8538. on(window, "mouseup", mouseup)
  8539. } else {
  8540. setTimeout(rehide, 50)
  8541. }
  8542. };
  8543. TextareaInput.prototype.readOnlyChanged = function (val) {
  8544. if (!val) { this.reset() }
  8545. this.textarea.disabled = val == "nocursor"
  8546. };
  8547. TextareaInput.prototype.setUneditable = function () {};
  8548. TextareaInput.prototype.needsContentAttribute = false
  8549. function fromTextArea(textarea, options) {
  8550. options = options ? copyObj(options) : {}
  8551. options.value = textarea.value
  8552. if (!options.tabindex && textarea.tabIndex)
  8553. { options.tabindex = textarea.tabIndex }
  8554. if (!options.placeholder && textarea.placeholder)
  8555. { options.placeholder = textarea.placeholder }
  8556. // Set autofocus to true if this textarea is focused, or if it has
  8557. // autofocus and no other element is focused.
  8558. if (options.autofocus == null) {
  8559. var hasFocus = activeElt()
  8560. options.autofocus = hasFocus == textarea ||
  8561. textarea.getAttribute("autofocus") != null && hasFocus == document.body
  8562. }
  8563. function save() {textarea.value = cm.getValue()}
  8564. var realSubmit
  8565. if (textarea.form) {
  8566. on(textarea.form, "submit", save)
  8567. // Deplorable hack to make the submit method do the right thing.
  8568. if (!options.leaveSubmitMethodAlone) {
  8569. var form = textarea.form
  8570. realSubmit = form.submit
  8571. try {
  8572. var wrappedSubmit = form.submit = function () {
  8573. save()
  8574. form.submit = realSubmit
  8575. form.submit()
  8576. form.submit = wrappedSubmit
  8577. }
  8578. } catch(e) {}
  8579. }
  8580. }
  8581. options.finishInit = function (cm) {
  8582. cm.save = save
  8583. cm.getTextArea = function () { return textarea; }
  8584. cm.toTextArea = function () {
  8585. cm.toTextArea = isNaN // Prevent this from being ran twice
  8586. save()
  8587. textarea.parentNode.removeChild(cm.getWrapperElement())
  8588. textarea.style.display = ""
  8589. if (textarea.form) {
  8590. off(textarea.form, "submit", save)
  8591. if (typeof textarea.form.submit == "function")
  8592. { textarea.form.submit = realSubmit }
  8593. }
  8594. }
  8595. }
  8596. textarea.style.display = "none"
  8597. var cm = CodeMirror(function (node) { return textarea.parentNode.insertBefore(node, textarea.nextSibling); },
  8598. options)
  8599. return cm
  8600. }
  8601. function addLegacyProps(CodeMirror) {
  8602. CodeMirror.off = off
  8603. CodeMirror.on = on
  8604. CodeMirror.wheelEventPixels = wheelEventPixels
  8605. CodeMirror.Doc = Doc
  8606. CodeMirror.splitLines = splitLinesAuto
  8607. CodeMirror.countColumn = countColumn
  8608. CodeMirror.findColumn = findColumn
  8609. CodeMirror.isWordChar = isWordCharBasic
  8610. CodeMirror.Pass = Pass
  8611. CodeMirror.signal = signal
  8612. CodeMirror.Line = Line
  8613. CodeMirror.changeEnd = changeEnd
  8614. CodeMirror.scrollbarModel = scrollbarModel
  8615. CodeMirror.Pos = Pos
  8616. CodeMirror.cmpPos = cmp
  8617. CodeMirror.modes = modes
  8618. CodeMirror.mimeModes = mimeModes
  8619. CodeMirror.resolveMode = resolveMode
  8620. CodeMirror.getMode = getMode
  8621. CodeMirror.modeExtensions = modeExtensions
  8622. CodeMirror.extendMode = extendMode
  8623. CodeMirror.copyState = copyState
  8624. CodeMirror.startState = startState
  8625. CodeMirror.innerMode = innerMode
  8626. CodeMirror.commands = commands
  8627. CodeMirror.keyMap = keyMap
  8628. CodeMirror.keyName = keyName
  8629. CodeMirror.isModifierKey = isModifierKey
  8630. CodeMirror.lookupKey = lookupKey
  8631. CodeMirror.normalizeKeyMap = normalizeKeyMap
  8632. CodeMirror.StringStream = StringStream
  8633. CodeMirror.SharedTextMarker = SharedTextMarker
  8634. CodeMirror.TextMarker = TextMarker
  8635. CodeMirror.LineWidget = LineWidget
  8636. CodeMirror.e_preventDefault = e_preventDefault
  8637. CodeMirror.e_stopPropagation = e_stopPropagation
  8638. CodeMirror.e_stop = e_stop
  8639. CodeMirror.addClass = addClass
  8640. CodeMirror.contains = contains
  8641. CodeMirror.rmClass = rmClass
  8642. CodeMirror.keyNames = keyNames
  8643. }
  8644. // EDITOR CONSTRUCTOR
  8645. defineOptions(CodeMirror)
  8646. addEditorMethods(CodeMirror)
  8647. // Set up methods on CodeMirror's prototype to redirect to the editor's document.
  8648. var dontDelegate = "iter insert remove copy getEditor constructor".split(" ")
  8649. for (var prop in Doc.prototype) { if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0)
  8650. { CodeMirror.prototype[prop] = (function(method) {
  8651. return function() {return method.apply(this.doc, arguments)}
  8652. })(Doc.prototype[prop]) } }
  8653. eventMixin(Doc)
  8654. // INPUT HANDLING
  8655. CodeMirror.inputStyles = {"textarea": TextareaInput, "contenteditable": ContentEditableInput}
  8656. // MODE DEFINITION AND QUERYING
  8657. // Extra arguments are stored as the mode's dependencies, which is
  8658. // used by (legacy) mechanisms like loadmode.js to automatically
  8659. // load a mode. (Preferred mechanism is the require/define calls.)
  8660. CodeMirror.defineMode = function(name/*, mode, …*/) {
  8661. if (!CodeMirror.defaults.mode && name != "null") { CodeMirror.defaults.mode = name }
  8662. defineMode.apply(this, arguments)
  8663. }
  8664. CodeMirror.defineMIME = defineMIME
  8665. // Minimal default mode.
  8666. CodeMirror.defineMode("null", function () { return ({token: function (stream) { return stream.skipToEnd(); }}); })
  8667. CodeMirror.defineMIME("text/plain", "null")
  8668. // EXTENSIONS
  8669. CodeMirror.defineExtension = function (name, func) {
  8670. CodeMirror.prototype[name] = func
  8671. }
  8672. CodeMirror.defineDocExtension = function (name, func) {
  8673. Doc.prototype[name] = func
  8674. }
  8675. CodeMirror.fromTextArea = fromTextArea
  8676. addLegacyProps(CodeMirror)
  8677. CodeMirror.version = "5.33.0"
  8678. return CodeMirror;
  8679. })));