simplemde-editor.js 624 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377
  1. (function webpackUniversalModuleDefinition(root, factory) {
  2. if(typeof exports === 'object' && typeof module === 'object')
  3. module.exports = factory(require("react"));
  4. else if(typeof define === 'function' && define.amd)
  5. define(["react"], factory);
  6. else {
  7. var a = typeof exports === 'object' ? factory(require("react")) : factory(root["React"]);
  8. for(var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i];
  9. }
  10. })(this, function(__WEBPACK_EXTERNAL_MODULE_1__) {
  11. return /******/ (function(modules) { // webpackBootstrap
  12. /******/ // The module cache
  13. /******/ var installedModules = {};
  14. /******/
  15. /******/ // The require function
  16. /******/ function __webpack_require__(moduleId) {
  17. /******/
  18. /******/ // Check if module is in cache
  19. /******/ if(installedModules[moduleId])
  20. /******/ return installedModules[moduleId].exports;
  21. /******/
  22. /******/ // Create a new module (and put it into the cache)
  23. /******/ var module = installedModules[moduleId] = {
  24. /******/ exports: {},
  25. /******/ id: moduleId,
  26. /******/ loaded: false
  27. /******/ };
  28. /******/
  29. /******/ // Execute the module function
  30. /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  31. /******/
  32. /******/ // Flag the module as loaded
  33. /******/ module.loaded = true;
  34. /******/
  35. /******/ // Return the exports of the module
  36. /******/ return module.exports;
  37. /******/ }
  38. /******/
  39. /******/
  40. /******/ // expose the modules object (__webpack_modules__)
  41. /******/ __webpack_require__.m = modules;
  42. /******/
  43. /******/ // expose the module cache
  44. /******/ __webpack_require__.c = installedModules;
  45. /******/
  46. /******/ // __webpack_public_path__
  47. /******/ __webpack_require__.p = "";
  48. /******/
  49. /******/ // Load entry module and return exports
  50. /******/ return __webpack_require__(0);
  51. /******/ })
  52. /************************************************************************/
  53. /******/ ([
  54. /* 0 */
  55. /***/ (function(module, exports, __webpack_require__) {
  56. 'use strict';
  57. var React = __webpack_require__(1);
  58. var generateId = __webpack_require__(2);
  59. var NOOP = __webpack_require__(3);
  60. module.exports = React.createClass({
  61. displayName: 'exports',
  62. getInitialState: function getInitialState() {
  63. return {
  64. keyChange: false
  65. };
  66. },
  67. getDefaultProps: function getDefaultProps() {
  68. return {
  69. onChange: NOOP,
  70. options: {}
  71. };
  72. },
  73. componentWillMount: function componentWillMount() {
  74. var id = this.props.id;
  75. if (id) {
  76. this.id = id;
  77. } else {
  78. this.id = generateId();
  79. }
  80. },
  81. componentDidMount: function componentDidMount() {
  82. this.createEditor();
  83. this.addEvents();
  84. this.addExtraKeys();
  85. },
  86. componentWillReceiveProps: function componentWillReceiveProps(nextProps) {
  87. if (!this.state.keyChange && nextProps.value !== this.simplemde.value()) {
  88. this.simplemde.value(nextProps.value);
  89. }
  90. this.setState({
  91. keyChange: false
  92. });
  93. },
  94. componentWillUnmount: function componentWillUnmount() {
  95. this.removeEvents();
  96. },
  97. createEditor: function createEditor() {
  98. var SimpleMDE = __webpack_require__(4);
  99. var initialOptions = {
  100. element: document.getElementById(this.id),
  101. initialValue: this.props.value
  102. };
  103. var allOptions = Object.assign({}, initialOptions, this.props.options);
  104. this.simplemde = new SimpleMDE(allOptions);
  105. },
  106. eventWrapper: function eventWrapper() {
  107. this.setState({
  108. keyChange: true
  109. });
  110. this.props.onChange(this.simplemde.value());
  111. },
  112. removeEvents: function removeEvents() {
  113. this.editorEl.removeEventListener('keyup', this.eventWrapper);
  114. this.editorToolbarEl && this.editorToolbarEl.removeEventListener('click', this.eventWrapper);
  115. },
  116. addEvents: function addEvents() {
  117. var wrapperId = this.id + '-wrapper';
  118. var wrapperEl = document.getElementById('' + wrapperId);
  119. this.editorEl = wrapperEl.getElementsByClassName('CodeMirror')[0];
  120. this.editorToolbarEl = wrapperEl.getElementsByClassName('editor-toolbar')[0];
  121. this.editorEl.addEventListener('keyup', this.eventWrapper);
  122. this.editorToolbarEl && this.editorToolbarEl.addEventListener('click', this.eventWrapper);
  123. },
  124. addExtraKeys: function addExtraKeys() {
  125. // https://codemirror.net/doc/manual.html#option_extraKeys
  126. if (this.props.extraKeys) {
  127. this.simplemde.codemirror.setOption('extraKeys', this.props.extraKeys);
  128. }
  129. },
  130. render: function render() {
  131. var textarea = React.createElement('textarea', { id: this.id });
  132. var label = this.props.label ? React.createElement('label', { htmlFor: this.id }, [this.props.label]) : false;
  133. return React.createElement('div', { id: this.id + '-wrapper', className: this.props.className }, [label, textarea]);
  134. }
  135. });
  136. /***/ }),
  137. /* 1 */
  138. /***/ (function(module, exports) {
  139. module.exports = __WEBPACK_EXTERNAL_MODULE_1__;
  140. /***/ }),
  141. /* 2 */
  142. /***/ (function(module, exports) {
  143. "use strict";
  144. var _id = 0;
  145. module.exports = function generateId() {
  146. return "simplepostmd-editor-" + ++_id;
  147. };
  148. /***/ }),
  149. /* 3 */
  150. /***/ (function(module, exports) {
  151. "use strict";
  152. module.exports = function () {};
  153. /***/ }),
  154. /* 4 */
  155. /***/ (function(module, exports, __webpack_require__) {
  156. /*global require,module*/
  157. "use strict";
  158. var CodeMirror = __webpack_require__(5);
  159. __webpack_require__(6);
  160. __webpack_require__(7);
  161. __webpack_require__(8);
  162. __webpack_require__(9);
  163. __webpack_require__(12);
  164. __webpack_require__(13);
  165. __webpack_require__(14);
  166. __webpack_require__(15);
  167. __webpack_require__(10);
  168. var CodeMirrorSpellChecker = __webpack_require__(16);
  169. var marked = __webpack_require__(23);
  170. // Some variables
  171. var isMac = /Mac/.test(navigator.platform);
  172. // Mapping of actions that can be bound to keyboard shortcuts or toolbar buttons
  173. var bindings = {
  174. "toggleBold": toggleBold,
  175. "toggleItalic": toggleItalic,
  176. "drawLink": drawLink,
  177. "toggleHeadingSmaller": toggleHeadingSmaller,
  178. "toggleHeadingBigger": toggleHeadingBigger,
  179. "drawImage": drawImage,
  180. "toggleBlockquote": toggleBlockquote,
  181. "toggleOrderedList": toggleOrderedList,
  182. "toggleUnorderedList": toggleUnorderedList,
  183. "toggleCodeBlock": toggleCodeBlock,
  184. "togglePreview": togglePreview,
  185. "toggleStrikethrough": toggleStrikethrough,
  186. "toggleHeading1": toggleHeading1,
  187. "toggleHeading2": toggleHeading2,
  188. "toggleHeading3": toggleHeading3,
  189. "cleanBlock": cleanBlock,
  190. "drawTable": drawTable,
  191. "drawHorizontalRule": drawHorizontalRule,
  192. "undo": undo,
  193. "redo": redo,
  194. "toggleSideBySide": toggleSideBySide,
  195. "toggleFullScreen": toggleFullScreen
  196. };
  197. var shortcuts = {
  198. "toggleBold": "Cmd-B",
  199. "toggleItalic": "Cmd-I",
  200. "drawLink": "Cmd-K",
  201. "toggleHeadingSmaller": "Cmd-H",
  202. "toggleHeadingBigger": "Shift-Cmd-H",
  203. "cleanBlock": "Cmd-E",
  204. "drawImage": "Cmd-Alt-I",
  205. "toggleBlockquote": "Cmd-'",
  206. "toggleOrderedList": "Cmd-Alt-L",
  207. "toggleUnorderedList": "Cmd-L",
  208. "toggleCodeBlock": "Cmd-Alt-C",
  209. "togglePreview": "Cmd-P",
  210. "toggleSideBySide": "F9",
  211. "toggleFullScreen": "F11"
  212. };
  213. var getBindingName = function(f) {
  214. for(var key in bindings) {
  215. if(bindings[key] === f) {
  216. return key;
  217. }
  218. }
  219. return null;
  220. };
  221. var isMobile = function() {
  222. var check = false;
  223. (function(a) {
  224. if(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino|android|ipad|playbook|silk/i.test(a) || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0, 4))) check = true;
  225. })(navigator.userAgent || navigator.vendor || window.opera);
  226. return check;
  227. };
  228. /**
  229. * Fix shortcut. Mac use Command, others use Ctrl.
  230. */
  231. function fixShortcut(name) {
  232. if(isMac) {
  233. name = name.replace("Ctrl", "Cmd");
  234. } else {
  235. name = name.replace("Cmd", "Ctrl");
  236. }
  237. return name;
  238. }
  239. /**
  240. * Create icon element for toolbar.
  241. */
  242. function createIcon(options, enableTooltips, shortcuts) {
  243. options = options || {};
  244. var el = document.createElement("a");
  245. enableTooltips = (enableTooltips == undefined) ? true : enableTooltips;
  246. if(options.title && enableTooltips) {
  247. el.title = createTootlip(options.title, options.action, shortcuts);
  248. if(isMac) {
  249. el.title = el.title.replace("Ctrl", "⌘");
  250. el.title = el.title.replace("Alt", "⌥");
  251. }
  252. }
  253. el.tabIndex = -1;
  254. el.className = options.className;
  255. return el;
  256. }
  257. function createSep() {
  258. var el = document.createElement("i");
  259. el.className = "separator";
  260. el.innerHTML = "|";
  261. return el;
  262. }
  263. function createTootlip(title, action, shortcuts) {
  264. var actionName;
  265. var tooltip = title;
  266. if(action) {
  267. actionName = getBindingName(action);
  268. if(shortcuts[actionName]) {
  269. tooltip += " (" + fixShortcut(shortcuts[actionName]) + ")";
  270. }
  271. }
  272. return tooltip;
  273. }
  274. /**
  275. * The state of CodeMirror at the given position.
  276. */
  277. function getState(cm, pos) {
  278. pos = pos || cm.getCursor("start");
  279. var stat = cm.getTokenAt(pos);
  280. if(!stat.type) return {};
  281. var types = stat.type.split(" ");
  282. var ret = {},
  283. data, text;
  284. for(var i = 0; i < types.length; i++) {
  285. data = types[i];
  286. if(data === "strong") {
  287. ret.bold = true;
  288. } else if(data === "variable-2") {
  289. text = cm.getLine(pos.line);
  290. if(/^\s*\d+\.\s/.test(text)) {
  291. ret["ordered-list"] = true;
  292. } else {
  293. ret["unordered-list"] = true;
  294. }
  295. } else if(data === "atom") {
  296. ret.quote = true;
  297. } else if(data === "em") {
  298. ret.italic = true;
  299. } else if(data === "quote") {
  300. ret.quote = true;
  301. } else if(data === "strikethrough") {
  302. ret.strikethrough = true;
  303. } else if(data === "comment") {
  304. ret.code = true;
  305. } else if(data === "link") {
  306. ret.link = true;
  307. } else if(data === "tag") {
  308. ret.image = true;
  309. } else if(data.match(/^header(\-[1-6])?$/)) {
  310. ret[data.replace("header", "heading")] = true;
  311. }
  312. }
  313. return ret;
  314. }
  315. // Saved overflow setting
  316. var saved_overflow = "";
  317. /**
  318. * Toggle full screen of the editor.
  319. */
  320. function toggleFullScreen(editor) {
  321. // Set fullscreen
  322. var cm = editor.codemirror;
  323. cm.setOption("fullScreen", !cm.getOption("fullScreen"));
  324. // Prevent scrolling on body during fullscreen active
  325. if(cm.getOption("fullScreen")) {
  326. saved_overflow = document.body.style.overflow;
  327. document.body.style.overflow = "hidden";
  328. } else {
  329. document.body.style.overflow = saved_overflow;
  330. }
  331. // Update toolbar class
  332. var wrap = cm.getWrapperElement();
  333. if(!/fullscreen/.test(wrap.previousSibling.className)) {
  334. wrap.previousSibling.className += " fullscreen";
  335. } else {
  336. wrap.previousSibling.className = wrap.previousSibling.className.replace(/\s*fullscreen\b/, "");
  337. }
  338. // Update toolbar button
  339. var toolbarButton = editor.toolbarElements.fullscreen;
  340. if(!/active/.test(toolbarButton.className)) {
  341. toolbarButton.className += " active";
  342. } else {
  343. toolbarButton.className = toolbarButton.className.replace(/\s*active\s*/g, "");
  344. }
  345. // Hide side by side if needed
  346. var sidebyside = cm.getWrapperElement().nextSibling;
  347. if(/editor-preview-active-side/.test(sidebyside.className))
  348. toggleSideBySide(editor);
  349. }
  350. /**
  351. * Action for toggling bold.
  352. */
  353. function toggleBold(editor) {
  354. _toggleBlock(editor, "bold", editor.options.blockStyles.bold);
  355. }
  356. /**
  357. * Action for toggling italic.
  358. */
  359. function toggleItalic(editor) {
  360. _toggleBlock(editor, "italic", editor.options.blockStyles.italic);
  361. }
  362. /**
  363. * Action for toggling strikethrough.
  364. */
  365. function toggleStrikethrough(editor) {
  366. _toggleBlock(editor, "strikethrough", "~~");
  367. }
  368. /**
  369. * Action for toggling code block.
  370. */
  371. function toggleCodeBlock(editor) {
  372. var fenceCharsToInsert = editor.options.blockStyles.code;
  373. function fencing_line(line) {
  374. /* return true, if this is a ``` or ~~~ line */
  375. if(typeof line !== "object") {
  376. throw "fencing_line() takes a 'line' object (not a line number, or line text). Got: " + typeof line + ": " + line;
  377. }
  378. return line.styles && line.styles[2] && line.styles[2].indexOf("formatting-code-block") !== -1;
  379. }
  380. function token_state(token) {
  381. // base goes an extra level deep when mode backdrops are used, e.g. spellchecker on
  382. return token.state.base.base || token.state.base;
  383. }
  384. function code_type(cm, line_num, line, firstTok, lastTok) {
  385. /*
  386. * Return "single", "indented", "fenced" or false
  387. *
  388. * cm and line_num are required. Others are optional for efficiency
  389. * To check in the middle of a line, pass in firstTok yourself.
  390. */
  391. line = line || cm.getLineHandle(line_num);
  392. firstTok = firstTok || cm.getTokenAt({
  393. line: line_num,
  394. ch: 1
  395. });
  396. lastTok = lastTok || (!!line.text && cm.getTokenAt({
  397. line: line_num,
  398. ch: line.text.length - 1
  399. }));
  400. var types = firstTok.type ? firstTok.type.split(" ") : [];
  401. if(lastTok && token_state(lastTok).indentedCode) {
  402. // have to check last char, since first chars of first line aren"t marked as indented
  403. return "indented";
  404. } else if(types.indexOf("comment") === -1) {
  405. // has to be after "indented" check, since first chars of first indented line aren"t marked as such
  406. return false;
  407. } else if(token_state(firstTok).fencedChars || token_state(lastTok).fencedChars || fencing_line(line)) {
  408. return "fenced";
  409. } else {
  410. return "single";
  411. }
  412. }
  413. function insertFencingAtSelection(cm, cur_start, cur_end, fenceCharsToInsert) {
  414. var start_line_sel = cur_start.line + 1,
  415. end_line_sel = cur_end.line + 1,
  416. sel_multi = cur_start.line !== cur_end.line,
  417. repl_start = fenceCharsToInsert + "\n",
  418. repl_end = "\n" + fenceCharsToInsert;
  419. if(sel_multi) {
  420. end_line_sel++;
  421. }
  422. // handle last char including \n or not
  423. if(sel_multi && cur_end.ch === 0) {
  424. repl_end = fenceCharsToInsert + "\n";
  425. end_line_sel--;
  426. }
  427. _replaceSelection(cm, false, [repl_start, repl_end]);
  428. cm.setSelection({
  429. line: start_line_sel,
  430. ch: 0
  431. }, {
  432. line: end_line_sel,
  433. ch: 0
  434. });
  435. }
  436. var cm = editor.codemirror,
  437. cur_start = cm.getCursor("start"),
  438. cur_end = cm.getCursor("end"),
  439. tok = cm.getTokenAt({
  440. line: cur_start.line,
  441. ch: cur_start.ch || 1
  442. }), // avoid ch 0 which is a cursor pos but not token
  443. line = cm.getLineHandle(cur_start.line),
  444. is_code = code_type(cm, cur_start.line, line, tok);
  445. var block_start, block_end, lineCount;
  446. if(is_code === "single") {
  447. // similar to some SimpleMDE _toggleBlock logic
  448. var start = line.text.slice(0, cur_start.ch).replace("`", ""),
  449. end = line.text.slice(cur_start.ch).replace("`", "");
  450. cm.replaceRange(start + end, {
  451. line: cur_start.line,
  452. ch: 0
  453. }, {
  454. line: cur_start.line,
  455. ch: 99999999999999
  456. });
  457. cur_start.ch--;
  458. if(cur_start !== cur_end) {
  459. cur_end.ch--;
  460. }
  461. cm.setSelection(cur_start, cur_end);
  462. cm.focus();
  463. } else if(is_code === "fenced") {
  464. if(cur_start.line !== cur_end.line || cur_start.ch !== cur_end.ch) {
  465. // use selection
  466. // find the fenced line so we know what type it is (tilde, backticks, number of them)
  467. for(block_start = cur_start.line; block_start >= 0; block_start--) {
  468. line = cm.getLineHandle(block_start);
  469. if(fencing_line(line)) {
  470. break;
  471. }
  472. }
  473. var fencedTok = cm.getTokenAt({
  474. line: block_start,
  475. ch: 1
  476. });
  477. var fence_chars = token_state(fencedTok).fencedChars;
  478. var start_text, start_line;
  479. var end_text, end_line;
  480. // check for selection going up against fenced lines, in which case we don't want to add more fencing
  481. if(fencing_line(cm.getLineHandle(cur_start.line))) {
  482. start_text = "";
  483. start_line = cur_start.line;
  484. } else if(fencing_line(cm.getLineHandle(cur_start.line - 1))) {
  485. start_text = "";
  486. start_line = cur_start.line - 1;
  487. } else {
  488. start_text = fence_chars + "\n";
  489. start_line = cur_start.line;
  490. }
  491. if(fencing_line(cm.getLineHandle(cur_end.line))) {
  492. end_text = "";
  493. end_line = cur_end.line;
  494. if(cur_end.ch === 0) {
  495. end_line += 1;
  496. }
  497. } else if(cur_end.ch !== 0 && fencing_line(cm.getLineHandle(cur_end.line + 1))) {
  498. end_text = "";
  499. end_line = cur_end.line + 1;
  500. } else {
  501. end_text = fence_chars + "\n";
  502. end_line = cur_end.line + 1;
  503. }
  504. if(cur_end.ch === 0) {
  505. // full last line selected, putting cursor at beginning of next
  506. end_line -= 1;
  507. }
  508. cm.operation(function() {
  509. // end line first, so that line numbers don't change
  510. cm.replaceRange(end_text, {
  511. line: end_line,
  512. ch: 0
  513. }, {
  514. line: end_line + (end_text ? 0 : 1),
  515. ch: 0
  516. });
  517. cm.replaceRange(start_text, {
  518. line: start_line,
  519. ch: 0
  520. }, {
  521. line: start_line + (start_text ? 0 : 1),
  522. ch: 0
  523. });
  524. });
  525. cm.setSelection({
  526. line: start_line + (start_text ? 1 : 0),
  527. ch: 0
  528. }, {
  529. line: end_line + (start_text ? 1 : -1),
  530. ch: 0
  531. });
  532. cm.focus();
  533. } else {
  534. // no selection, search for ends of this fenced block
  535. var search_from = cur_start.line;
  536. if(fencing_line(cm.getLineHandle(cur_start.line))) { // gets a little tricky if cursor is right on a fenced line
  537. if(code_type(cm, cur_start.line + 1) === "fenced") {
  538. block_start = cur_start.line;
  539. search_from = cur_start.line + 1; // for searching for "end"
  540. } else {
  541. block_end = cur_start.line;
  542. search_from = cur_start.line - 1; // for searching for "start"
  543. }
  544. }
  545. if(block_start === undefined) {
  546. for(block_start = search_from; block_start >= 0; block_start--) {
  547. line = cm.getLineHandle(block_start);
  548. if(fencing_line(line)) {
  549. break;
  550. }
  551. }
  552. }
  553. if(block_end === undefined) {
  554. lineCount = cm.lineCount();
  555. for(block_end = search_from; block_end < lineCount; block_end++) {
  556. line = cm.getLineHandle(block_end);
  557. if(fencing_line(line)) {
  558. break;
  559. }
  560. }
  561. }
  562. cm.operation(function() {
  563. cm.replaceRange("", {
  564. line: block_start,
  565. ch: 0
  566. }, {
  567. line: block_start + 1,
  568. ch: 0
  569. });
  570. cm.replaceRange("", {
  571. line: block_end - 1,
  572. ch: 0
  573. }, {
  574. line: block_end,
  575. ch: 0
  576. });
  577. });
  578. cm.focus();
  579. }
  580. } else if(is_code === "indented") {
  581. if(cur_start.line !== cur_end.line || cur_start.ch !== cur_end.ch) {
  582. // use selection
  583. block_start = cur_start.line;
  584. block_end = cur_end.line;
  585. if(cur_end.ch === 0) {
  586. block_end--;
  587. }
  588. } else {
  589. // no selection, search for ends of this indented block
  590. for(block_start = cur_start.line; block_start >= 0; block_start--) {
  591. line = cm.getLineHandle(block_start);
  592. if(line.text.match(/^\s*$/)) {
  593. // empty or all whitespace - keep going
  594. continue;
  595. } else {
  596. if(code_type(cm, block_start, line) !== "indented") {
  597. block_start += 1;
  598. break;
  599. }
  600. }
  601. }
  602. lineCount = cm.lineCount();
  603. for(block_end = cur_start.line; block_end < lineCount; block_end++) {
  604. line = cm.getLineHandle(block_end);
  605. if(line.text.match(/^\s*$/)) {
  606. // empty or all whitespace - keep going
  607. continue;
  608. } else {
  609. if(code_type(cm, block_end, line) !== "indented") {
  610. block_end -= 1;
  611. break;
  612. }
  613. }
  614. }
  615. }
  616. // if we are going to un-indent based on a selected set of lines, and the next line is indented too, we need to
  617. // insert a blank line so that the next line(s) continue to be indented code
  618. var next_line = cm.getLineHandle(block_end + 1),
  619. next_line_last_tok = next_line && cm.getTokenAt({
  620. line: block_end + 1,
  621. ch: next_line.text.length - 1
  622. }),
  623. next_line_indented = next_line_last_tok && token_state(next_line_last_tok).indentedCode;
  624. if(next_line_indented) {
  625. cm.replaceRange("\n", {
  626. line: block_end + 1,
  627. ch: 0
  628. });
  629. }
  630. for(var i = block_start; i <= block_end; i++) {
  631. cm.indentLine(i, "subtract"); // TODO: this doesn't get tracked in the history, so can't be undone :(
  632. }
  633. cm.focus();
  634. } else {
  635. // insert code formatting
  636. var no_sel_and_starting_of_line = (cur_start.line === cur_end.line && cur_start.ch === cur_end.ch && cur_start.ch === 0);
  637. var sel_multi = cur_start.line !== cur_end.line;
  638. if(no_sel_and_starting_of_line || sel_multi) {
  639. insertFencingAtSelection(cm, cur_start, cur_end, fenceCharsToInsert);
  640. } else {
  641. _replaceSelection(cm, false, ["`", "`"]);
  642. }
  643. }
  644. }
  645. /**
  646. * Action for toggling blockquote.
  647. */
  648. function toggleBlockquote(editor) {
  649. var cm = editor.codemirror;
  650. _toggleLine(cm, "quote");
  651. }
  652. /**
  653. * Action for toggling heading size: normal -> h1 -> h2 -> h3 -> h4 -> h5 -> h6 -> normal
  654. */
  655. function toggleHeadingSmaller(editor) {
  656. var cm = editor.codemirror;
  657. _toggleHeading(cm, "smaller");
  658. }
  659. /**
  660. * Action for toggling heading size: normal -> h6 -> h5 -> h4 -> h3 -> h2 -> h1 -> normal
  661. */
  662. function toggleHeadingBigger(editor) {
  663. var cm = editor.codemirror;
  664. _toggleHeading(cm, "bigger");
  665. }
  666. /**
  667. * Action for toggling heading size 1
  668. */
  669. function toggleHeading1(editor) {
  670. var cm = editor.codemirror;
  671. _toggleHeading(cm, undefined, 1);
  672. }
  673. /**
  674. * Action for toggling heading size 2
  675. */
  676. function toggleHeading2(editor) {
  677. var cm = editor.codemirror;
  678. _toggleHeading(cm, undefined, 2);
  679. }
  680. /**
  681. * Action for toggling heading size 3
  682. */
  683. function toggleHeading3(editor) {
  684. var cm = editor.codemirror;
  685. _toggleHeading(cm, undefined, 3);
  686. }
  687. /**
  688. * Action for toggling ul.
  689. */
  690. function toggleUnorderedList(editor) {
  691. var cm = editor.codemirror;
  692. _toggleLine(cm, "unordered-list");
  693. }
  694. /**
  695. * Action for toggling ol.
  696. */
  697. function toggleOrderedList(editor) {
  698. var cm = editor.codemirror;
  699. _toggleLine(cm, "ordered-list");
  700. }
  701. /**
  702. * Action for clean block (remove headline, list, blockquote code, markers)
  703. */
  704. function cleanBlock(editor) {
  705. var cm = editor.codemirror;
  706. _cleanBlock(cm);
  707. }
  708. /**
  709. * Action for drawing a link.
  710. */
  711. function drawLink(editor) {
  712. var cm = editor.codemirror;
  713. var stat = getState(cm);
  714. var options = editor.options;
  715. var url = "safe://";
  716. if(options.promptURLs) {
  717. url = prompt(options.promptTexts.link);
  718. if(!url) {
  719. return false;
  720. }
  721. }
  722. _replaceSelection(cm, stat.link, options.insertTexts.link, url);
  723. }
  724. /**
  725. * Action for drawing an img.
  726. */
  727. function drawImage(editor) {
  728. var cm = editor.codemirror;
  729. var stat = getState(cm);
  730. var options = editor.options;
  731. var url = "safe://";
  732. if(options.promptURLs) {
  733. url = prompt(options.promptTexts.image);
  734. if(!url) {
  735. return false;
  736. }
  737. }
  738. _replaceSelection(cm, stat.image, options.insertTexts.image, url);
  739. }
  740. /**
  741. * Action for drawing a table.
  742. */
  743. function drawTable(editor) {
  744. var cm = editor.codemirror;
  745. var stat = getState(cm);
  746. var options = editor.options;
  747. _replaceSelection(cm, stat.table, options.insertTexts.table);
  748. }
  749. /**
  750. * Action for drawing a horizontal rule.
  751. */
  752. function drawHorizontalRule(editor) {
  753. var cm = editor.codemirror;
  754. var stat = getState(cm);
  755. var options = editor.options;
  756. _replaceSelection(cm, stat.image, options.insertTexts.horizontalRule);
  757. }
  758. /**
  759. * Undo action.
  760. */
  761. function undo(editor) {
  762. var cm = editor.codemirror;
  763. cm.undo();
  764. cm.focus();
  765. }
  766. /**
  767. * Redo action.
  768. */
  769. function redo(editor) {
  770. var cm = editor.codemirror;
  771. cm.redo();
  772. cm.focus();
  773. }
  774. /**
  775. * Toggle side by side preview
  776. */
  777. function toggleSideBySide(editor) {
  778. var cm = editor.codemirror;
  779. var wrapper = cm.getWrapperElement();
  780. var preview = wrapper.nextSibling;
  781. var toolbarButton = editor.toolbarElements["side-by-side"];
  782. var useSideBySideListener = false;
  783. if(/editor-preview-active-side/.test(preview.className)) {
  784. preview.className = preview.className.replace(
  785. /\s*editor-preview-active-side\s*/g, ""
  786. );
  787. toolbarButton.className = toolbarButton.className.replace(/\s*active\s*/g, "");
  788. wrapper.className = wrapper.className.replace(/\s*CodeMirror-sided\s*/g, " ");
  789. } else {
  790. // When the preview button is clicked for the first time,
  791. // give some time for the transition from editor.css to fire and the view to slide from right to left,
  792. // instead of just appearing.
  793. setTimeout(function() {
  794. if(!cm.getOption("fullScreen"))
  795. toggleFullScreen(editor);
  796. preview.className += " editor-preview-active-side";
  797. }, 1);
  798. toolbarButton.className += " active";
  799. wrapper.className += " CodeMirror-sided";
  800. useSideBySideListener = true;
  801. }
  802. // Hide normal preview if active
  803. var previewNormal = wrapper.lastChild;
  804. if(/editor-preview-active/.test(previewNormal.className)) {
  805. previewNormal.className = previewNormal.className.replace(
  806. /\s*editor-preview-active\s*/g, ""
  807. );
  808. var toolbar = editor.toolbarElements.preview;
  809. var toolbar_div = wrapper.previousSibling;
  810. toolbar.className = toolbar.className.replace(/\s*active\s*/g, "");
  811. toolbar_div.className = toolbar_div.className.replace(/\s*disabled-for-preview*/g, "");
  812. }
  813. var sideBySideRenderingFunction = function() {
  814. preview.innerHTML = editor.options.previewRender(editor.value(), preview);
  815. };
  816. if(!cm.sideBySideRenderingFunction) {
  817. cm.sideBySideRenderingFunction = sideBySideRenderingFunction;
  818. }
  819. if(useSideBySideListener) {
  820. preview.innerHTML = editor.options.previewRender(editor.value(), preview);
  821. cm.on("update", cm.sideBySideRenderingFunction);
  822. } else {
  823. cm.off("update", cm.sideBySideRenderingFunction);
  824. }
  825. // Refresh to fix selection being off (#309)
  826. cm.refresh();
  827. }
  828. /**
  829. * Preview action.
  830. */
  831. function togglePreview(editor) {
  832. var cm = editor.codemirror;
  833. var wrapper = cm.getWrapperElement();
  834. var toolbar_div = wrapper.previousSibling;
  835. var toolbar = editor.options.toolbar ? editor.toolbarElements.preview : false;
  836. var preview = wrapper.lastChild;
  837. if(!preview || !/editor-preview/.test(preview.className)) {
  838. preview = document.createElement("div");
  839. preview.className = "editor-preview";
  840. wrapper.appendChild(preview);
  841. }
  842. if(/editor-preview-active/.test(preview.className)) {
  843. preview.className = preview.className.replace(
  844. /\s*editor-preview-active\s*/g, ""
  845. );
  846. if(toolbar) {
  847. toolbar.className = toolbar.className.replace(/\s*active\s*/g, "");
  848. toolbar_div.className = toolbar_div.className.replace(/\s*disabled-for-preview*/g, "");
  849. }
  850. } else {
  851. // When the preview button is clicked for the first time,
  852. // give some time for the transition from editor.css to fire and the view to slide from right to left,
  853. // instead of just appearing.
  854. setTimeout(function() {
  855. preview.className += " editor-preview-active";
  856. }, 1);
  857. if(toolbar) {
  858. toolbar.className += " active";
  859. toolbar_div.className += " disabled-for-preview";
  860. }
  861. }
  862. preview.innerHTML = editor.options.previewRender(editor.value(), preview);
  863. // Turn off side by side if needed
  864. var sidebyside = cm.getWrapperElement().nextSibling;
  865. if(/editor-preview-active-side/.test(sidebyside.className))
  866. toggleSideBySide(editor);
  867. }
  868. function _replaceSelection(cm, active, startEnd, url) {
  869. if(/editor-preview-active/.test(cm.getWrapperElement().lastChild.className))
  870. return;
  871. var text;
  872. var start = startEnd[0];
  873. var end = startEnd[1];
  874. var startPoint = cm.getCursor("start");
  875. var endPoint = cm.getCursor("end");
  876. if(url) {
  877. end = end.replace("#url#", url);
  878. }
  879. if(active) {
  880. text = cm.getLine(startPoint.line);
  881. start = text.slice(0, startPoint.ch);
  882. end = text.slice(startPoint.ch);
  883. cm.replaceRange(start + end, {
  884. line: startPoint.line,
  885. ch: 0
  886. });
  887. } else {
  888. text = cm.getSelection();
  889. cm.replaceSelection(start + text + end);
  890. startPoint.ch += start.length;
  891. if(startPoint !== endPoint) {
  892. endPoint.ch += start.length;
  893. }
  894. }
  895. cm.setSelection(startPoint, endPoint);
  896. cm.focus();
  897. }
  898. function _toggleHeading(cm, direction, size) {
  899. if(/editor-preview-active/.test(cm.getWrapperElement().lastChild.className))
  900. return;
  901. var startPoint = cm.getCursor("start");
  902. var endPoint = cm.getCursor("end");
  903. for(var i = startPoint.line; i <= endPoint.line; i++) {
  904. (function(i) {
  905. var text = cm.getLine(i);
  906. var currHeadingLevel = text.search(/[^#]/);
  907. if(direction !== undefined) {
  908. if(currHeadingLevel <= 0) {
  909. if(direction == "bigger") {
  910. text = "###### " + text;
  911. } else {
  912. text = "# " + text;
  913. }
  914. } else if(currHeadingLevel == 6 && direction == "smaller") {
  915. text = text.substr(7);
  916. } else if(currHeadingLevel == 1 && direction == "bigger") {
  917. text = text.substr(2);
  918. } else {
  919. if(direction == "bigger") {
  920. text = text.substr(1);
  921. } else {
  922. text = "#" + text;
  923. }
  924. }
  925. } else {
  926. if(size == 1) {
  927. if(currHeadingLevel <= 0) {
  928. text = "# " + text;
  929. } else if(currHeadingLevel == size) {
  930. text = text.substr(currHeadingLevel + 1);
  931. } else {
  932. text = "# " + text.substr(currHeadingLevel + 1);
  933. }
  934. } else if(size == 2) {
  935. if(currHeadingLevel <= 0) {
  936. text = "## " + text;
  937. } else if(currHeadingLevel == size) {
  938. text = text.substr(currHeadingLevel + 1);
  939. } else {
  940. text = "## " + text.substr(currHeadingLevel + 1);
  941. }
  942. } else {
  943. if(currHeadingLevel <= 0) {
  944. text = "### " + text;
  945. } else if(currHeadingLevel == size) {
  946. text = text.substr(currHeadingLevel + 1);
  947. } else {
  948. text = "### " + text.substr(currHeadingLevel + 1);
  949. }
  950. }
  951. }
  952. cm.replaceRange(text, {
  953. line: i,
  954. ch: 0
  955. }, {
  956. line: i,
  957. ch: 99999999999999
  958. });
  959. })(i);
  960. }
  961. cm.focus();
  962. }
  963. function _toggleLine(cm, name) {
  964. if(/editor-preview-active/.test(cm.getWrapperElement().lastChild.className))
  965. return;
  966. var stat = getState(cm);
  967. var startPoint = cm.getCursor("start");
  968. var endPoint = cm.getCursor("end");
  969. var repl = {
  970. "quote": /^(\s*)\>\s+/,
  971. "unordered-list": /^(\s*)(\*|\-|\+)\s+/,
  972. "ordered-list": /^(\s*)\d+\.\s+/
  973. };
  974. var map = {
  975. "quote": "> ",
  976. "unordered-list": "* ",
  977. "ordered-list": "1. "
  978. };
  979. for(var i = startPoint.line; i <= endPoint.line; i++) {
  980. (function(i) {
  981. var text = cm.getLine(i);
  982. if(stat[name]) {
  983. text = text.replace(repl[name], "$1");
  984. } else {
  985. text = map[name] + text;
  986. }
  987. cm.replaceRange(text, {
  988. line: i,
  989. ch: 0
  990. }, {
  991. line: i,
  992. ch: 99999999999999
  993. });
  994. })(i);
  995. }
  996. cm.focus();
  997. }
  998. function _toggleBlock(editor, type, start_chars, end_chars) {
  999. if(/editor-preview-active/.test(editor.codemirror.getWrapperElement().lastChild.className))
  1000. return;
  1001. end_chars = (typeof end_chars === "undefined") ? start_chars : end_chars;
  1002. var cm = editor.codemirror;
  1003. var stat = getState(cm);
  1004. var text;
  1005. var start = start_chars;
  1006. var end = end_chars;
  1007. var startPoint = cm.getCursor("start");
  1008. var endPoint = cm.getCursor("end");
  1009. if(stat[type]) {
  1010. text = cm.getLine(startPoint.line);
  1011. start = text.slice(0, startPoint.ch);
  1012. end = text.slice(startPoint.ch);
  1013. if(type == "bold") {
  1014. start = start.replace(/(\*\*|__)(?![\s\S]*(\*\*|__))/, "");
  1015. end = end.replace(/(\*\*|__)/, "");
  1016. } else if(type == "italic") {
  1017. start = start.replace(/(\*|_)(?![\s\S]*(\*|_))/, "");
  1018. end = end.replace(/(\*|_)/, "");
  1019. } else if(type == "strikethrough") {
  1020. start = start.replace(/(\*\*|~~)(?![\s\S]*(\*\*|~~))/, "");
  1021. end = end.replace(/(\*\*|~~)/, "");
  1022. }
  1023. cm.replaceRange(start + end, {
  1024. line: startPoint.line,
  1025. ch: 0
  1026. }, {
  1027. line: startPoint.line,
  1028. ch: 99999999999999
  1029. });
  1030. if(type == "bold" || type == "strikethrough") {
  1031. startPoint.ch -= 2;
  1032. if(startPoint !== endPoint) {
  1033. endPoint.ch -= 2;
  1034. }
  1035. } else if(type == "italic") {
  1036. startPoint.ch -= 1;
  1037. if(startPoint !== endPoint) {
  1038. endPoint.ch -= 1;
  1039. }
  1040. }
  1041. } else {
  1042. text = cm.getSelection();
  1043. if(type == "bold") {
  1044. text = text.split("**").join("");
  1045. text = text.split("__").join("");
  1046. } else if(type == "italic") {
  1047. text = text.split("*").join("");
  1048. text = text.split("_").join("");
  1049. } else if(type == "strikethrough") {
  1050. text = text.split("~~").join("");
  1051. }
  1052. cm.replaceSelection(start + text + end);
  1053. startPoint.ch += start_chars.length;
  1054. endPoint.ch = startPoint.ch + text.length;
  1055. }
  1056. cm.setSelection(startPoint, endPoint);
  1057. cm.focus();
  1058. }
  1059. function _cleanBlock(cm) {
  1060. if(/editor-preview-active/.test(cm.getWrapperElement().lastChild.className))
  1061. return;
  1062. var startPoint = cm.getCursor("start");
  1063. var endPoint = cm.getCursor("end");
  1064. var text;
  1065. for(var line = startPoint.line; line <= endPoint.line; line++) {
  1066. text = cm.getLine(line);
  1067. text = text.replace(/^[ ]*([# ]+|\*|\-|[> ]+|[0-9]+(.|\)))[ ]*/, "");
  1068. cm.replaceRange(text, {
  1069. line: line,
  1070. ch: 0
  1071. }, {
  1072. line: line,
  1073. ch: 99999999999999
  1074. });
  1075. }
  1076. }
  1077. // Merge the properties of one object into another.
  1078. function _mergeProperties(target, source) {
  1079. for(var property in source) {
  1080. if(source.hasOwnProperty(property)) {
  1081. if(source[property] instanceof Array) {
  1082. target[property] = source[property].concat(target[property] instanceof Array ? target[property] : []);
  1083. } else if(
  1084. source[property] !== null &&
  1085. typeof source[property] === "object" &&
  1086. source[property].constructor === Object
  1087. ) {
  1088. target[property] = _mergeProperties(target[property] || {}, source[property]);
  1089. } else {
  1090. target[property] = source[property];
  1091. }
  1092. }
  1093. }
  1094. return target;
  1095. }
  1096. // Merge an arbitrary number of objects into one.
  1097. function extend(target) {
  1098. for(var i = 1; i < arguments.length; i++) {
  1099. target = _mergeProperties(target, arguments[i]);
  1100. }
  1101. return target;
  1102. }
  1103. /* The right word count in respect for CJK. */
  1104. function wordCount(data) {
  1105. var pattern = /[a-zA-Z0-9_\u0392-\u03c9\u0410-\u04F9]+|[\u4E00-\u9FFF\u3400-\u4dbf\uf900-\ufaff\u3040-\u309f\uac00-\ud7af]+/g;
  1106. var m = data.match(pattern);
  1107. var count = 0;
  1108. if(m === null) return count;
  1109. for(var i = 0; i < m.length; i++) {
  1110. if(m[i].charCodeAt(0) >= 0x4E00) {
  1111. count += m[i].length;
  1112. } else {
  1113. count += 1;
  1114. }
  1115. }
  1116. return count;
  1117. }
  1118. var toolbarBuiltInButtons = {
  1119. "bold": {
  1120. name: "bold",
  1121. action: toggleBold,
  1122. className: "fa fa-bold",
  1123. title: "Bold",
  1124. default: true
  1125. },
  1126. "italic": {
  1127. name: "italic",
  1128. action: toggleItalic,
  1129. className: "fa fa-italic",
  1130. title: "Italic",
  1131. default: true
  1132. },
  1133. "strikethrough": {
  1134. name: "strikethrough",
  1135. action: toggleStrikethrough,
  1136. className: "fa fa-strikethrough",
  1137. title: "Strikethrough"
  1138. },
  1139. "heading": {
  1140. name: "heading",
  1141. action: toggleHeadingSmaller,
  1142. className: "fa fa-header",
  1143. title: "Heading",
  1144. default: true
  1145. },
  1146. "heading-smaller": {
  1147. name: "heading-smaller",
  1148. action: toggleHeadingSmaller,
  1149. className: "fa fa-header fa-header-x fa-header-smaller",
  1150. title: "Smaller Heading"
  1151. },
  1152. "heading-bigger": {
  1153. name: "heading-bigger",
  1154. action: toggleHeadingBigger,
  1155. className: "fa fa-header fa-header-x fa-header-bigger",
  1156. title: "Bigger Heading"
  1157. },
  1158. "heading-1": {
  1159. name: "heading-1",
  1160. action: toggleHeading1,
  1161. className: "fa fa-header fa-header-x fa-header-1",
  1162. title: "Big Heading"
  1163. },
  1164. "heading-2": {
  1165. name: "heading-2",
  1166. action: toggleHeading2,
  1167. className: "fa fa-header fa-header-x fa-header-2",
  1168. title: "Medium Heading"
  1169. },
  1170. "heading-3": {
  1171. name: "heading-3",
  1172. action: toggleHeading3,
  1173. className: "fa fa-header fa-header-x fa-header-3",
  1174. title: "Small Heading"
  1175. },
  1176. "separator-1": {
  1177. name: "separator-1"
  1178. },
  1179. "code": {
  1180. name: "code",
  1181. action: toggleCodeBlock,
  1182. className: "fa fa-code",
  1183. title: "Code"
  1184. },
  1185. "quote": {
  1186. name: "quote",
  1187. action: toggleBlockquote,
  1188. className: "fa fa-quote-left",
  1189. title: "Quote",
  1190. default: true
  1191. },
  1192. "unordered-list": {
  1193. name: "unordered-list",
  1194. action: toggleUnorderedList,
  1195. className: "fa fa-list-ul",
  1196. title: "Generic List",
  1197. default: true
  1198. },
  1199. "ordered-list": {
  1200. name: "ordered-list",
  1201. action: toggleOrderedList,
  1202. className: "fa fa-list-ol",
  1203. title: "Numbered List",
  1204. default: true
  1205. },
  1206. "clean-block": {
  1207. name: "clean-block",
  1208. action: cleanBlock,
  1209. className: "fa fa-eraser fa-clean-block",
  1210. title: "Clean block"
  1211. },
  1212. "separator-2": {
  1213. name: "separator-2"
  1214. },
  1215. "link": {
  1216. name: "link",
  1217. action: drawLink,
  1218. className: "fa fa-link",
  1219. title: "Create Link",
  1220. default: true
  1221. },
  1222. "image": {
  1223. name: "image",
  1224. action: drawImage,
  1225. className: "fa fa-picture-o",
  1226. title: "Insert Image",
  1227. default: true
  1228. },
  1229. "table": {
  1230. name: "table",
  1231. action: drawTable,
  1232. className: "fa fa-table",
  1233. title: "Insert Table"
  1234. },
  1235. "horizontal-rule": {
  1236. name: "horizontal-rule",
  1237. action: drawHorizontalRule,
  1238. className: "fa fa-minus",
  1239. title: "Insert Horizontal Line"
  1240. },
  1241. "separator-3": {
  1242. name: "separator-3"
  1243. },
  1244. "preview": {
  1245. name: "preview",
  1246. action: togglePreview,
  1247. className: "fa fa-eye no-disable",
  1248. title: "Toggle Preview",
  1249. default: true
  1250. },
  1251. "side-by-side": {
  1252. name: "side-by-side",
  1253. action: toggleSideBySide,
  1254. className: "fa fa-columns no-disable no-mobile",
  1255. title: "Toggle Side by Side",
  1256. default: true
  1257. },
  1258. "fullscreen": {
  1259. name: "fullscreen",
  1260. action: toggleFullScreen,
  1261. className: "fa fa-arrows-alt no-disable no-mobile",
  1262. title: "Toggle Fullscreen",
  1263. default: true
  1264. },
  1265. "separator-4": {
  1266. name: "separator-4"
  1267. },
  1268. "guide": {
  1269. name: "guide",
  1270. action: "safe://markdown-guide", // maybe one day
  1271. className: "fa fa-question-circle",
  1272. title: "Markdown Guide",
  1273. default: false // disable this for now
  1274. },
  1275. "separator-5": {
  1276. name: "separator-5"
  1277. },
  1278. "undo": {
  1279. name: "undo",
  1280. action: undo,
  1281. className: "fa fa-undo no-disable",
  1282. title: "Undo"
  1283. },
  1284. "redo": {
  1285. name: "redo",
  1286. action: redo,
  1287. className: "fa fa-repeat no-disable",
  1288. title: "Redo"
  1289. }
  1290. };
  1291. var insertTexts = {
  1292. link: ["[", "](#url#)"],
  1293. image: ["![", "](#url#)"],
  1294. table: ["", "\n\n| Column 1 | Column 2 | Column 3 |\n| -------- | -------- | -------- |\n| Text | Text | Text |\n\n"],
  1295. horizontalRule: ["", "\n\n-----\n\n"]
  1296. };
  1297. var promptTexts = {
  1298. link: "URL for the link:",
  1299. image: "URL of the image:"
  1300. };
  1301. var blockStyles = {
  1302. "bold": "**",
  1303. "code": "```",
  1304. "italic": "*"
  1305. };
  1306. /**
  1307. * Interface of SimpleMDE.
  1308. */
  1309. function SimpleMDE(options) {
  1310. // Handle options parameter
  1311. options = options || {};
  1312. // Used later to refer to it"s parent
  1313. options.parent = this;
  1314. // Check if Font Awesome needs to be auto downloaded
  1315. // var autoDownloadFA = true;
  1316. var autoDownloadFA = false; // lets disable this for now
  1317. if(options.autoDownloadFontAwesome === false) {
  1318. autoDownloadFA = false; //
  1319. }
  1320. if(options.autoDownloadFontAwesome !== true) {
  1321. var styleSheets = document.styleSheets;
  1322. for(var i = 0; i < styleSheets.length; i++) {
  1323. if(!styleSheets[i].href)
  1324. continue;
  1325. if(styleSheets[i].href.indexOf("//maxcdn.bootstrapcdn.com/font-awesome/") > -1) {
  1326. autoDownloadFA = false;
  1327. }
  1328. }
  1329. }
  1330. if(autoDownloadFA) {
  1331. var link = document.createElement("link");
  1332. link.rel = "stylesheet";
  1333. // link.href = "https://maxcdn.bootstrapcdn.com/font-awesome/latest/css/font-awesome.min.css"; //we really don't want to make an http request
  1334. link.href = "safe://somepath/font-awesome.min.css"; // one day maybe
  1335. document.getElementsByTagName("head")[0].appendChild(link);
  1336. }
  1337. // Find the textarea to use
  1338. if(options.element) {
  1339. this.element = options.element;
  1340. } else if(options.element === null) {
  1341. // This means that the element option was specified, but no element was found
  1342. console.log("SimpleMDE: Error. No element was found.");
  1343. return;
  1344. }
  1345. // Handle toolbar
  1346. if(options.toolbar === undefined) {
  1347. // Initialize
  1348. options.toolbar = [];
  1349. // Loop over the built in buttons, to get the preferred order
  1350. for(var key in toolbarBuiltInButtons) {
  1351. if(toolbarBuiltInButtons.hasOwnProperty(key)) {
  1352. if(key.indexOf("separator-") != -1) {
  1353. options.toolbar.push("|");
  1354. }
  1355. if(toolbarBuiltInButtons[key].default === true || (options.showIcons && options.showIcons.constructor === Array && options.showIcons.indexOf(key) != -1)) {
  1356. options.toolbar.push(key);
  1357. }
  1358. }
  1359. }
  1360. }
  1361. // Handle status bar
  1362. if(!options.hasOwnProperty("status")) {
  1363. options.status = ["autosave", "lines", "words", "cursor"];
  1364. }
  1365. // Add default preview rendering function
  1366. if(!options.previewRender) {
  1367. options.previewRender = function(plainText) {
  1368. // Note: "this" refers to the options object
  1369. return this.parent.markdown(plainText);
  1370. };
  1371. }
  1372. // Set default options for parsing config
  1373. options.parsingConfig = extend({
  1374. highlightFormatting: true // needed for toggleCodeBlock to detect types of code
  1375. }, options.parsingConfig || {});
  1376. // Merging the insertTexts, with the given options
  1377. options.insertTexts = extend({}, insertTexts, options.insertTexts || {});
  1378. // Merging the promptTexts, with the given options
  1379. options.promptTexts = promptTexts;
  1380. // Merging the blockStyles, with the given options
  1381. options.blockStyles = extend({}, blockStyles, options.blockStyles || {});
  1382. // Merging the shortcuts, with the given options
  1383. options.shortcuts = extend({}, shortcuts, options.shortcuts || {});
  1384. // Change unique_id to uniqueId for backwards compatibility
  1385. if(options.autosave != undefined && options.autosave.unique_id != undefined && options.autosave.unique_id != "")
  1386. options.autosave.uniqueId = options.autosave.unique_id;
  1387. // Update this options
  1388. this.options = options;
  1389. // Auto render
  1390. this.render();
  1391. // The codemirror component is only available after rendering
  1392. // so, the setter for the initialValue can only run after
  1393. // the element has been rendered
  1394. if(options.initialValue && (!this.options.autosave || this.options.autosave.foundSavedValue !== true)) {
  1395. this.value(options.initialValue);
  1396. }
  1397. }
  1398. /**
  1399. * Default markdown render.
  1400. */
  1401. SimpleMDE.prototype.markdown = function(text) {
  1402. if(marked) {
  1403. // Initialize
  1404. var markedOptions = {};
  1405. // Update options
  1406. if(this.options && this.options.renderingConfig && this.options.renderingConfig.singleLineBreaks === false) {
  1407. markedOptions.breaks = false;
  1408. } else {
  1409. markedOptions.breaks = true;
  1410. }
  1411. if(this.options && this.options.renderingConfig && this.options.renderingConfig.codeSyntaxHighlighting === true && window.hljs) {
  1412. markedOptions.highlight = function(code) {
  1413. return window.hljs.highlightAuto(code).value;
  1414. };
  1415. }
  1416. // Set options
  1417. marked.setOptions(markedOptions);
  1418. // Return
  1419. return marked(text);
  1420. }
  1421. };
  1422. /**
  1423. * Render editor to the given element.
  1424. */
  1425. SimpleMDE.prototype.render = function(el) {
  1426. if(!el) {
  1427. el = this.element || document.getElementsByTagName("textarea")[0];
  1428. }
  1429. if(this._rendered && this._rendered === el) {
  1430. // Already rendered.
  1431. return;
  1432. }
  1433. this.element = el;
  1434. var options = this.options;
  1435. var self = this;
  1436. var keyMaps = {};
  1437. for(var key in options.shortcuts) {
  1438. // null stands for "do not bind this command"
  1439. if(options.shortcuts[key] !== null && bindings[key] !== null) {
  1440. (function(key) {
  1441. keyMaps[fixShortcut(options.shortcuts[key])] = function() {
  1442. bindings[key](self);
  1443. };
  1444. })(key);
  1445. }
  1446. }
  1447. keyMaps["Enter"] = "newlineAndIndentContinueMarkdownList";
  1448. keyMaps["Tab"] = "tabAndIndentMarkdownList";
  1449. keyMaps["Shift-Tab"] = "shiftTabAndUnindentMarkdownList";
  1450. keyMaps["Esc"] = function(cm) {
  1451. if(cm.getOption("fullScreen")) toggleFullScreen(self);
  1452. };
  1453. document.addEventListener("keydown", function(e) {
  1454. e = e || window.event;
  1455. if(e.keyCode == 27) {
  1456. if(self.codemirror.getOption("fullScreen")) toggleFullScreen(self);
  1457. }
  1458. }, false);
  1459. var mode, backdrop;
  1460. if(options.spellChecker !== false) {
  1461. mode = "spell-checker";
  1462. backdrop = options.parsingConfig;
  1463. backdrop.name = "gfm";
  1464. backdrop.gitHubSpice = false;
  1465. CodeMirrorSpellChecker({
  1466. codeMirrorInstance: CodeMirror
  1467. });
  1468. } else {
  1469. mode = options.parsingConfig;
  1470. mode.name = "gfm";
  1471. mode.gitHubSpice = false;
  1472. }
  1473. this.codemirror = CodeMirror.fromTextArea(el, {
  1474. mode: mode,
  1475. backdrop: backdrop,
  1476. theme: "paper",
  1477. tabSize: (options.tabSize != undefined) ? options.tabSize : 2,
  1478. indentUnit: (options.tabSize != undefined) ? options.tabSize : 2,
  1479. indentWithTabs: (options.indentWithTabs === false) ? false : true,
  1480. lineNumbers: false,
  1481. autofocus: (options.autofocus === true) ? true : false,
  1482. extraKeys: keyMaps,
  1483. lineWrapping: (options.lineWrapping === false) ? false : true,
  1484. allowDropFileTypes: ["text/plain"],
  1485. placeholder: options.placeholder || el.getAttribute("placeholder") || "",
  1486. styleSelectedText: (options.styleSelectedText != undefined) ? options.styleSelectedText : true
  1487. });
  1488. if(options.forceSync === true) {
  1489. var cm = this.codemirror;
  1490. cm.on("change", function() {
  1491. cm.save();
  1492. });
  1493. }
  1494. this.gui = {};
  1495. if(options.toolbar !== false) {
  1496. this.gui.toolbar = this.createToolbar();
  1497. }
  1498. if(options.status !== false) {
  1499. this.gui.statusbar = this.createStatusbar();
  1500. }
  1501. if(options.autosave != undefined && options.autosave.enabled === true) {
  1502. this.autosave();
  1503. }
  1504. this.gui.sideBySide = this.createSideBySide();
  1505. this._rendered = this.element;
  1506. // Fixes CodeMirror bug (#344)
  1507. var temp_cm = this.codemirror;
  1508. setTimeout(function() {
  1509. temp_cm.refresh();
  1510. }.bind(temp_cm), 0);
  1511. };
  1512. // Safari, in Private Browsing Mode, looks like it supports localStorage but all calls to setItem throw QuotaExceededError. We're going to detect this and set a variable accordingly.
  1513. function isLocalStorageAvailable() {
  1514. if(typeof localStorage === "object") {
  1515. try {
  1516. localStorage.setItem("smde_localStorage", 1);
  1517. localStorage.removeItem("smde_localStorage");
  1518. } catch(e) {
  1519. return false;
  1520. }
  1521. } else {
  1522. return false;
  1523. }
  1524. return true;
  1525. }
  1526. SimpleMDE.prototype.autosave = function() {
  1527. if(isLocalStorageAvailable()) {
  1528. var simplemde = this;
  1529. if(this.options.autosave.uniqueId == undefined || this.options.autosave.uniqueId == "") {
  1530. console.log("SimpleMDE: You must set a uniqueId to use the autosave feature");
  1531. return;
  1532. }
  1533. if(simplemde.element.form != null && simplemde.element.form != undefined) {
  1534. simplemde.element.form.addEventListener("submit", function() {
  1535. localStorage.removeItem("smde_" + simplemde.options.autosave.uniqueId);
  1536. });
  1537. }
  1538. if(this.options.autosave.loaded !== true) {
  1539. if(typeof localStorage.getItem("smde_" + this.options.autosave.uniqueId) == "string" && localStorage.getItem("smde_" + this.options.autosave.uniqueId) != "") {
  1540. this.codemirror.setValue(localStorage.getItem("smde_" + this.options.autosave.uniqueId));
  1541. this.options.autosave.foundSavedValue = true;
  1542. }
  1543. this.options.autosave.loaded = true;
  1544. }
  1545. localStorage.setItem("smde_" + this.options.autosave.uniqueId, simplemde.value());
  1546. var el = document.getElementById("autosaved");
  1547. if(el != null && el != undefined && el != "") {
  1548. var d = new Date();
  1549. var hh = d.getHours();
  1550. var m = d.getMinutes();
  1551. var dd = "am";
  1552. var h = hh;
  1553. if(h >= 12) {
  1554. h = hh - 12;
  1555. dd = "pm";
  1556. }
  1557. if(h == 0) {
  1558. h = 12;
  1559. }
  1560. m = m < 10 ? "0" + m : m;
  1561. el.innerHTML = "Autosaved: " + h + ":" + m + " " + dd;
  1562. }
  1563. this.autosaveTimeoutId = setTimeout(function() {
  1564. simplemde.autosave();
  1565. }, this.options.autosave.delay || 10000);
  1566. } else {
  1567. console.log("SimpleMDE: localStorage not available, cannot autosave");
  1568. }
  1569. };
  1570. SimpleMDE.prototype.clearAutosavedValue = function() {
  1571. if(isLocalStorageAvailable()) {
  1572. if(this.options.autosave == undefined || this.options.autosave.uniqueId == undefined || this.options.autosave.uniqueId == "") {
  1573. console.log("SimpleMDE: You must set a uniqueId to clear the autosave value");
  1574. return;
  1575. }
  1576. localStorage.removeItem("smde_" + this.options.autosave.uniqueId);
  1577. } else {
  1578. console.log("SimpleMDE: localStorage not available, cannot autosave");
  1579. }
  1580. };
  1581. SimpleMDE.prototype.createSideBySide = function() {
  1582. var cm = this.codemirror;
  1583. var wrapper = cm.getWrapperElement();
  1584. var preview = wrapper.nextSibling;
  1585. if(!preview || !/editor-preview-side/.test(preview.className)) {
  1586. preview = document.createElement("div");
  1587. preview.className = "editor-preview-side";
  1588. wrapper.parentNode.insertBefore(preview, wrapper.nextSibling);
  1589. }
  1590. // Syncs scroll editor -> preview
  1591. var cScroll = false;
  1592. var pScroll = false;
  1593. cm.on("scroll", function(v) {
  1594. if(cScroll) {
  1595. cScroll = false;
  1596. return;
  1597. }
  1598. pScroll = true;
  1599. var height = v.getScrollInfo().height - v.getScrollInfo().clientHeight;
  1600. var ratio = parseFloat(v.getScrollInfo().top) / height;
  1601. var move = (preview.scrollHeight - preview.clientHeight) * ratio;
  1602. preview.scrollTop = move;
  1603. });
  1604. // Syncs scroll preview -> editor
  1605. preview.onscroll = function() {
  1606. if(pScroll) {
  1607. pScroll = false;
  1608. return;
  1609. }
  1610. cScroll = true;
  1611. var height = preview.scrollHeight - preview.clientHeight;
  1612. var ratio = parseFloat(preview.scrollTop) / height;
  1613. var move = (cm.getScrollInfo().height - cm.getScrollInfo().clientHeight) * ratio;
  1614. cm.scrollTo(0, move);
  1615. };
  1616. return preview;
  1617. };
  1618. SimpleMDE.prototype.createToolbar = function(items) {
  1619. items = items || this.options.toolbar;
  1620. if(!items || items.length === 0) {
  1621. return;
  1622. }
  1623. var i;
  1624. for(i = 0; i < items.length; i++) {
  1625. if(toolbarBuiltInButtons[items[i]] != undefined) {
  1626. items[i] = toolbarBuiltInButtons[items[i]];
  1627. }
  1628. }
  1629. var bar = document.createElement("div");
  1630. bar.className = "editor-toolbar";
  1631. var self = this;
  1632. var toolbarData = {};
  1633. self.toolbar = items;
  1634. for(i = 0; i < items.length; i++) {
  1635. if(items[i].name == "guide" && self.options.toolbarGuideIcon === false)
  1636. continue;
  1637. if(self.options.hideIcons && self.options.hideIcons.indexOf(items[i].name) != -1)
  1638. continue;
  1639. // Fullscreen does not work well on mobile devices (even tablets)
  1640. // In the future, hopefully this can be resolved
  1641. if((items[i].name == "fullscreen" || items[i].name == "side-by-side") && isMobile())
  1642. continue;
  1643. // Don't include trailing separators
  1644. if(items[i] === "|") {
  1645. var nonSeparatorIconsFollow = false;
  1646. for(var x = (i + 1); x < items.length; x++) {
  1647. if(items[x] !== "|" && (!self.options.hideIcons || self.options.hideIcons.indexOf(items[x].name) == -1)) {
  1648. nonSeparatorIconsFollow = true;
  1649. }
  1650. }
  1651. if(!nonSeparatorIconsFollow)
  1652. continue;
  1653. }
  1654. // Create the icon and append to the toolbar
  1655. (function(item) {
  1656. var el;
  1657. if(item === "|") {
  1658. el = createSep();
  1659. } else {
  1660. el = createIcon(item, self.options.toolbarTips, self.options.shortcuts);
  1661. }
  1662. // bind events, special for info
  1663. if(item.action) {
  1664. if(typeof item.action === "function") {
  1665. el.onclick = function(e) {
  1666. e.preventDefault();
  1667. item.action(self);
  1668. };
  1669. } else if(typeof item.action === "string") {
  1670. el.href = item.action;
  1671. el.target = "_blank";
  1672. }
  1673. }
  1674. toolbarData[item.name || item] = el;
  1675. bar.appendChild(el);
  1676. })(items[i]);
  1677. }
  1678. self.toolbarElements = toolbarData;
  1679. var cm = this.codemirror;
  1680. cm.on("cursorActivity", function() {
  1681. var stat = getState(cm);
  1682. for(var key in toolbarData) {
  1683. (function(key) {
  1684. var el = toolbarData[key];
  1685. if(stat[key]) {
  1686. el.className += " active";
  1687. } else if(key != "fullscreen" && key != "side-by-side") {
  1688. el.className = el.className.replace(/\s*active\s*/g, "");
  1689. }
  1690. })(key);
  1691. }
  1692. });
  1693. var cmWrapper = cm.getWrapperElement();
  1694. cmWrapper.parentNode.insertBefore(bar, cmWrapper);
  1695. return bar;
  1696. };
  1697. SimpleMDE.prototype.createStatusbar = function(status) {
  1698. // Initialize
  1699. status = status || this.options.status;
  1700. var options = this.options;
  1701. var cm = this.codemirror;
  1702. // Make sure the status variable is valid
  1703. if(!status || status.length === 0)
  1704. return;
  1705. // Set up the built-in items
  1706. var items = [];
  1707. var i, onUpdate, defaultValue;
  1708. for(i = 0; i < status.length; i++) {
  1709. // Reset some values
  1710. onUpdate = undefined;
  1711. defaultValue = undefined;
  1712. // Handle if custom or not
  1713. if(typeof status[i] === "object") {
  1714. items.push({
  1715. className: status[i].className,
  1716. defaultValue: status[i].defaultValue,
  1717. onUpdate: status[i].onUpdate
  1718. });
  1719. } else {
  1720. var name = status[i];
  1721. if(name === "words") {
  1722. defaultValue = function(el) {
  1723. el.innerHTML = wordCount(cm.getValue());
  1724. };
  1725. onUpdate = function(el) {
  1726. el.innerHTML = wordCount(cm.getValue());
  1727. };
  1728. } else if(name === "lines") {
  1729. defaultValue = function(el) {
  1730. el.innerHTML = cm.lineCount();
  1731. };
  1732. onUpdate = function(el) {
  1733. el.innerHTML = cm.lineCount();
  1734. };
  1735. } else if(name === "cursor") {
  1736. defaultValue = function(el) {
  1737. el.innerHTML = "0:0";
  1738. };
  1739. onUpdate = function(el) {
  1740. var pos = cm.getCursor();
  1741. el.innerHTML = pos.line + ":" + pos.ch;
  1742. };
  1743. } else if(name === "autosave") {
  1744. defaultValue = function(el) {
  1745. if(options.autosave != undefined && options.autosave.enabled === true) {
  1746. el.setAttribute("id", "autosaved");
  1747. }
  1748. };
  1749. }
  1750. items.push({
  1751. className: name,
  1752. defaultValue: defaultValue,
  1753. onUpdate: onUpdate
  1754. });
  1755. }
  1756. }
  1757. // Create element for the status bar
  1758. var bar = document.createElement("div");
  1759. bar.className = "editor-statusbar";
  1760. // Create a new span for each item
  1761. for(i = 0; i < items.length; i++) {
  1762. // Store in temporary variable
  1763. var item = items[i];
  1764. // Create span element
  1765. var el = document.createElement("span");
  1766. el.className = item.className;
  1767. // Ensure the defaultValue is a function
  1768. if(typeof item.defaultValue === "function") {
  1769. item.defaultValue(el);
  1770. }
  1771. // Ensure the onUpdate is a function
  1772. if(typeof item.onUpdate === "function") {
  1773. // Create a closure around the span of the current action, then execute the onUpdate handler
  1774. this.codemirror.on("update", (function(el, item) {
  1775. return function() {
  1776. item.onUpdate(el);
  1777. };
  1778. }(el, item)));
  1779. }
  1780. // Append the item to the status bar
  1781. bar.appendChild(el);
  1782. }
  1783. // Insert the status bar into the DOM
  1784. var cmWrapper = this.codemirror.getWrapperElement();
  1785. cmWrapper.parentNode.insertBefore(bar, cmWrapper.nextSibling);
  1786. return bar;
  1787. };
  1788. /**
  1789. * Get or set the text content.
  1790. */
  1791. SimpleMDE.prototype.value = function(val) {
  1792. if(val === undefined) {
  1793. return this.codemirror.getValue();
  1794. } else {
  1795. this.codemirror.getDoc().setValue(val);
  1796. return this;
  1797. }
  1798. };
  1799. /**
  1800. * Bind static methods for exports.
  1801. */
  1802. SimpleMDE.toggleBold = toggleBold;
  1803. SimpleMDE.toggleItalic = toggleItalic;
  1804. SimpleMDE.toggleStrikethrough = toggleStrikethrough;
  1805. SimpleMDE.toggleBlockquote = toggleBlockquote;
  1806. SimpleMDE.toggleHeadingSmaller = toggleHeadingSmaller;
  1807. SimpleMDE.toggleHeadingBigger = toggleHeadingBigger;
  1808. SimpleMDE.toggleHeading1 = toggleHeading1;
  1809. SimpleMDE.toggleHeading2 = toggleHeading2;
  1810. SimpleMDE.toggleHeading3 = toggleHeading3;
  1811. SimpleMDE.toggleCodeBlock = toggleCodeBlock;
  1812. SimpleMDE.toggleUnorderedList = toggleUnorderedList;
  1813. SimpleMDE.toggleOrderedList = toggleOrderedList;
  1814. SimpleMDE.cleanBlock = cleanBlock;
  1815. SimpleMDE.drawLink = drawLink;
  1816. SimpleMDE.drawImage = drawImage;
  1817. SimpleMDE.drawTable = drawTable;
  1818. SimpleMDE.drawHorizontalRule = drawHorizontalRule;
  1819. SimpleMDE.undo = undo;
  1820. SimpleMDE.redo = redo;
  1821. SimpleMDE.togglePreview = togglePreview;
  1822. SimpleMDE.toggleSideBySide = toggleSideBySide;
  1823. SimpleMDE.toggleFullScreen = toggleFullScreen;
  1824. /**
  1825. * Bind instance methods for exports.
  1826. */
  1827. SimpleMDE.prototype.toggleBold = function() {
  1828. toggleBold(this);
  1829. };
  1830. SimpleMDE.prototype.toggleItalic = function() {
  1831. toggleItalic(this);
  1832. };
  1833. SimpleMDE.prototype.toggleStrikethrough = function() {
  1834. toggleStrikethrough(this);
  1835. };
  1836. SimpleMDE.prototype.toggleBlockquote = function() {
  1837. toggleBlockquote(this);
  1838. };
  1839. SimpleMDE.prototype.toggleHeadingSmaller = function() {
  1840. toggleHeadingSmaller(this);
  1841. };
  1842. SimpleMDE.prototype.toggleHeadingBigger = function() {
  1843. toggleHeadingBigger(this);
  1844. };
  1845. SimpleMDE.prototype.toggleHeading1 = function() {
  1846. toggleHeading1(this);
  1847. };
  1848. SimpleMDE.prototype.toggleHeading2 = function() {
  1849. toggleHeading2(this);
  1850. };
  1851. SimpleMDE.prototype.toggleHeading3 = function() {
  1852. toggleHeading3(this);
  1853. };
  1854. SimpleMDE.prototype.toggleCodeBlock = function() {
  1855. toggleCodeBlock(this);
  1856. };
  1857. SimpleMDE.prototype.toggleUnorderedList = function() {
  1858. toggleUnorderedList(this);
  1859. };
  1860. SimpleMDE.prototype.toggleOrderedList = function() {
  1861. toggleOrderedList(this);
  1862. };
  1863. SimpleMDE.prototype.cleanBlock = function() {
  1864. cleanBlock(this);
  1865. };
  1866. SimpleMDE.prototype.drawLink = function() {
  1867. drawLink(this);
  1868. };
  1869. SimpleMDE.prototype.drawImage = function() {
  1870. drawImage(this);
  1871. };
  1872. SimpleMDE.prototype.drawTable = function() {
  1873. drawTable(this);
  1874. };
  1875. SimpleMDE.prototype.drawHorizontalRule = function() {
  1876. drawHorizontalRule(this);
  1877. };
  1878. SimpleMDE.prototype.undo = function() {
  1879. undo(this);
  1880. };
  1881. SimpleMDE.prototype.redo = function() {
  1882. redo(this);
  1883. };
  1884. SimpleMDE.prototype.togglePreview = function() {
  1885. togglePreview(this);
  1886. };
  1887. SimpleMDE.prototype.toggleSideBySide = function() {
  1888. toggleSideBySide(this);
  1889. };
  1890. SimpleMDE.prototype.toggleFullScreen = function() {
  1891. toggleFullScreen(this);
  1892. };
  1893. SimpleMDE.prototype.isPreviewActive = function() {
  1894. var cm = this.codemirror;
  1895. var wrapper = cm.getWrapperElement();
  1896. var preview = wrapper.lastChild;
  1897. return /editor-preview-active/.test(preview.className);
  1898. };
  1899. SimpleMDE.prototype.isSideBySideActive = function() {
  1900. var cm = this.codemirror;
  1901. var wrapper = cm.getWrapperElement();
  1902. var preview = wrapper.nextSibling;
  1903. return /editor-preview-active-side/.test(preview.className);
  1904. };
  1905. SimpleMDE.prototype.isFullscreenActive = function() {
  1906. var cm = this.codemirror;
  1907. return cm.getOption("fullScreen");
  1908. };
  1909. SimpleMDE.prototype.getState = function() {
  1910. var cm = this.codemirror;
  1911. return getState(cm);
  1912. };
  1913. SimpleMDE.prototype.toTextArea = function() {
  1914. var cm = this.codemirror;
  1915. var wrapper = cm.getWrapperElement();
  1916. if(wrapper.parentNode) {
  1917. if(this.gui.toolbar) {
  1918. wrapper.parentNode.removeChild(this.gui.toolbar);
  1919. }
  1920. if(this.gui.statusbar) {
  1921. wrapper.parentNode.removeChild(this.gui.statusbar);
  1922. }
  1923. if(this.gui.sideBySide) {
  1924. wrapper.parentNode.removeChild(this.gui.sideBySide);
  1925. }
  1926. }
  1927. cm.toTextArea();
  1928. if(this.autosaveTimeoutId) {
  1929. clearTimeout(this.autosaveTimeoutId);
  1930. this.autosaveTimeoutId = undefined;
  1931. this.clearAutosavedValue();
  1932. }
  1933. };
  1934. module.exports = SimpleMDE;
  1935. /***/ }),
  1936. /* 5 */
  1937. /***/ (function(module, exports, __webpack_require__) {
  1938. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  1939. // Distributed under an MIT license: http://codemirror.net/LICENSE
  1940. // This is CodeMirror (http://codemirror.net), a code editor
  1941. // implemented in JavaScript on top of the browser's DOM.
  1942. //
  1943. // You can find some technical background for some of the code below
  1944. // at http://marijnhaverbeke.nl/blog/#cm-internals .
  1945. (function (global, factory) {
  1946. true ? module.exports = factory() :
  1947. typeof define === 'function' && define.amd ? define(factory) :
  1948. (global.CodeMirror = factory());
  1949. }(this, (function () { 'use strict';
  1950. // Kludges for bugs and behavior differences that can't be feature
  1951. // detected are enabled based on userAgent etc sniffing.
  1952. var userAgent = navigator.userAgent;
  1953. var platform = navigator.platform;
  1954. var gecko = /gecko\/\d/i.test(userAgent);
  1955. var ie_upto10 = /MSIE \d/.test(userAgent);
  1956. var ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(userAgent);
  1957. var edge = /Edge\/(\d+)/.exec(userAgent);
  1958. var ie = ie_upto10 || ie_11up || edge;
  1959. var ie_version = ie && (ie_upto10 ? document.documentMode || 6 : +(edge || ie_11up)[1]);
  1960. var webkit = !edge && /WebKit\//.test(userAgent);
  1961. var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(userAgent);
  1962. var chrome = !edge && /Chrome\//.test(userAgent);
  1963. var presto = /Opera\//.test(userAgent);
  1964. var safari = /Apple Computer/.test(navigator.vendor);
  1965. var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(userAgent);
  1966. var phantom = /PhantomJS/.test(userAgent);
  1967. var ios = !edge && /AppleWebKit/.test(userAgent) && /Mobile\/\w+/.test(userAgent);
  1968. var android = /Android/.test(userAgent);
  1969. // This is woefully incomplete. Suggestions for alternative methods welcome.
  1970. var mobile = ios || android || /webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(userAgent);
  1971. var mac = ios || /Mac/.test(platform);
  1972. var chromeOS = /\bCrOS\b/.test(userAgent);
  1973. var windows = /win/i.test(platform);
  1974. var presto_version = presto && userAgent.match(/Version\/(\d*\.\d*)/);
  1975. if (presto_version) { presto_version = Number(presto_version[1]); }
  1976. if (presto_version && presto_version >= 15) { presto = false; webkit = true; }
  1977. // Some browsers use the wrong event properties to signal cmd/ctrl on OS X
  1978. var flipCtrlCmd = mac && (qtwebkit || presto && (presto_version == null || presto_version < 12.11));
  1979. var captureRightClick = gecko || (ie && ie_version >= 9);
  1980. function classTest(cls) { return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*") }
  1981. var rmClass = function(node, cls) {
  1982. var current = node.className;
  1983. var match = classTest(cls).exec(current);
  1984. if (match) {
  1985. var after = current.slice(match.index + match[0].length);
  1986. node.className = current.slice(0, match.index) + (after ? match[1] + after : "");
  1987. }
  1988. };
  1989. function removeChildren(e) {
  1990. for (var count = e.childNodes.length; count > 0; --count)
  1991. { e.removeChild(e.firstChild); }
  1992. return e
  1993. }
  1994. function removeChildrenAndAdd(parent, e) {
  1995. return removeChildren(parent).appendChild(e)
  1996. }
  1997. function elt(tag, content, className, style) {
  1998. var e = document.createElement(tag);
  1999. if (className) { e.className = className; }
  2000. if (style) { e.style.cssText = style; }
  2001. if (typeof content == "string") { e.appendChild(document.createTextNode(content)); }
  2002. else if (content) { for (var i = 0; i < content.length; ++i) { e.appendChild(content[i]); } }
  2003. return e
  2004. }
  2005. // wrapper for elt, which removes the elt from the accessibility tree
  2006. function eltP(tag, content, className, style) {
  2007. var e = elt(tag, content, className, style);
  2008. e.setAttribute("role", "presentation");
  2009. return e
  2010. }
  2011. var range;
  2012. if (document.createRange) { range = function(node, start, end, endNode) {
  2013. var r = document.createRange();
  2014. r.setEnd(endNode || node, end);
  2015. r.setStart(node, start);
  2016. return r
  2017. }; }
  2018. else { range = function(node, start, end) {
  2019. var r = document.body.createTextRange();
  2020. try { r.moveToElementText(node.parentNode); }
  2021. catch(e) { return r }
  2022. r.collapse(true);
  2023. r.moveEnd("character", end);
  2024. r.moveStart("character", start);
  2025. return r
  2026. }; }
  2027. function contains(parent, child) {
  2028. if (child.nodeType == 3) // Android browser always returns false when child is a textnode
  2029. { child = child.parentNode; }
  2030. if (parent.contains)
  2031. { return parent.contains(child) }
  2032. do {
  2033. if (child.nodeType == 11) { child = child.host; }
  2034. if (child == parent) { return true }
  2035. } while (child = child.parentNode)
  2036. }
  2037. function activeElt() {
  2038. // IE and Edge may throw an "Unspecified Error" when accessing document.activeElement.
  2039. // IE < 10 will throw when accessed while the page is loading or in an iframe.
  2040. // IE > 9 and Edge will throw when accessed in an iframe if document.body is unavailable.
  2041. var activeElement;
  2042. try {
  2043. activeElement = document.activeElement;
  2044. } catch(e) {
  2045. activeElement = document.body || null;
  2046. }
  2047. while (activeElement && activeElement.shadowRoot && activeElement.shadowRoot.activeElement)
  2048. { activeElement = activeElement.shadowRoot.activeElement; }
  2049. return activeElement
  2050. }
  2051. function addClass(node, cls) {
  2052. var current = node.className;
  2053. if (!classTest(cls).test(current)) { node.className += (current ? " " : "") + cls; }
  2054. }
  2055. function joinClasses(a, b) {
  2056. var as = a.split(" ");
  2057. for (var i = 0; i < as.length; i++)
  2058. { if (as[i] && !classTest(as[i]).test(b)) { b += " " + as[i]; } }
  2059. return b
  2060. }
  2061. var selectInput = function(node) { node.select(); };
  2062. if (ios) // Mobile Safari apparently has a bug where select() is broken.
  2063. { selectInput = function(node) { node.selectionStart = 0; node.selectionEnd = node.value.length; }; }
  2064. else if (ie) // Suppress mysterious IE10 errors
  2065. { selectInput = function(node) { try { node.select(); } catch(_e) {} }; }
  2066. function bind(f) {
  2067. var args = Array.prototype.slice.call(arguments, 1);
  2068. return function(){return f.apply(null, args)}
  2069. }
  2070. function copyObj(obj, target, overwrite) {
  2071. if (!target) { target = {}; }
  2072. for (var prop in obj)
  2073. { if (obj.hasOwnProperty(prop) && (overwrite !== false || !target.hasOwnProperty(prop)))
  2074. { target[prop] = obj[prop]; } }
  2075. return target
  2076. }
  2077. // Counts the column offset in a string, taking tabs into account.
  2078. // Used mostly to find indentation.
  2079. function countColumn(string, end, tabSize, startIndex, startValue) {
  2080. if (end == null) {
  2081. end = string.search(/[^\s\u00a0]/);
  2082. if (end == -1) { end = string.length; }
  2083. }
  2084. for (var i = startIndex || 0, n = startValue || 0;;) {
  2085. var nextTab = string.indexOf("\t", i);
  2086. if (nextTab < 0 || nextTab >= end)
  2087. { return n + (end - i) }
  2088. n += nextTab - i;
  2089. n += tabSize - (n % tabSize);
  2090. i = nextTab + 1;
  2091. }
  2092. }
  2093. var Delayed = function() {this.id = null;};
  2094. Delayed.prototype.set = function (ms, f) {
  2095. clearTimeout(this.id);
  2096. this.id = setTimeout(f, ms);
  2097. };
  2098. function indexOf(array, elt) {
  2099. for (var i = 0; i < array.length; ++i)
  2100. { if (array[i] == elt) { return i } }
  2101. return -1
  2102. }
  2103. // Number of pixels added to scroller and sizer to hide scrollbar
  2104. var scrollerGap = 30;
  2105. // Returned or thrown by various protocols to signal 'I'm not
  2106. // handling this'.
  2107. var Pass = {toString: function(){return "CodeMirror.Pass"}};
  2108. // Reused option objects for setSelection & friends
  2109. var sel_dontScroll = {scroll: false};
  2110. var sel_mouse = {origin: "*mouse"};
  2111. var sel_move = {origin: "+move"};
  2112. // The inverse of countColumn -- find the offset that corresponds to
  2113. // a particular column.
  2114. function findColumn(string, goal, tabSize) {
  2115. for (var pos = 0, col = 0;;) {
  2116. var nextTab = string.indexOf("\t", pos);
  2117. if (nextTab == -1) { nextTab = string.length; }
  2118. var skipped = nextTab - pos;
  2119. if (nextTab == string.length || col + skipped >= goal)
  2120. { return pos + Math.min(skipped, goal - col) }
  2121. col += nextTab - pos;
  2122. col += tabSize - (col % tabSize);
  2123. pos = nextTab + 1;
  2124. if (col >= goal) { return pos }
  2125. }
  2126. }
  2127. var spaceStrs = [""];
  2128. function spaceStr(n) {
  2129. while (spaceStrs.length <= n)
  2130. { spaceStrs.push(lst(spaceStrs) + " "); }
  2131. return spaceStrs[n]
  2132. }
  2133. function lst(arr) { return arr[arr.length-1] }
  2134. function map(array, f) {
  2135. var out = [];
  2136. for (var i = 0; i < array.length; i++) { out[i] = f(array[i], i); }
  2137. return out
  2138. }
  2139. function insertSorted(array, value, score) {
  2140. var pos = 0, priority = score(value);
  2141. while (pos < array.length && score(array[pos]) <= priority) { pos++; }
  2142. array.splice(pos, 0, value);
  2143. }
  2144. function nothing() {}
  2145. function createObj(base, props) {
  2146. var inst;
  2147. if (Object.create) {
  2148. inst = Object.create(base);
  2149. } else {
  2150. nothing.prototype = base;
  2151. inst = new nothing();
  2152. }
  2153. if (props) { copyObj(props, inst); }
  2154. return inst
  2155. }
  2156. var nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;
  2157. function isWordCharBasic(ch) {
  2158. return /\w/.test(ch) || ch > "\x80" &&
  2159. (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch))
  2160. }
  2161. function isWordChar(ch, helper) {
  2162. if (!helper) { return isWordCharBasic(ch) }
  2163. if (helper.source.indexOf("\\w") > -1 && isWordCharBasic(ch)) { return true }
  2164. return helper.test(ch)
  2165. }
  2166. function isEmpty(obj) {
  2167. for (var n in obj) { if (obj.hasOwnProperty(n) && obj[n]) { return false } }
  2168. return true
  2169. }
  2170. // Extending unicode characters. A series of a non-extending char +
  2171. // any number of extending chars is treated as a single unit as far
  2172. // as editing and measuring is concerned. This is not fully correct,
  2173. // since some scripts/fonts/browsers also treat other configurations
  2174. // of code points as a group.
  2175. 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]/;
  2176. function isExtendingChar(ch) { return ch.charCodeAt(0) >= 768 && extendingChars.test(ch) }
  2177. // Returns a number from the range [`0`; `str.length`] unless `pos` is outside that range.
  2178. function skipExtendingChars(str, pos, dir) {
  2179. while ((dir < 0 ? pos > 0 : pos < str.length) && isExtendingChar(str.charAt(pos))) { pos += dir; }
  2180. return pos
  2181. }
  2182. // Returns the value from the range [`from`; `to`] that satisfies
  2183. // `pred` and is closest to `from`. Assumes that at least `to`
  2184. // satisfies `pred`. Supports `from` being greater than `to`.
  2185. function findFirst(pred, from, to) {
  2186. // At any point we are certain `to` satisfies `pred`, don't know
  2187. // whether `from` does.
  2188. var dir = from > to ? -1 : 1;
  2189. for (;;) {
  2190. if (from == to) { return from }
  2191. var midF = (from + to) / 2, mid = dir < 0 ? Math.ceil(midF) : Math.floor(midF);
  2192. if (mid == from) { return pred(mid) ? from : to }
  2193. if (pred(mid)) { to = mid; }
  2194. else { from = mid + dir; }
  2195. }
  2196. }
  2197. // The display handles the DOM integration, both for input reading
  2198. // and content drawing. It holds references to DOM nodes and
  2199. // display-related state.
  2200. function Display(place, doc, input) {
  2201. var d = this;
  2202. this.input = input;
  2203. // Covers bottom-right square when both scrollbars are present.
  2204. d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler");
  2205. d.scrollbarFiller.setAttribute("cm-not-content", "true");
  2206. // Covers bottom of gutter when coverGutterNextToScrollbar is on
  2207. // and h scrollbar is present.
  2208. d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler");
  2209. d.gutterFiller.setAttribute("cm-not-content", "true");
  2210. // Will contain the actual code, positioned to cover the viewport.
  2211. d.lineDiv = eltP("div", null, "CodeMirror-code");
  2212. // Elements are added to these to represent selection and cursors.
  2213. d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1");
  2214. d.cursorDiv = elt("div", null, "CodeMirror-cursors");
  2215. // A visibility: hidden element used to find the size of things.
  2216. d.measure = elt("div", null, "CodeMirror-measure");
  2217. // When lines outside of the viewport are measured, they are drawn in this.
  2218. d.lineMeasure = elt("div", null, "CodeMirror-measure");
  2219. // Wraps everything that needs to exist inside the vertically-padded coordinate system
  2220. d.lineSpace = eltP("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv],
  2221. null, "position: relative; outline: none");
  2222. var lines = eltP("div", [d.lineSpace], "CodeMirror-lines");
  2223. // Moved around its parent to cover visible view.
  2224. d.mover = elt("div", [lines], null, "position: relative");
  2225. // Set to the height of the document, allowing scrolling.
  2226. d.sizer = elt("div", [d.mover], "CodeMirror-sizer");
  2227. d.sizerWidth = null;
  2228. // Behavior of elts with overflow: auto and padding is
  2229. // inconsistent across browsers. This is used to ensure the
  2230. // scrollable area is big enough.
  2231. d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerGap + "px; width: 1px;");
  2232. // Will contain the gutters, if any.
  2233. d.gutters = elt("div", null, "CodeMirror-gutters");
  2234. d.lineGutter = null;
  2235. // Actual scrollable element.
  2236. d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll");
  2237. d.scroller.setAttribute("tabIndex", "-1");
  2238. // The element in which the editor lives.
  2239. d.wrapper = elt("div", [d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror");
  2240. // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported)
  2241. if (ie && ie_version < 8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; }
  2242. if (!webkit && !(gecko && mobile)) { d.scroller.draggable = true; }
  2243. if (place) {
  2244. if (place.appendChild) { place.appendChild(d.wrapper); }
  2245. else { place(d.wrapper); }
  2246. }
  2247. // Current rendered range (may be bigger than the view window).
  2248. d.viewFrom = d.viewTo = doc.first;
  2249. d.reportedViewFrom = d.reportedViewTo = doc.first;
  2250. // Information about the rendered lines.
  2251. d.view = [];
  2252. d.renderedView = null;
  2253. // Holds info about a single rendered line when it was rendered
  2254. // for measurement, while not in view.
  2255. d.externalMeasured = null;
  2256. // Empty space (in pixels) above the view
  2257. d.viewOffset = 0;
  2258. d.lastWrapHeight = d.lastWrapWidth = 0;
  2259. d.updateLineNumbers = null;
  2260. d.nativeBarWidth = d.barHeight = d.barWidth = 0;
  2261. d.scrollbarsClipped = false;
  2262. // Used to only resize the line number gutter when necessary (when
  2263. // the amount of lines crosses a boundary that makes its width change)
  2264. d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null;
  2265. // Set to true when a non-horizontal-scrolling line widget is
  2266. // added. As an optimization, line widget aligning is skipped when
  2267. // this is false.
  2268. d.alignWidgets = false;
  2269. d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
  2270. // Tracks the maximum line length so that the horizontal scrollbar
  2271. // can be kept static when scrolling.
  2272. d.maxLine = null;
  2273. d.maxLineLength = 0;
  2274. d.maxLineChanged = false;
  2275. // Used for measuring wheel scrolling granularity
  2276. d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null;
  2277. // True when shift is held down.
  2278. d.shift = false;
  2279. // Used to track whether anything happened since the context menu
  2280. // was opened.
  2281. d.selForContextMenu = null;
  2282. d.activeTouch = null;
  2283. input.init(d);
  2284. }
  2285. // Find the line object corresponding to the given line number.
  2286. function getLine(doc, n) {
  2287. n -= doc.first;
  2288. if (n < 0 || n >= doc.size) { throw new Error("There is no line " + (n + doc.first) + " in the document.") }
  2289. var chunk = doc;
  2290. while (!chunk.lines) {
  2291. for (var i = 0;; ++i) {
  2292. var child = chunk.children[i], sz = child.chunkSize();
  2293. if (n < sz) { chunk = child; break }
  2294. n -= sz;
  2295. }
  2296. }
  2297. return chunk.lines[n]
  2298. }
  2299. // Get the part of a document between two positions, as an array of
  2300. // strings.
  2301. function getBetween(doc, start, end) {
  2302. var out = [], n = start.line;
  2303. doc.iter(start.line, end.line + 1, function (line) {
  2304. var text = line.text;
  2305. if (n == end.line) { text = text.slice(0, end.ch); }
  2306. if (n == start.line) { text = text.slice(start.ch); }
  2307. out.push(text);
  2308. ++n;
  2309. });
  2310. return out
  2311. }
  2312. // Get the lines between from and to, as array of strings.
  2313. function getLines(doc, from, to) {
  2314. var out = [];
  2315. doc.iter(from, to, function (line) { out.push(line.text); }); // iter aborts when callback returns truthy value
  2316. return out
  2317. }
  2318. // Update the height of a line, propagating the height change
  2319. // upwards to parent nodes.
  2320. function updateLineHeight(line, height) {
  2321. var diff = height - line.height;
  2322. if (diff) { for (var n = line; n; n = n.parent) { n.height += diff; } }
  2323. }
  2324. // Given a line object, find its line number by walking up through
  2325. // its parent links.
  2326. function lineNo(line) {
  2327. if (line.parent == null) { return null }
  2328. var cur = line.parent, no = indexOf(cur.lines, line);
  2329. for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) {
  2330. for (var i = 0;; ++i) {
  2331. if (chunk.children[i] == cur) { break }
  2332. no += chunk.children[i].chunkSize();
  2333. }
  2334. }
  2335. return no + cur.first
  2336. }
  2337. // Find the line at the given vertical position, using the height
  2338. // information in the document tree.
  2339. function lineAtHeight(chunk, h) {
  2340. var n = chunk.first;
  2341. outer: do {
  2342. for (var i$1 = 0; i$1 < chunk.children.length; ++i$1) {
  2343. var child = chunk.children[i$1], ch = child.height;
  2344. if (h < ch) { chunk = child; continue outer }
  2345. h -= ch;
  2346. n += child.chunkSize();
  2347. }
  2348. return n
  2349. } while (!chunk.lines)
  2350. var i = 0;
  2351. for (; i < chunk.lines.length; ++i) {
  2352. var line = chunk.lines[i], lh = line.height;
  2353. if (h < lh) { break }
  2354. h -= lh;
  2355. }
  2356. return n + i
  2357. }
  2358. function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size}
  2359. function lineNumberFor(options, i) {
  2360. return String(options.lineNumberFormatter(i + options.firstLineNumber))
  2361. }
  2362. // A Pos instance represents a position within the text.
  2363. function Pos(line, ch, sticky) {
  2364. if ( sticky === void 0 ) sticky = null;
  2365. if (!(this instanceof Pos)) { return new Pos(line, ch, sticky) }
  2366. this.line = line;
  2367. this.ch = ch;
  2368. this.sticky = sticky;
  2369. }
  2370. // Compare two positions, return 0 if they are the same, a negative
  2371. // number when a is less, and a positive number otherwise.
  2372. function cmp(a, b) { return a.line - b.line || a.ch - b.ch }
  2373. function equalCursorPos(a, b) { return a.sticky == b.sticky && cmp(a, b) == 0 }
  2374. function copyPos(x) {return Pos(x.line, x.ch)}
  2375. function maxPos(a, b) { return cmp(a, b) < 0 ? b : a }
  2376. function minPos(a, b) { return cmp(a, b) < 0 ? a : b }
  2377. // Most of the external API clips given positions to make sure they
  2378. // actually exist within the document.
  2379. function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1))}
  2380. function clipPos(doc, pos) {
  2381. if (pos.line < doc.first) { return Pos(doc.first, 0) }
  2382. var last = doc.first + doc.size - 1;
  2383. if (pos.line > last) { return Pos(last, getLine(doc, last).text.length) }
  2384. return clipToLen(pos, getLine(doc, pos.line).text.length)
  2385. }
  2386. function clipToLen(pos, linelen) {
  2387. var ch = pos.ch;
  2388. if (ch == null || ch > linelen) { return Pos(pos.line, linelen) }
  2389. else if (ch < 0) { return Pos(pos.line, 0) }
  2390. else { return pos }
  2391. }
  2392. function clipPosArray(doc, array) {
  2393. var out = [];
  2394. for (var i = 0; i < array.length; i++) { out[i] = clipPos(doc, array[i]); }
  2395. return out
  2396. }
  2397. // Optimize some code when these features are not used.
  2398. var sawReadOnlySpans = false;
  2399. var sawCollapsedSpans = false;
  2400. function seeReadOnlySpans() {
  2401. sawReadOnlySpans = true;
  2402. }
  2403. function seeCollapsedSpans() {
  2404. sawCollapsedSpans = true;
  2405. }
  2406. // TEXTMARKER SPANS
  2407. function MarkedSpan(marker, from, to) {
  2408. this.marker = marker;
  2409. this.from = from; this.to = to;
  2410. }
  2411. // Search an array of spans for a span matching the given marker.
  2412. function getMarkedSpanFor(spans, marker) {
  2413. if (spans) { for (var i = 0; i < spans.length; ++i) {
  2414. var span = spans[i];
  2415. if (span.marker == marker) { return span }
  2416. } }
  2417. }
  2418. // Remove a span from an array, returning undefined if no spans are
  2419. // left (we don't store arrays for lines without spans).
  2420. function removeMarkedSpan(spans, span) {
  2421. var r;
  2422. for (var i = 0; i < spans.length; ++i)
  2423. { if (spans[i] != span) { (r || (r = [])).push(spans[i]); } }
  2424. return r
  2425. }
  2426. // Add a span to a line.
  2427. function addMarkedSpan(line, span) {
  2428. line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span];
  2429. span.marker.attachLine(line);
  2430. }
  2431. // Used for the algorithm that adjusts markers for a change in the
  2432. // document. These functions cut an array of spans at a given
  2433. // character position, returning an array of remaining chunks (or
  2434. // undefined if nothing remains).
  2435. function markedSpansBefore(old, startCh, isInsert) {
  2436. var nw;
  2437. if (old) { for (var i = 0; i < old.length; ++i) {
  2438. var span = old[i], marker = span.marker;
  2439. var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh);
  2440. if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) {
  2441. var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh);(nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to));
  2442. }
  2443. } }
  2444. return nw
  2445. }
  2446. function markedSpansAfter(old, endCh, isInsert) {
  2447. var nw;
  2448. if (old) { for (var i = 0; i < old.length; ++i) {
  2449. var span = old[i], marker = span.marker;
  2450. var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh);
  2451. if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) {
  2452. var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh);(nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh,
  2453. span.to == null ? null : span.to - endCh));
  2454. }
  2455. } }
  2456. return nw
  2457. }
  2458. // Given a change object, compute the new set of marker spans that
  2459. // cover the line in which the change took place. Removes spans
  2460. // entirely within the change, reconnects spans belonging to the
  2461. // same marker that appear on both sides of the change, and cuts off
  2462. // spans partially within the change. Returns an array of span
  2463. // arrays with one element for each line in (after) the change.
  2464. function stretchSpansOverChange(doc, change) {
  2465. if (change.full) { return null }
  2466. var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans;
  2467. var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans;
  2468. if (!oldFirst && !oldLast) { return null }
  2469. var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0;
  2470. // Get the spans that 'stick out' on both sides
  2471. var first = markedSpansBefore(oldFirst, startCh, isInsert);
  2472. var last = markedSpansAfter(oldLast, endCh, isInsert);
  2473. // Next, merge those two ends
  2474. var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0);
  2475. if (first) {
  2476. // Fix up .to properties of first
  2477. for (var i = 0; i < first.length; ++i) {
  2478. var span = first[i];
  2479. if (span.to == null) {
  2480. var found = getMarkedSpanFor(last, span.marker);
  2481. if (!found) { span.to = startCh; }
  2482. else if (sameLine) { span.to = found.to == null ? null : found.to + offset; }
  2483. }
  2484. }
  2485. }
  2486. if (last) {
  2487. // Fix up .from in last (or move them into first in case of sameLine)
  2488. for (var i$1 = 0; i$1 < last.length; ++i$1) {
  2489. var span$1 = last[i$1];
  2490. if (span$1.to != null) { span$1.to += offset; }
  2491. if (span$1.from == null) {
  2492. var found$1 = getMarkedSpanFor(first, span$1.marker);
  2493. if (!found$1) {
  2494. span$1.from = offset;
  2495. if (sameLine) { (first || (first = [])).push(span$1); }
  2496. }
  2497. } else {
  2498. span$1.from += offset;
  2499. if (sameLine) { (first || (first = [])).push(span$1); }
  2500. }
  2501. }
  2502. }
  2503. // Make sure we didn't create any zero-length spans
  2504. if (first) { first = clearEmptySpans(first); }
  2505. if (last && last != first) { last = clearEmptySpans(last); }
  2506. var newMarkers = [first];
  2507. if (!sameLine) {
  2508. // Fill gap with whole-line-spans
  2509. var gap = change.text.length - 2, gapMarkers;
  2510. if (gap > 0 && first)
  2511. { for (var i$2 = 0; i$2 < first.length; ++i$2)
  2512. { if (first[i$2].to == null)
  2513. { (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i$2].marker, null, null)); } } }
  2514. for (var i$3 = 0; i$3 < gap; ++i$3)
  2515. { newMarkers.push(gapMarkers); }
  2516. newMarkers.push(last);
  2517. }
  2518. return newMarkers
  2519. }
  2520. // Remove spans that are empty and don't have a clearWhenEmpty
  2521. // option of false.
  2522. function clearEmptySpans(spans) {
  2523. for (var i = 0; i < spans.length; ++i) {
  2524. var span = spans[i];
  2525. if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false)
  2526. { spans.splice(i--, 1); }
  2527. }
  2528. if (!spans.length) { return null }
  2529. return spans
  2530. }
  2531. // Used to 'clip' out readOnly ranges when making a change.
  2532. function removeReadOnlyRanges(doc, from, to) {
  2533. var markers = null;
  2534. doc.iter(from.line, to.line + 1, function (line) {
  2535. if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) {
  2536. var mark = line.markedSpans[i].marker;
  2537. if (mark.readOnly && (!markers || indexOf(markers, mark) == -1))
  2538. { (markers || (markers = [])).push(mark); }
  2539. } }
  2540. });
  2541. if (!markers) { return null }
  2542. var parts = [{from: from, to: to}];
  2543. for (var i = 0; i < markers.length; ++i) {
  2544. var mk = markers[i], m = mk.find(0);
  2545. for (var j = 0; j < parts.length; ++j) {
  2546. var p = parts[j];
  2547. if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) { continue }
  2548. var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to);
  2549. if (dfrom < 0 || !mk.inclusiveLeft && !dfrom)
  2550. { newParts.push({from: p.from, to: m.from}); }
  2551. if (dto > 0 || !mk.inclusiveRight && !dto)
  2552. { newParts.push({from: m.to, to: p.to}); }
  2553. parts.splice.apply(parts, newParts);
  2554. j += newParts.length - 3;
  2555. }
  2556. }
  2557. return parts
  2558. }
  2559. // Connect or disconnect spans from a line.
  2560. function detachMarkedSpans(line) {
  2561. var spans = line.markedSpans;
  2562. if (!spans) { return }
  2563. for (var i = 0; i < spans.length; ++i)
  2564. { spans[i].marker.detachLine(line); }
  2565. line.markedSpans = null;
  2566. }
  2567. function attachMarkedSpans(line, spans) {
  2568. if (!spans) { return }
  2569. for (var i = 0; i < spans.length; ++i)
  2570. { spans[i].marker.attachLine(line); }
  2571. line.markedSpans = spans;
  2572. }
  2573. // Helpers used when computing which overlapping collapsed span
  2574. // counts as the larger one.
  2575. function extraLeft(marker) { return marker.inclusiveLeft ? -1 : 0 }
  2576. function extraRight(marker) { return marker.inclusiveRight ? 1 : 0 }
  2577. // Returns a number indicating which of two overlapping collapsed
  2578. // spans is larger (and thus includes the other). Falls back to
  2579. // comparing ids when the spans cover exactly the same range.
  2580. function compareCollapsedMarkers(a, b) {
  2581. var lenDiff = a.lines.length - b.lines.length;
  2582. if (lenDiff != 0) { return lenDiff }
  2583. var aPos = a.find(), bPos = b.find();
  2584. var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b);
  2585. if (fromCmp) { return -fromCmp }
  2586. var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b);
  2587. if (toCmp) { return toCmp }
  2588. return b.id - a.id
  2589. }
  2590. // Find out whether a line ends or starts in a collapsed span. If
  2591. // so, return the marker for that span.
  2592. function collapsedSpanAtSide(line, start) {
  2593. var sps = sawCollapsedSpans && line.markedSpans, found;
  2594. if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) {
  2595. sp = sps[i];
  2596. if (sp.marker.collapsed && (start ? sp.from : sp.to) == null &&
  2597. (!found || compareCollapsedMarkers(found, sp.marker) < 0))
  2598. { found = sp.marker; }
  2599. } }
  2600. return found
  2601. }
  2602. function collapsedSpanAtStart(line) { return collapsedSpanAtSide(line, true) }
  2603. function collapsedSpanAtEnd(line) { return collapsedSpanAtSide(line, false) }
  2604. // Test whether there exists a collapsed span that partially
  2605. // overlaps (covers the start or end, but not both) of a new span.
  2606. // Such overlap is not allowed.
  2607. function conflictingCollapsedRange(doc, lineNo$$1, from, to, marker) {
  2608. var line = getLine(doc, lineNo$$1);
  2609. var sps = sawCollapsedSpans && line.markedSpans;
  2610. if (sps) { for (var i = 0; i < sps.length; ++i) {
  2611. var sp = sps[i];
  2612. if (!sp.marker.collapsed) { continue }
  2613. var found = sp.marker.find(0);
  2614. var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker);
  2615. var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker);
  2616. if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) { continue }
  2617. if (fromCmp <= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.to, from) >= 0 : cmp(found.to, from) > 0) ||
  2618. fromCmp >= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.from, to) <= 0 : cmp(found.from, to) < 0))
  2619. { return true }
  2620. } }
  2621. }
  2622. // A visual line is a line as drawn on the screen. Folding, for
  2623. // example, can cause multiple logical lines to appear on the same
  2624. // visual line. This finds the start of the visual line that the
  2625. // given line is part of (usually that is the line itself).
  2626. function visualLine(line) {
  2627. var merged;
  2628. while (merged = collapsedSpanAtStart(line))
  2629. { line = merged.find(-1, true).line; }
  2630. return line
  2631. }
  2632. function visualLineEnd(line) {
  2633. var merged;
  2634. while (merged = collapsedSpanAtEnd(line))
  2635. { line = merged.find(1, true).line; }
  2636. return line
  2637. }
  2638. // Returns an array of logical lines that continue the visual line
  2639. // started by the argument, or undefined if there are no such lines.
  2640. function visualLineContinued(line) {
  2641. var merged, lines;
  2642. while (merged = collapsedSpanAtEnd(line)) {
  2643. line = merged.find(1, true).line
  2644. ;(lines || (lines = [])).push(line);
  2645. }
  2646. return lines
  2647. }
  2648. // Get the line number of the start of the visual line that the
  2649. // given line number is part of.
  2650. function visualLineNo(doc, lineN) {
  2651. var line = getLine(doc, lineN), vis = visualLine(line);
  2652. if (line == vis) { return lineN }
  2653. return lineNo(vis)
  2654. }
  2655. // Get the line number of the start of the next visual line after
  2656. // the given line.
  2657. function visualLineEndNo(doc, lineN) {
  2658. if (lineN > doc.lastLine()) { return lineN }
  2659. var line = getLine(doc, lineN), merged;
  2660. if (!lineIsHidden(doc, line)) { return lineN }
  2661. while (merged = collapsedSpanAtEnd(line))
  2662. { line = merged.find(1, true).line; }
  2663. return lineNo(line) + 1
  2664. }
  2665. // Compute whether a line is hidden. Lines count as hidden when they
  2666. // are part of a visual line that starts with another line, or when
  2667. // they are entirely covered by collapsed, non-widget span.
  2668. function lineIsHidden(doc, line) {
  2669. var sps = sawCollapsedSpans && line.markedSpans;
  2670. if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) {
  2671. sp = sps[i];
  2672. if (!sp.marker.collapsed) { continue }
  2673. if (sp.from == null) { return true }
  2674. if (sp.marker.widgetNode) { continue }
  2675. if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp))
  2676. { return true }
  2677. } }
  2678. }
  2679. function lineIsHiddenInner(doc, line, span) {
  2680. if (span.to == null) {
  2681. var end = span.marker.find(1, true);
  2682. return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker))
  2683. }
  2684. if (span.marker.inclusiveRight && span.to == line.text.length)
  2685. { return true }
  2686. for (var sp = (void 0), i = 0; i < line.markedSpans.length; ++i) {
  2687. sp = line.markedSpans[i];
  2688. if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to &&
  2689. (sp.to == null || sp.to != span.from) &&
  2690. (sp.marker.inclusiveLeft || span.marker.inclusiveRight) &&
  2691. lineIsHiddenInner(doc, line, sp)) { return true }
  2692. }
  2693. }
  2694. // Find the height above the given line.
  2695. function heightAtLine(lineObj) {
  2696. lineObj = visualLine(lineObj);
  2697. var h = 0, chunk = lineObj.parent;
  2698. for (var i = 0; i < chunk.lines.length; ++i) {
  2699. var line = chunk.lines[i];
  2700. if (line == lineObj) { break }
  2701. else { h += line.height; }
  2702. }
  2703. for (var p = chunk.parent; p; chunk = p, p = chunk.parent) {
  2704. for (var i$1 = 0; i$1 < p.children.length; ++i$1) {
  2705. var cur = p.children[i$1];
  2706. if (cur == chunk) { break }
  2707. else { h += cur.height; }
  2708. }
  2709. }
  2710. return h
  2711. }
  2712. // Compute the character length of a line, taking into account
  2713. // collapsed ranges (see markText) that might hide parts, and join
  2714. // other lines onto it.
  2715. function lineLength(line) {
  2716. if (line.height == 0) { return 0 }
  2717. var len = line.text.length, merged, cur = line;
  2718. while (merged = collapsedSpanAtStart(cur)) {
  2719. var found = merged.find(0, true);
  2720. cur = found.from.line;
  2721. len += found.from.ch - found.to.ch;
  2722. }
  2723. cur = line;
  2724. while (merged = collapsedSpanAtEnd(cur)) {
  2725. var found$1 = merged.find(0, true);
  2726. len -= cur.text.length - found$1.from.ch;
  2727. cur = found$1.to.line;
  2728. len += cur.text.length - found$1.to.ch;
  2729. }
  2730. return len
  2731. }
  2732. // Find the longest line in the document.
  2733. function findMaxLine(cm) {
  2734. var d = cm.display, doc = cm.doc;
  2735. d.maxLine = getLine(doc, doc.first);
  2736. d.maxLineLength = lineLength(d.maxLine);
  2737. d.maxLineChanged = true;
  2738. doc.iter(function (line) {
  2739. var len = lineLength(line);
  2740. if (len > d.maxLineLength) {
  2741. d.maxLineLength = len;
  2742. d.maxLine = line;
  2743. }
  2744. });
  2745. }
  2746. // BIDI HELPERS
  2747. function iterateBidiSections(order, from, to, f) {
  2748. if (!order) { return f(from, to, "ltr", 0) }
  2749. var found = false;
  2750. for (var i = 0; i < order.length; ++i) {
  2751. var part = order[i];
  2752. if (part.from < to && part.to > from || from == to && part.to == from) {
  2753. f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr", i);
  2754. found = true;
  2755. }
  2756. }
  2757. if (!found) { f(from, to, "ltr"); }
  2758. }
  2759. var bidiOther = null;
  2760. function getBidiPartAt(order, ch, sticky) {
  2761. var found;
  2762. bidiOther = null;
  2763. for (var i = 0; i < order.length; ++i) {
  2764. var cur = order[i];
  2765. if (cur.from < ch && cur.to > ch) { return i }
  2766. if (cur.to == ch) {
  2767. if (cur.from != cur.to && sticky == "before") { found = i; }
  2768. else { bidiOther = i; }
  2769. }
  2770. if (cur.from == ch) {
  2771. if (cur.from != cur.to && sticky != "before") { found = i; }
  2772. else { bidiOther = i; }
  2773. }
  2774. }
  2775. return found != null ? found : bidiOther
  2776. }
  2777. // Bidirectional ordering algorithm
  2778. // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm
  2779. // that this (partially) implements.
  2780. // One-char codes used for character types:
  2781. // L (L): Left-to-Right
  2782. // R (R): Right-to-Left
  2783. // r (AL): Right-to-Left Arabic
  2784. // 1 (EN): European Number
  2785. // + (ES): European Number Separator
  2786. // % (ET): European Number Terminator
  2787. // n (AN): Arabic Number
  2788. // , (CS): Common Number Separator
  2789. // m (NSM): Non-Spacing Mark
  2790. // b (BN): Boundary Neutral
  2791. // s (B): Paragraph Separator
  2792. // t (S): Segment Separator
  2793. // w (WS): Whitespace
  2794. // N (ON): Other Neutrals
  2795. // Returns null if characters are ordered as they appear
  2796. // (left-to-right), or an array of sections ({from, to, level}
  2797. // objects) in the order in which they occur visually.
  2798. var bidiOrdering = (function() {
  2799. // Character types for codepoints 0 to 0xff
  2800. var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN";
  2801. // Character types for codepoints 0x600 to 0x6f9
  2802. var arabicTypes = "nnnnnnNNr%%r,rNNmmmmmmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmmmnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmnNmmmmmmrrmmNmmmmrr1111111111";
  2803. function charType(code) {
  2804. if (code <= 0xf7) { return lowTypes.charAt(code) }
  2805. else if (0x590 <= code && code <= 0x5f4) { return "R" }
  2806. else if (0x600 <= code && code <= 0x6f9) { return arabicTypes.charAt(code - 0x600) }
  2807. else if (0x6ee <= code && code <= 0x8ac) { return "r" }
  2808. else if (0x2000 <= code && code <= 0x200b) { return "w" }
  2809. else if (code == 0x200c) { return "b" }
  2810. else { return "L" }
  2811. }
  2812. var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/;
  2813. var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/;
  2814. function BidiSpan(level, from, to) {
  2815. this.level = level;
  2816. this.from = from; this.to = to;
  2817. }
  2818. return function(str, direction) {
  2819. var outerType = direction == "ltr" ? "L" : "R";
  2820. if (str.length == 0 || direction == "ltr" && !bidiRE.test(str)) { return false }
  2821. var len = str.length, types = [];
  2822. for (var i = 0; i < len; ++i)
  2823. { types.push(charType(str.charCodeAt(i))); }
  2824. // W1. Examine each non-spacing mark (NSM) in the level run, and
  2825. // change the type of the NSM to the type of the previous
  2826. // character. If the NSM is at the start of the level run, it will
  2827. // get the type of sor.
  2828. for (var i$1 = 0, prev = outerType; i$1 < len; ++i$1) {
  2829. var type = types[i$1];
  2830. if (type == "m") { types[i$1] = prev; }
  2831. else { prev = type; }
  2832. }
  2833. // W2. Search backwards from each instance of a European number
  2834. // until the first strong type (R, L, AL, or sor) is found. If an
  2835. // AL is found, change the type of the European number to Arabic
  2836. // number.
  2837. // W3. Change all ALs to R.
  2838. for (var i$2 = 0, cur = outerType; i$2 < len; ++i$2) {
  2839. var type$1 = types[i$2];
  2840. if (type$1 == "1" && cur == "r") { types[i$2] = "n"; }
  2841. else if (isStrong.test(type$1)) { cur = type$1; if (type$1 == "r") { types[i$2] = "R"; } }
  2842. }
  2843. // W4. A single European separator between two European numbers
  2844. // changes to a European number. A single common separator between
  2845. // two numbers of the same type changes to that type.
  2846. for (var i$3 = 1, prev$1 = types[0]; i$3 < len - 1; ++i$3) {
  2847. var type$2 = types[i$3];
  2848. if (type$2 == "+" && prev$1 == "1" && types[i$3+1] == "1") { types[i$3] = "1"; }
  2849. else if (type$2 == "," && prev$1 == types[i$3+1] &&
  2850. (prev$1 == "1" || prev$1 == "n")) { types[i$3] = prev$1; }
  2851. prev$1 = type$2;
  2852. }
  2853. // W5. A sequence of European terminators adjacent to European
  2854. // numbers changes to all European numbers.
  2855. // W6. Otherwise, separators and terminators change to Other
  2856. // Neutral.
  2857. for (var i$4 = 0; i$4 < len; ++i$4) {
  2858. var type$3 = types[i$4];
  2859. if (type$3 == ",") { types[i$4] = "N"; }
  2860. else if (type$3 == "%") {
  2861. var end = (void 0);
  2862. for (end = i$4 + 1; end < len && types[end] == "%"; ++end) {}
  2863. var replace = (i$4 && types[i$4-1] == "!") || (end < len && types[end] == "1") ? "1" : "N";
  2864. for (var j = i$4; j < end; ++j) { types[j] = replace; }
  2865. i$4 = end - 1;
  2866. }
  2867. }
  2868. // W7. Search backwards from each instance of a European number
  2869. // until the first strong type (R, L, or sor) is found. If an L is
  2870. // found, then change the type of the European number to L.
  2871. for (var i$5 = 0, cur$1 = outerType; i$5 < len; ++i$5) {
  2872. var type$4 = types[i$5];
  2873. if (cur$1 == "L" && type$4 == "1") { types[i$5] = "L"; }
  2874. else if (isStrong.test(type$4)) { cur$1 = type$4; }
  2875. }
  2876. // N1. A sequence of neutrals takes the direction of the
  2877. // surrounding strong text if the text on both sides has the same
  2878. // direction. European and Arabic numbers act as if they were R in
  2879. // terms of their influence on neutrals. Start-of-level-run (sor)
  2880. // and end-of-level-run (eor) are used at level run boundaries.
  2881. // N2. Any remaining neutrals take the embedding direction.
  2882. for (var i$6 = 0; i$6 < len; ++i$6) {
  2883. if (isNeutral.test(types[i$6])) {
  2884. var end$1 = (void 0);
  2885. for (end$1 = i$6 + 1; end$1 < len && isNeutral.test(types[end$1]); ++end$1) {}
  2886. var before = (i$6 ? types[i$6-1] : outerType) == "L";
  2887. var after = (end$1 < len ? types[end$1] : outerType) == "L";
  2888. var replace$1 = before == after ? (before ? "L" : "R") : outerType;
  2889. for (var j$1 = i$6; j$1 < end$1; ++j$1) { types[j$1] = replace$1; }
  2890. i$6 = end$1 - 1;
  2891. }
  2892. }
  2893. // Here we depart from the documented algorithm, in order to avoid
  2894. // building up an actual levels array. Since there are only three
  2895. // levels (0, 1, 2) in an implementation that doesn't take
  2896. // explicit embedding into account, we can build up the order on
  2897. // the fly, without following the level-based algorithm.
  2898. var order = [], m;
  2899. for (var i$7 = 0; i$7 < len;) {
  2900. if (countsAsLeft.test(types[i$7])) {
  2901. var start = i$7;
  2902. for (++i$7; i$7 < len && countsAsLeft.test(types[i$7]); ++i$7) {}
  2903. order.push(new BidiSpan(0, start, i$7));
  2904. } else {
  2905. var pos = i$7, at = order.length;
  2906. for (++i$7; i$7 < len && types[i$7] != "L"; ++i$7) {}
  2907. for (var j$2 = pos; j$2 < i$7;) {
  2908. if (countsAsNum.test(types[j$2])) {
  2909. if (pos < j$2) { order.splice(at, 0, new BidiSpan(1, pos, j$2)); }
  2910. var nstart = j$2;
  2911. for (++j$2; j$2 < i$7 && countsAsNum.test(types[j$2]); ++j$2) {}
  2912. order.splice(at, 0, new BidiSpan(2, nstart, j$2));
  2913. pos = j$2;
  2914. } else { ++j$2; }
  2915. }
  2916. if (pos < i$7) { order.splice(at, 0, new BidiSpan(1, pos, i$7)); }
  2917. }
  2918. }
  2919. if (direction == "ltr") {
  2920. if (order[0].level == 1 && (m = str.match(/^\s+/))) {
  2921. order[0].from = m[0].length;
  2922. order.unshift(new BidiSpan(0, 0, m[0].length));
  2923. }
  2924. if (lst(order).level == 1 && (m = str.match(/\s+$/))) {
  2925. lst(order).to -= m[0].length;
  2926. order.push(new BidiSpan(0, len - m[0].length, len));
  2927. }
  2928. }
  2929. return direction == "rtl" ? order.reverse() : order
  2930. }
  2931. })();
  2932. // Get the bidi ordering for the given line (and cache it). Returns
  2933. // false for lines that are fully left-to-right, and an array of
  2934. // BidiSpan objects otherwise.
  2935. function getOrder(line, direction) {
  2936. var order = line.order;
  2937. if (order == null) { order = line.order = bidiOrdering(line.text, direction); }
  2938. return order
  2939. }
  2940. // EVENT HANDLING
  2941. // Lightweight event framework. on/off also work on DOM nodes,
  2942. // registering native DOM handlers.
  2943. var noHandlers = [];
  2944. var on = function(emitter, type, f) {
  2945. if (emitter.addEventListener) {
  2946. emitter.addEventListener(type, f, false);
  2947. } else if (emitter.attachEvent) {
  2948. emitter.attachEvent("on" + type, f);
  2949. } else {
  2950. var map$$1 = emitter._handlers || (emitter._handlers = {});
  2951. map$$1[type] = (map$$1[type] || noHandlers).concat(f);
  2952. }
  2953. };
  2954. function getHandlers(emitter, type) {
  2955. return emitter._handlers && emitter._handlers[type] || noHandlers
  2956. }
  2957. function off(emitter, type, f) {
  2958. if (emitter.removeEventListener) {
  2959. emitter.removeEventListener(type, f, false);
  2960. } else if (emitter.detachEvent) {
  2961. emitter.detachEvent("on" + type, f);
  2962. } else {
  2963. var map$$1 = emitter._handlers, arr = map$$1 && map$$1[type];
  2964. if (arr) {
  2965. var index = indexOf(arr, f);
  2966. if (index > -1)
  2967. { map$$1[type] = arr.slice(0, index).concat(arr.slice(index + 1)); }
  2968. }
  2969. }
  2970. }
  2971. function signal(emitter, type /*, values...*/) {
  2972. var handlers = getHandlers(emitter, type);
  2973. if (!handlers.length) { return }
  2974. var args = Array.prototype.slice.call(arguments, 2);
  2975. for (var i = 0; i < handlers.length; ++i) { handlers[i].apply(null, args); }
  2976. }
  2977. // The DOM events that CodeMirror handles can be overridden by
  2978. // registering a (non-DOM) handler on the editor for the event name,
  2979. // and preventDefault-ing the event in that handler.
  2980. function signalDOMEvent(cm, e, override) {
  2981. if (typeof e == "string")
  2982. { e = {type: e, preventDefault: function() { this.defaultPrevented = true; }}; }
  2983. signal(cm, override || e.type, cm, e);
  2984. return e_defaultPrevented(e) || e.codemirrorIgnore
  2985. }
  2986. function signalCursorActivity(cm) {
  2987. var arr = cm._handlers && cm._handlers.cursorActivity;
  2988. if (!arr) { return }
  2989. var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = []);
  2990. for (var i = 0; i < arr.length; ++i) { if (indexOf(set, arr[i]) == -1)
  2991. { set.push(arr[i]); } }
  2992. }
  2993. function hasHandler(emitter, type) {
  2994. return getHandlers(emitter, type).length > 0
  2995. }
  2996. // Add on and off methods to a constructor's prototype, to make
  2997. // registering events on such objects more convenient.
  2998. function eventMixin(ctor) {
  2999. ctor.prototype.on = function(type, f) {on(this, type, f);};
  3000. ctor.prototype.off = function(type, f) {off(this, type, f);};
  3001. }
  3002. // Due to the fact that we still support jurassic IE versions, some
  3003. // compatibility wrappers are needed.
  3004. function e_preventDefault(e) {
  3005. if (e.preventDefault) { e.preventDefault(); }
  3006. else { e.returnValue = false; }
  3007. }
  3008. function e_stopPropagation(e) {
  3009. if (e.stopPropagation) { e.stopPropagation(); }
  3010. else { e.cancelBubble = true; }
  3011. }
  3012. function e_defaultPrevented(e) {
  3013. return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false
  3014. }
  3015. function e_stop(e) {e_preventDefault(e); e_stopPropagation(e);}
  3016. function e_target(e) {return e.target || e.srcElement}
  3017. function e_button(e) {
  3018. var b = e.which;
  3019. if (b == null) {
  3020. if (e.button & 1) { b = 1; }
  3021. else if (e.button & 2) { b = 3; }
  3022. else if (e.button & 4) { b = 2; }
  3023. }
  3024. if (mac && e.ctrlKey && b == 1) { b = 3; }
  3025. return b
  3026. }
  3027. // Detect drag-and-drop
  3028. var dragAndDrop = function() {
  3029. // There is *some* kind of drag-and-drop support in IE6-8, but I
  3030. // couldn't get it to work yet.
  3031. if (ie && ie_version < 9) { return false }
  3032. var div = elt('div');
  3033. return "draggable" in div || "dragDrop" in div
  3034. }();
  3035. var zwspSupported;
  3036. function zeroWidthElement(measure) {
  3037. if (zwspSupported == null) {
  3038. var test = elt("span", "\u200b");
  3039. removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")]));
  3040. if (measure.firstChild.offsetHeight != 0)
  3041. { zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8); }
  3042. }
  3043. var node = zwspSupported ? elt("span", "\u200b") :
  3044. elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px");
  3045. node.setAttribute("cm-text", "");
  3046. return node
  3047. }
  3048. // Feature-detect IE's crummy client rect reporting for bidi text
  3049. var badBidiRects;
  3050. function hasBadBidiRects(measure) {
  3051. if (badBidiRects != null) { return badBidiRects }
  3052. var txt = removeChildrenAndAdd(measure, document.createTextNode("A\u062eA"));
  3053. var r0 = range(txt, 0, 1).getBoundingClientRect();
  3054. var r1 = range(txt, 1, 2).getBoundingClientRect();
  3055. removeChildren(measure);
  3056. if (!r0 || r0.left == r0.right) { return false } // Safari returns null in some cases (#2780)
  3057. return badBidiRects = (r1.right - r0.right < 3)
  3058. }
  3059. // See if "".split is the broken IE version, if so, provide an
  3060. // alternative way to split lines.
  3061. var splitLinesAuto = "\n\nb".split(/\n/).length != 3 ? function (string) {
  3062. var pos = 0, result = [], l = string.length;
  3063. while (pos <= l) {
  3064. var nl = string.indexOf("\n", pos);
  3065. if (nl == -1) { nl = string.length; }
  3066. var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl);
  3067. var rt = line.indexOf("\r");
  3068. if (rt != -1) {
  3069. result.push(line.slice(0, rt));
  3070. pos += rt + 1;
  3071. } else {
  3072. result.push(line);
  3073. pos = nl + 1;
  3074. }
  3075. }
  3076. return result
  3077. } : function (string) { return string.split(/\r\n?|\n/); };
  3078. var hasSelection = window.getSelection ? function (te) {
  3079. try { return te.selectionStart != te.selectionEnd }
  3080. catch(e) { return false }
  3081. } : function (te) {
  3082. var range$$1;
  3083. try {range$$1 = te.ownerDocument.selection.createRange();}
  3084. catch(e) {}
  3085. if (!range$$1 || range$$1.parentElement() != te) { return false }
  3086. return range$$1.compareEndPoints("StartToEnd", range$$1) != 0
  3087. };
  3088. var hasCopyEvent = (function () {
  3089. var e = elt("div");
  3090. if ("oncopy" in e) { return true }
  3091. e.setAttribute("oncopy", "return;");
  3092. return typeof e.oncopy == "function"
  3093. })();
  3094. var badZoomedRects = null;
  3095. function hasBadZoomedRects(measure) {
  3096. if (badZoomedRects != null) { return badZoomedRects }
  3097. var node = removeChildrenAndAdd(measure, elt("span", "x"));
  3098. var normal = node.getBoundingClientRect();
  3099. var fromRange = range(node, 0, 1).getBoundingClientRect();
  3100. return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1
  3101. }
  3102. // Known modes, by name and by MIME
  3103. var modes = {};
  3104. var mimeModes = {};
  3105. // Extra arguments are stored as the mode's dependencies, which is
  3106. // used by (legacy) mechanisms like loadmode.js to automatically
  3107. // load a mode. (Preferred mechanism is the require/define calls.)
  3108. function defineMode(name, mode) {
  3109. if (arguments.length > 2)
  3110. { mode.dependencies = Array.prototype.slice.call(arguments, 2); }
  3111. modes[name] = mode;
  3112. }
  3113. function defineMIME(mime, spec) {
  3114. mimeModes[mime] = spec;
  3115. }
  3116. // Given a MIME type, a {name, ...options} config object, or a name
  3117. // string, return a mode config object.
  3118. function resolveMode(spec) {
  3119. if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) {
  3120. spec = mimeModes[spec];
  3121. } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) {
  3122. var found = mimeModes[spec.name];
  3123. if (typeof found == "string") { found = {name: found}; }
  3124. spec = createObj(found, spec);
  3125. spec.name = found.name;
  3126. } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) {
  3127. return resolveMode("application/xml")
  3128. } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+json$/.test(spec)) {
  3129. return resolveMode("application/json")
  3130. }
  3131. if (typeof spec == "string") { return {name: spec} }
  3132. else { return spec || {name: "null"} }
  3133. }
  3134. // Given a mode spec (anything that resolveMode accepts), find and
  3135. // initialize an actual mode object.
  3136. function getMode(options, spec) {
  3137. spec = resolveMode(spec);
  3138. var mfactory = modes[spec.name];
  3139. if (!mfactory) { return getMode(options, "text/plain") }
  3140. var modeObj = mfactory(options, spec);
  3141. if (modeExtensions.hasOwnProperty(spec.name)) {
  3142. var exts = modeExtensions[spec.name];
  3143. for (var prop in exts) {
  3144. if (!exts.hasOwnProperty(prop)) { continue }
  3145. if (modeObj.hasOwnProperty(prop)) { modeObj["_" + prop] = modeObj[prop]; }
  3146. modeObj[prop] = exts[prop];
  3147. }
  3148. }
  3149. modeObj.name = spec.name;
  3150. if (spec.helperType) { modeObj.helperType = spec.helperType; }
  3151. if (spec.modeProps) { for (var prop$1 in spec.modeProps)
  3152. { modeObj[prop$1] = spec.modeProps[prop$1]; } }
  3153. return modeObj
  3154. }
  3155. // This can be used to attach properties to mode objects from
  3156. // outside the actual mode definition.
  3157. var modeExtensions = {};
  3158. function extendMode(mode, properties) {
  3159. var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {});
  3160. copyObj(properties, exts);
  3161. }
  3162. function copyState(mode, state) {
  3163. if (state === true) { return state }
  3164. if (mode.copyState) { return mode.copyState(state) }
  3165. var nstate = {};
  3166. for (var n in state) {
  3167. var val = state[n];
  3168. if (val instanceof Array) { val = val.concat([]); }
  3169. nstate[n] = val;
  3170. }
  3171. return nstate
  3172. }
  3173. // Given a mode and a state (for that mode), find the inner mode and
  3174. // state at the position that the state refers to.
  3175. function innerMode(mode, state) {
  3176. var info;
  3177. while (mode.innerMode) {
  3178. info = mode.innerMode(state);
  3179. if (!info || info.mode == mode) { break }
  3180. state = info.state;
  3181. mode = info.mode;
  3182. }
  3183. return info || {mode: mode, state: state}
  3184. }
  3185. function startState(mode, a1, a2) {
  3186. return mode.startState ? mode.startState(a1, a2) : true
  3187. }
  3188. // STRING STREAM
  3189. // Fed to the mode parsers, provides helper functions to make
  3190. // parsers more succinct.
  3191. var StringStream = function(string, tabSize, lineOracle) {
  3192. this.pos = this.start = 0;
  3193. this.string = string;
  3194. this.tabSize = tabSize || 8;
  3195. this.lastColumnPos = this.lastColumnValue = 0;
  3196. this.lineStart = 0;
  3197. this.lineOracle = lineOracle;
  3198. };
  3199. StringStream.prototype.eol = function () {return this.pos >= this.string.length};
  3200. StringStream.prototype.sol = function () {return this.pos == this.lineStart};
  3201. StringStream.prototype.peek = function () {return this.string.charAt(this.pos) || undefined};
  3202. StringStream.prototype.next = function () {
  3203. if (this.pos < this.string.length)
  3204. { return this.string.charAt(this.pos++) }
  3205. };
  3206. StringStream.prototype.eat = function (match) {
  3207. var ch = this.string.charAt(this.pos);
  3208. var ok;
  3209. if (typeof match == "string") { ok = ch == match; }
  3210. else { ok = ch && (match.test ? match.test(ch) : match(ch)); }
  3211. if (ok) {++this.pos; return ch}
  3212. };
  3213. StringStream.prototype.eatWhile = function (match) {
  3214. var start = this.pos;
  3215. while (this.eat(match)){}
  3216. return this.pos > start
  3217. };
  3218. StringStream.prototype.eatSpace = function () {
  3219. var this$1 = this;
  3220. var start = this.pos;
  3221. while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) { ++this$1.pos; }
  3222. return this.pos > start
  3223. };
  3224. StringStream.prototype.skipToEnd = function () {this.pos = this.string.length;};
  3225. StringStream.prototype.skipTo = function (ch) {
  3226. var found = this.string.indexOf(ch, this.pos);
  3227. if (found > -1) {this.pos = found; return true}
  3228. };
  3229. StringStream.prototype.backUp = function (n) {this.pos -= n;};
  3230. StringStream.prototype.column = function () {
  3231. if (this.lastColumnPos < this.start) {
  3232. this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue);
  3233. this.lastColumnPos = this.start;
  3234. }
  3235. return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0)
  3236. };
  3237. StringStream.prototype.indentation = function () {
  3238. return countColumn(this.string, null, this.tabSize) -
  3239. (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0)
  3240. };
  3241. StringStream.prototype.match = function (pattern, consume, caseInsensitive) {
  3242. if (typeof pattern == "string") {
  3243. var cased = function (str) { return caseInsensitive ? str.toLowerCase() : str; };
  3244. var substr = this.string.substr(this.pos, pattern.length);
  3245. if (cased(substr) == cased(pattern)) {
  3246. if (consume !== false) { this.pos += pattern.length; }
  3247. return true
  3248. }
  3249. } else {
  3250. var match = this.string.slice(this.pos).match(pattern);
  3251. if (match && match.index > 0) { return null }
  3252. if (match && consume !== false) { this.pos += match[0].length; }
  3253. return match
  3254. }
  3255. };
  3256. StringStream.prototype.current = function (){return this.string.slice(this.start, this.pos)};
  3257. StringStream.prototype.hideFirstChars = function (n, inner) {
  3258. this.lineStart += n;
  3259. try { return inner() }
  3260. finally { this.lineStart -= n; }
  3261. };
  3262. StringStream.prototype.lookAhead = function (n) {
  3263. var oracle = this.lineOracle;
  3264. return oracle && oracle.lookAhead(n)
  3265. };
  3266. StringStream.prototype.baseToken = function () {
  3267. var oracle = this.lineOracle;
  3268. return oracle && oracle.baseToken(this.pos)
  3269. };
  3270. var SavedContext = function(state, lookAhead) {
  3271. this.state = state;
  3272. this.lookAhead = lookAhead;
  3273. };
  3274. var Context = function(doc, state, line, lookAhead) {
  3275. this.state = state;
  3276. this.doc = doc;
  3277. this.line = line;
  3278. this.maxLookAhead = lookAhead || 0;
  3279. this.baseTokens = null;
  3280. this.baseTokenPos = 1;
  3281. };
  3282. Context.prototype.lookAhead = function (n) {
  3283. var line = this.doc.getLine(this.line + n);
  3284. if (line != null && n > this.maxLookAhead) { this.maxLookAhead = n; }
  3285. return line
  3286. };
  3287. Context.prototype.baseToken = function (n) {
  3288. var this$1 = this;
  3289. if (!this.baseTokens) { return null }
  3290. while (this.baseTokens[this.baseTokenPos] <= n)
  3291. { this$1.baseTokenPos += 2; }
  3292. var type = this.baseTokens[this.baseTokenPos + 1];
  3293. return {type: type && type.replace(/( |^)overlay .*/, ""),
  3294. size: this.baseTokens[this.baseTokenPos] - n}
  3295. };
  3296. Context.prototype.nextLine = function () {
  3297. this.line++;
  3298. if (this.maxLookAhead > 0) { this.maxLookAhead--; }
  3299. };
  3300. Context.fromSaved = function (doc, saved, line) {
  3301. if (saved instanceof SavedContext)
  3302. { return new Context(doc, copyState(doc.mode, saved.state), line, saved.lookAhead) }
  3303. else
  3304. { return new Context(doc, copyState(doc.mode, saved), line) }
  3305. };
  3306. Context.prototype.save = function (copy) {
  3307. var state = copy !== false ? copyState(this.doc.mode, this.state) : this.state;
  3308. return this.maxLookAhead > 0 ? new SavedContext(state, this.maxLookAhead) : state
  3309. };
  3310. // Compute a style array (an array starting with a mode generation
  3311. // -- for invalidation -- followed by pairs of end positions and
  3312. // style strings), which is used to highlight the tokens on the
  3313. // line.
  3314. function highlightLine(cm, line, context, forceToEnd) {
  3315. // A styles array always starts with a number identifying the
  3316. // mode/overlays that it is based on (for easy invalidation).
  3317. var st = [cm.state.modeGen], lineClasses = {};
  3318. // Compute the base array of styles
  3319. runMode(cm, line.text, cm.doc.mode, context, function (end, style) { return st.push(end, style); },
  3320. lineClasses, forceToEnd);
  3321. var state = context.state;
  3322. // Run overlays, adjust style array.
  3323. var loop = function ( o ) {
  3324. context.baseTokens = st;
  3325. var overlay = cm.state.overlays[o], i = 1, at = 0;
  3326. context.state = true;
  3327. runMode(cm, line.text, overlay.mode, context, function (end, style) {
  3328. var start = i;
  3329. // Ensure there's a token end at the current position, and that i points at it
  3330. while (at < end) {
  3331. var i_end = st[i];
  3332. if (i_end > end)
  3333. { st.splice(i, 1, end, st[i+1], i_end); }
  3334. i += 2;
  3335. at = Math.min(end, i_end);
  3336. }
  3337. if (!style) { return }
  3338. if (overlay.opaque) {
  3339. st.splice(start, i - start, end, "overlay " + style);
  3340. i = start + 2;
  3341. } else {
  3342. for (; start < i; start += 2) {
  3343. var cur = st[start+1];
  3344. st[start+1] = (cur ? cur + " " : "") + "overlay " + style;
  3345. }
  3346. }
  3347. }, lineClasses);
  3348. context.state = state;
  3349. context.baseTokens = null;
  3350. context.baseTokenPos = 1;
  3351. };
  3352. for (var o = 0; o < cm.state.overlays.length; ++o) loop( o );
  3353. return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null}
  3354. }
  3355. function getLineStyles(cm, line, updateFrontier) {
  3356. if (!line.styles || line.styles[0] != cm.state.modeGen) {
  3357. var context = getContextBefore(cm, lineNo(line));
  3358. var resetState = line.text.length > cm.options.maxHighlightLength && copyState(cm.doc.mode, context.state);
  3359. var result = highlightLine(cm, line, context);
  3360. if (resetState) { context.state = resetState; }
  3361. line.stateAfter = context.save(!resetState);
  3362. line.styles = result.styles;
  3363. if (result.classes) { line.styleClasses = result.classes; }
  3364. else if (line.styleClasses) { line.styleClasses = null; }
  3365. if (updateFrontier === cm.doc.highlightFrontier)
  3366. { cm.doc.modeFrontier = Math.max(cm.doc.modeFrontier, ++cm.doc.highlightFrontier); }
  3367. }
  3368. return line.styles
  3369. }
  3370. function getContextBefore(cm, n, precise) {
  3371. var doc = cm.doc, display = cm.display;
  3372. if (!doc.mode.startState) { return new Context(doc, true, n) }
  3373. var start = findStartLine(cm, n, precise);
  3374. var saved = start > doc.first && getLine(doc, start - 1).stateAfter;
  3375. var context = saved ? Context.fromSaved(doc, saved, start) : new Context(doc, startState(doc.mode), start);
  3376. doc.iter(start, n, function (line) {
  3377. processLine(cm, line.text, context);
  3378. var pos = context.line;
  3379. line.stateAfter = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo ? context.save() : null;
  3380. context.nextLine();
  3381. });
  3382. if (precise) { doc.modeFrontier = context.line; }
  3383. return context
  3384. }
  3385. // Lightweight form of highlight -- proceed over this line and
  3386. // update state, but don't save a style array. Used for lines that
  3387. // aren't currently visible.
  3388. function processLine(cm, text, context, startAt) {
  3389. var mode = cm.doc.mode;
  3390. var stream = new StringStream(text, cm.options.tabSize, context);
  3391. stream.start = stream.pos = startAt || 0;
  3392. if (text == "") { callBlankLine(mode, context.state); }
  3393. while (!stream.eol()) {
  3394. readToken(mode, stream, context.state);
  3395. stream.start = stream.pos;
  3396. }
  3397. }
  3398. function callBlankLine(mode, state) {
  3399. if (mode.blankLine) { return mode.blankLine(state) }
  3400. if (!mode.innerMode) { return }
  3401. var inner = innerMode(mode, state);
  3402. if (inner.mode.blankLine) { return inner.mode.blankLine(inner.state) }
  3403. }
  3404. function readToken(mode, stream, state, inner) {
  3405. for (var i = 0; i < 10; i++) {
  3406. if (inner) { inner[0] = innerMode(mode, state).mode; }
  3407. var style = mode.token(stream, state);
  3408. if (stream.pos > stream.start) { return style }
  3409. }
  3410. throw new Error("Mode " + mode.name + " failed to advance stream.")
  3411. }
  3412. var Token = function(stream, type, state) {
  3413. this.start = stream.start; this.end = stream.pos;
  3414. this.string = stream.current();
  3415. this.type = type || null;
  3416. this.state = state;
  3417. };
  3418. // Utility for getTokenAt and getLineTokens
  3419. function takeToken(cm, pos, precise, asArray) {
  3420. var doc = cm.doc, mode = doc.mode, style;
  3421. pos = clipPos(doc, pos);
  3422. var line = getLine(doc, pos.line), context = getContextBefore(cm, pos.line, precise);
  3423. var stream = new StringStream(line.text, cm.options.tabSize, context), tokens;
  3424. if (asArray) { tokens = []; }
  3425. while ((asArray || stream.pos < pos.ch) && !stream.eol()) {
  3426. stream.start = stream.pos;
  3427. style = readToken(mode, stream, context.state);
  3428. if (asArray) { tokens.push(new Token(stream, style, copyState(doc.mode, context.state))); }
  3429. }
  3430. return asArray ? tokens : new Token(stream, style, context.state)
  3431. }
  3432. function extractLineClasses(type, output) {
  3433. if (type) { for (;;) {
  3434. var lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/);
  3435. if (!lineClass) { break }
  3436. type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length);
  3437. var prop = lineClass[1] ? "bgClass" : "textClass";
  3438. if (output[prop] == null)
  3439. { output[prop] = lineClass[2]; }
  3440. else if (!(new RegExp("(?:^|\s)" + lineClass[2] + "(?:$|\s)")).test(output[prop]))
  3441. { output[prop] += " " + lineClass[2]; }
  3442. } }
  3443. return type
  3444. }
  3445. // Run the given mode's parser over a line, calling f for each token.
  3446. function runMode(cm, text, mode, context, f, lineClasses, forceToEnd) {
  3447. var flattenSpans = mode.flattenSpans;
  3448. if (flattenSpans == null) { flattenSpans = cm.options.flattenSpans; }
  3449. var curStart = 0, curStyle = null;
  3450. var stream = new StringStream(text, cm.options.tabSize, context), style;
  3451. var inner = cm.options.addModeClass && [null];
  3452. if (text == "") { extractLineClasses(callBlankLine(mode, context.state), lineClasses); }
  3453. while (!stream.eol()) {
  3454. if (stream.pos > cm.options.maxHighlightLength) {
  3455. flattenSpans = false;
  3456. if (forceToEnd) { processLine(cm, text, context, stream.pos); }
  3457. stream.pos = text.length;
  3458. style = null;
  3459. } else {
  3460. style = extractLineClasses(readToken(mode, stream, context.state, inner), lineClasses);
  3461. }
  3462. if (inner) {
  3463. var mName = inner[0].name;
  3464. if (mName) { style = "m-" + (style ? mName + " " + style : mName); }
  3465. }
  3466. if (!flattenSpans || curStyle != style) {
  3467. while (curStart < stream.start) {
  3468. curStart = Math.min(stream.start, curStart + 5000);
  3469. f(curStart, curStyle);
  3470. }
  3471. curStyle = style;
  3472. }
  3473. stream.start = stream.pos;
  3474. }
  3475. while (curStart < stream.pos) {
  3476. // Webkit seems to refuse to render text nodes longer than 57444
  3477. // characters, and returns inaccurate measurements in nodes
  3478. // starting around 5000 chars.
  3479. var pos = Math.min(stream.pos, curStart + 5000);
  3480. f(pos, curStyle);
  3481. curStart = pos;
  3482. }
  3483. }
  3484. // Finds the line to start with when starting a parse. Tries to
  3485. // find a line with a stateAfter, so that it can start with a
  3486. // valid state. If that fails, it returns the line with the
  3487. // smallest indentation, which tends to need the least context to
  3488. // parse correctly.
  3489. function findStartLine(cm, n, precise) {
  3490. var minindent, minline, doc = cm.doc;
  3491. var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100);
  3492. for (var search = n; search > lim; --search) {
  3493. if (search <= doc.first) { return doc.first }
  3494. var line = getLine(doc, search - 1), after = line.stateAfter;
  3495. if (after && (!precise || search + (after instanceof SavedContext ? after.lookAhead : 0) <= doc.modeFrontier))
  3496. { return search }
  3497. var indented = countColumn(line.text, null, cm.options.tabSize);
  3498. if (minline == null || minindent > indented) {
  3499. minline = search - 1;
  3500. minindent = indented;
  3501. }
  3502. }
  3503. return minline
  3504. }
  3505. function retreatFrontier(doc, n) {
  3506. doc.modeFrontier = Math.min(doc.modeFrontier, n);
  3507. if (doc.highlightFrontier < n - 10) { return }
  3508. var start = doc.first;
  3509. for (var line = n - 1; line > start; line--) {
  3510. var saved = getLine(doc, line).stateAfter;
  3511. // change is on 3
  3512. // state on line 1 looked ahead 2 -- so saw 3
  3513. // test 1 + 2 < 3 should cover this
  3514. if (saved && (!(saved instanceof SavedContext) || line + saved.lookAhead < n)) {
  3515. start = line + 1;
  3516. break
  3517. }
  3518. }
  3519. doc.highlightFrontier = Math.min(doc.highlightFrontier, start);
  3520. }
  3521. // LINE DATA STRUCTURE
  3522. // Line objects. These hold state related to a line, including
  3523. // highlighting info (the styles array).
  3524. var Line = function(text, markedSpans, estimateHeight) {
  3525. this.text = text;
  3526. attachMarkedSpans(this, markedSpans);
  3527. this.height = estimateHeight ? estimateHeight(this) : 1;
  3528. };
  3529. Line.prototype.lineNo = function () { return lineNo(this) };
  3530. eventMixin(Line);
  3531. // Change the content (text, markers) of a line. Automatically
  3532. // invalidates cached information and tries to re-estimate the
  3533. // line's height.
  3534. function updateLine(line, text, markedSpans, estimateHeight) {
  3535. line.text = text;
  3536. if (line.stateAfter) { line.stateAfter = null; }
  3537. if (line.styles) { line.styles = null; }
  3538. if (line.order != null) { line.order = null; }
  3539. detachMarkedSpans(line);
  3540. attachMarkedSpans(line, markedSpans);
  3541. var estHeight = estimateHeight ? estimateHeight(line) : 1;
  3542. if (estHeight != line.height) { updateLineHeight(line, estHeight); }
  3543. }
  3544. // Detach a line from the document tree and its markers.
  3545. function cleanUpLine(line) {
  3546. line.parent = null;
  3547. detachMarkedSpans(line);
  3548. }
  3549. // Convert a style as returned by a mode (either null, or a string
  3550. // containing one or more styles) to a CSS style. This is cached,
  3551. // and also looks for line-wide styles.
  3552. var styleToClassCache = {};
  3553. var styleToClassCacheWithMode = {};
  3554. function interpretTokenStyle(style, options) {
  3555. if (!style || /^\s*$/.test(style)) { return null }
  3556. var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache;
  3557. return cache[style] ||
  3558. (cache[style] = style.replace(/\S+/g, "cm-$&"))
  3559. }
  3560. // Render the DOM representation of the text of a line. Also builds
  3561. // up a 'line map', which points at the DOM nodes that represent
  3562. // specific stretches of text, and is used by the measuring code.
  3563. // The returned object contains the DOM node, this map, and
  3564. // information about line-wide styles that were set by the mode.
  3565. function buildLineContent(cm, lineView) {
  3566. // The padding-right forces the element to have a 'border', which
  3567. // is needed on Webkit to be able to get line-level bounding
  3568. // rectangles for it (in measureChar).
  3569. var content = eltP("span", null, null, webkit ? "padding-right: .1px" : null);
  3570. var builder = {pre: eltP("pre", [content], "CodeMirror-line"), content: content,
  3571. col: 0, pos: 0, cm: cm,
  3572. trailingSpace: false,
  3573. splitSpaces: (ie || webkit) && cm.getOption("lineWrapping")};
  3574. lineView.measure = {};
  3575. // Iterate over the logical lines that make up this visual line.
  3576. for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) {
  3577. var line = i ? lineView.rest[i - 1] : lineView.line, order = (void 0);
  3578. builder.pos = 0;
  3579. builder.addToken = buildToken;
  3580. // Optionally wire in some hacks into the token-rendering
  3581. // algorithm, to deal with browser quirks.
  3582. if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line, cm.doc.direction)))
  3583. { builder.addToken = buildTokenBadBidi(builder.addToken, order); }
  3584. builder.map = [];
  3585. var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line);
  3586. insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate));
  3587. if (line.styleClasses) {
  3588. if (line.styleClasses.bgClass)
  3589. { builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || ""); }
  3590. if (line.styleClasses.textClass)
  3591. { builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || ""); }
  3592. }
  3593. // Ensure at least a single node is present, for measuring.
  3594. if (builder.map.length == 0)
  3595. { builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure))); }
  3596. // Store the map and a cache object for the current logical line
  3597. if (i == 0) {
  3598. lineView.measure.map = builder.map;
  3599. lineView.measure.cache = {};
  3600. } else {
  3601. (lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map)
  3602. ;(lineView.measure.caches || (lineView.measure.caches = [])).push({});
  3603. }
  3604. }
  3605. // See issue #2901
  3606. if (webkit) {
  3607. var last = builder.content.lastChild;
  3608. if (/\bcm-tab\b/.test(last.className) || (last.querySelector && last.querySelector(".cm-tab")))
  3609. { builder.content.className = "cm-tab-wrap-hack"; }
  3610. }
  3611. signal(cm, "renderLine", cm, lineView.line, builder.pre);
  3612. if (builder.pre.className)
  3613. { builder.textClass = joinClasses(builder.pre.className, builder.textClass || ""); }
  3614. return builder
  3615. }
  3616. function defaultSpecialCharPlaceholder(ch) {
  3617. var token = elt("span", "\u2022", "cm-invalidchar");
  3618. token.title = "\\u" + ch.charCodeAt(0).toString(16);
  3619. token.setAttribute("aria-label", token.title);
  3620. return token
  3621. }
  3622. // Build up the DOM representation for a single token, and add it to
  3623. // the line map. Takes care to render special characters separately.
  3624. function buildToken(builder, text, style, startStyle, endStyle, title, css) {
  3625. if (!text) { return }
  3626. var displayText = builder.splitSpaces ? splitSpaces(text, builder.trailingSpace) : text;
  3627. var special = builder.cm.state.specialChars, mustWrap = false;
  3628. var content;
  3629. if (!special.test(text)) {
  3630. builder.col += text.length;
  3631. content = document.createTextNode(displayText);
  3632. builder.map.push(builder.pos, builder.pos + text.length, content);
  3633. if (ie && ie_version < 9) { mustWrap = true; }
  3634. builder.pos += text.length;
  3635. } else {
  3636. content = document.createDocumentFragment();
  3637. var pos = 0;
  3638. while (true) {
  3639. special.lastIndex = pos;
  3640. var m = special.exec(text);
  3641. var skipped = m ? m.index - pos : text.length - pos;
  3642. if (skipped) {
  3643. var txt = document.createTextNode(displayText.slice(pos, pos + skipped));
  3644. if (ie && ie_version < 9) { content.appendChild(elt("span", [txt])); }
  3645. else { content.appendChild(txt); }
  3646. builder.map.push(builder.pos, builder.pos + skipped, txt);
  3647. builder.col += skipped;
  3648. builder.pos += skipped;
  3649. }
  3650. if (!m) { break }
  3651. pos += skipped + 1;
  3652. var txt$1 = (void 0);
  3653. if (m[0] == "\t") {
  3654. var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize;
  3655. txt$1 = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab"));
  3656. txt$1.setAttribute("role", "presentation");
  3657. txt$1.setAttribute("cm-text", "\t");
  3658. builder.col += tabWidth;
  3659. } else if (m[0] == "\r" || m[0] == "\n") {
  3660. txt$1 = content.appendChild(elt("span", m[0] == "\r" ? "\u240d" : "\u2424", "cm-invalidchar"));
  3661. txt$1.setAttribute("cm-text", m[0]);
  3662. builder.col += 1;
  3663. } else {
  3664. txt$1 = builder.cm.options.specialCharPlaceholder(m[0]);
  3665. txt$1.setAttribute("cm-text", m[0]);
  3666. if (ie && ie_version < 9) { content.appendChild(elt("span", [txt$1])); }
  3667. else { content.appendChild(txt$1); }
  3668. builder.col += 1;
  3669. }
  3670. builder.map.push(builder.pos, builder.pos + 1, txt$1);
  3671. builder.pos++;
  3672. }
  3673. }
  3674. builder.trailingSpace = displayText.charCodeAt(text.length - 1) == 32;
  3675. if (style || startStyle || endStyle || mustWrap || css) {
  3676. var fullStyle = style || "";
  3677. if (startStyle) { fullStyle += startStyle; }
  3678. if (endStyle) { fullStyle += endStyle; }
  3679. var token = elt("span", [content], fullStyle, css);
  3680. if (title) { token.title = title; }
  3681. return builder.content.appendChild(token)
  3682. }
  3683. builder.content.appendChild(content);
  3684. }
  3685. function splitSpaces(text, trailingBefore) {
  3686. if (text.length > 1 && !/ /.test(text)) { return text }
  3687. var spaceBefore = trailingBefore, result = "";
  3688. for (var i = 0; i < text.length; i++) {
  3689. var ch = text.charAt(i);
  3690. if (ch == " " && spaceBefore && (i == text.length - 1 || text.charCodeAt(i + 1) == 32))
  3691. { ch = "\u00a0"; }
  3692. result += ch;
  3693. spaceBefore = ch == " ";
  3694. }
  3695. return result
  3696. }
  3697. // Work around nonsense dimensions being reported for stretches of
  3698. // right-to-left text.
  3699. function buildTokenBadBidi(inner, order) {
  3700. return function (builder, text, style, startStyle, endStyle, title, css) {
  3701. style = style ? style + " cm-force-border" : "cm-force-border";
  3702. var start = builder.pos, end = start + text.length;
  3703. for (;;) {
  3704. // Find the part that overlaps with the start of this text
  3705. var part = (void 0);
  3706. for (var i = 0; i < order.length; i++) {
  3707. part = order[i];
  3708. if (part.to > start && part.from <= start) { break }
  3709. }
  3710. if (part.to >= end) { return inner(builder, text, style, startStyle, endStyle, title, css) }
  3711. inner(builder, text.slice(0, part.to - start), style, startStyle, null, title, css);
  3712. startStyle = null;
  3713. text = text.slice(part.to - start);
  3714. start = part.to;
  3715. }
  3716. }
  3717. }
  3718. function buildCollapsedSpan(builder, size, marker, ignoreWidget) {
  3719. var widget = !ignoreWidget && marker.widgetNode;
  3720. if (widget) { builder.map.push(builder.pos, builder.pos + size, widget); }
  3721. if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) {
  3722. if (!widget)
  3723. { widget = builder.content.appendChild(document.createElement("span")); }
  3724. widget.setAttribute("cm-marker", marker.id);
  3725. }
  3726. if (widget) {
  3727. builder.cm.display.input.setUneditable(widget);
  3728. builder.content.appendChild(widget);
  3729. }
  3730. builder.pos += size;
  3731. builder.trailingSpace = false;
  3732. }
  3733. // Outputs a number of spans to make up a line, taking highlighting
  3734. // and marked text into account.
  3735. function insertLineContent(line, builder, styles) {
  3736. var spans = line.markedSpans, allText = line.text, at = 0;
  3737. if (!spans) {
  3738. for (var i$1 = 1; i$1 < styles.length; i$1+=2)
  3739. { builder.addToken(builder, allText.slice(at, at = styles[i$1]), interpretTokenStyle(styles[i$1+1], builder.cm.options)); }
  3740. return
  3741. }
  3742. var len = allText.length, pos = 0, i = 1, text = "", style, css;
  3743. var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, title, collapsed;
  3744. for (;;) {
  3745. if (nextChange == pos) { // Update current marker set
  3746. spanStyle = spanEndStyle = spanStartStyle = title = css = "";
  3747. collapsed = null; nextChange = Infinity;
  3748. var foundBookmarks = [], endStyles = (void 0);
  3749. for (var j = 0; j < spans.length; ++j) {
  3750. var sp = spans[j], m = sp.marker;
  3751. if (m.type == "bookmark" && sp.from == pos && m.widgetNode) {
  3752. foundBookmarks.push(m);
  3753. } else if (sp.from <= pos && (sp.to == null || sp.to > pos || m.collapsed && sp.to == pos && sp.from == pos)) {
  3754. if (sp.to != null && sp.to != pos && nextChange > sp.to) {
  3755. nextChange = sp.to;
  3756. spanEndStyle = "";
  3757. }
  3758. if (m.className) { spanStyle += " " + m.className; }
  3759. if (m.css) { css = (css ? css + ";" : "") + m.css; }
  3760. if (m.startStyle && sp.from == pos) { spanStartStyle += " " + m.startStyle; }
  3761. if (m.endStyle && sp.to == nextChange) { (endStyles || (endStyles = [])).push(m.endStyle, sp.to); }
  3762. if (m.title && !title) { title = m.title; }
  3763. if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0))
  3764. { collapsed = sp; }
  3765. } else if (sp.from > pos && nextChange > sp.from) {
  3766. nextChange = sp.from;
  3767. }
  3768. }
  3769. if (endStyles) { for (var j$1 = 0; j$1 < endStyles.length; j$1 += 2)
  3770. { if (endStyles[j$1 + 1] == nextChange) { spanEndStyle += " " + endStyles[j$1]; } } }
  3771. if (!collapsed || collapsed.from == pos) { for (var j$2 = 0; j$2 < foundBookmarks.length; ++j$2)
  3772. { buildCollapsedSpan(builder, 0, foundBookmarks[j$2]); } }
  3773. if (collapsed && (collapsed.from || 0) == pos) {
  3774. buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos,
  3775. collapsed.marker, collapsed.from == null);
  3776. if (collapsed.to == null) { return }
  3777. if (collapsed.to == pos) { collapsed = false; }
  3778. }
  3779. }
  3780. if (pos >= len) { break }
  3781. var upto = Math.min(len, nextChange);
  3782. while (true) {
  3783. if (text) {
  3784. var end = pos + text.length;
  3785. if (!collapsed) {
  3786. var tokenText = end > upto ? text.slice(0, upto - pos) : text;
  3787. builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle,
  3788. spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", title, css);
  3789. }
  3790. if (end >= upto) {text = text.slice(upto - pos); pos = upto; break}
  3791. pos = end;
  3792. spanStartStyle = "";
  3793. }
  3794. text = allText.slice(at, at = styles[i++]);
  3795. style = interpretTokenStyle(styles[i++], builder.cm.options);
  3796. }
  3797. }
  3798. }
  3799. // These objects are used to represent the visible (currently drawn)
  3800. // part of the document. A LineView may correspond to multiple
  3801. // logical lines, if those are connected by collapsed ranges.
  3802. function LineView(doc, line, lineN) {
  3803. // The starting line
  3804. this.line = line;
  3805. // Continuing lines, if any
  3806. this.rest = visualLineContinued(line);
  3807. // Number of logical lines in this visual line
  3808. this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1;
  3809. this.node = this.text = null;
  3810. this.hidden = lineIsHidden(doc, line);
  3811. }
  3812. // Create a range of LineView objects for the given lines.
  3813. function buildViewArray(cm, from, to) {
  3814. var array = [], nextPos;
  3815. for (var pos = from; pos < to; pos = nextPos) {
  3816. var view = new LineView(cm.doc, getLine(cm.doc, pos), pos);
  3817. nextPos = pos + view.size;
  3818. array.push(view);
  3819. }
  3820. return array
  3821. }
  3822. var operationGroup = null;
  3823. function pushOperation(op) {
  3824. if (operationGroup) {
  3825. operationGroup.ops.push(op);
  3826. } else {
  3827. op.ownsGroup = operationGroup = {
  3828. ops: [op],
  3829. delayedCallbacks: []
  3830. };
  3831. }
  3832. }
  3833. function fireCallbacksForOps(group) {
  3834. // Calls delayed callbacks and cursorActivity handlers until no
  3835. // new ones appear
  3836. var callbacks = group.delayedCallbacks, i = 0;
  3837. do {
  3838. for (; i < callbacks.length; i++)
  3839. { callbacks[i].call(null); }
  3840. for (var j = 0; j < group.ops.length; j++) {
  3841. var op = group.ops[j];
  3842. if (op.cursorActivityHandlers)
  3843. { while (op.cursorActivityCalled < op.cursorActivityHandlers.length)
  3844. { op.cursorActivityHandlers[op.cursorActivityCalled++].call(null, op.cm); } }
  3845. }
  3846. } while (i < callbacks.length)
  3847. }
  3848. function finishOperation(op, endCb) {
  3849. var group = op.ownsGroup;
  3850. if (!group) { return }
  3851. try { fireCallbacksForOps(group); }
  3852. finally {
  3853. operationGroup = null;
  3854. endCb(group);
  3855. }
  3856. }
  3857. var orphanDelayedCallbacks = null;
  3858. // Often, we want to signal events at a point where we are in the
  3859. // middle of some work, but don't want the handler to start calling
  3860. // other methods on the editor, which might be in an inconsistent
  3861. // state or simply not expect any other events to happen.
  3862. // signalLater looks whether there are any handlers, and schedules
  3863. // them to be executed when the last operation ends, or, if no
  3864. // operation is active, when a timeout fires.
  3865. function signalLater(emitter, type /*, values...*/) {
  3866. var arr = getHandlers(emitter, type);
  3867. if (!arr.length) { return }
  3868. var args = Array.prototype.slice.call(arguments, 2), list;
  3869. if (operationGroup) {
  3870. list = operationGroup.delayedCallbacks;
  3871. } else if (orphanDelayedCallbacks) {
  3872. list = orphanDelayedCallbacks;
  3873. } else {
  3874. list = orphanDelayedCallbacks = [];
  3875. setTimeout(fireOrphanDelayed, 0);
  3876. }
  3877. var loop = function ( i ) {
  3878. list.push(function () { return arr[i].apply(null, args); });
  3879. };
  3880. for (var i = 0; i < arr.length; ++i)
  3881. loop( i );
  3882. }
  3883. function fireOrphanDelayed() {
  3884. var delayed = orphanDelayedCallbacks;
  3885. orphanDelayedCallbacks = null;
  3886. for (var i = 0; i < delayed.length; ++i) { delayed[i](); }
  3887. }
  3888. // When an aspect of a line changes, a string is added to
  3889. // lineView.changes. This updates the relevant part of the line's
  3890. // DOM structure.
  3891. function updateLineForChanges(cm, lineView, lineN, dims) {
  3892. for (var j = 0; j < lineView.changes.length; j++) {
  3893. var type = lineView.changes[j];
  3894. if (type == "text") { updateLineText(cm, lineView); }
  3895. else if (type == "gutter") { updateLineGutter(cm, lineView, lineN, dims); }
  3896. else if (type == "class") { updateLineClasses(cm, lineView); }
  3897. else if (type == "widget") { updateLineWidgets(cm, lineView, dims); }
  3898. }
  3899. lineView.changes = null;
  3900. }
  3901. // Lines with gutter elements, widgets or a background class need to
  3902. // be wrapped, and have the extra elements added to the wrapper div
  3903. function ensureLineWrapped(lineView) {
  3904. if (lineView.node == lineView.text) {
  3905. lineView.node = elt("div", null, null, "position: relative");
  3906. if (lineView.text.parentNode)
  3907. { lineView.text.parentNode.replaceChild(lineView.node, lineView.text); }
  3908. lineView.node.appendChild(lineView.text);
  3909. if (ie && ie_version < 8) { lineView.node.style.zIndex = 2; }
  3910. }
  3911. return lineView.node
  3912. }
  3913. function updateLineBackground(cm, lineView) {
  3914. var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass;
  3915. if (cls) { cls += " CodeMirror-linebackground"; }
  3916. if (lineView.background) {
  3917. if (cls) { lineView.background.className = cls; }
  3918. else { lineView.background.parentNode.removeChild(lineView.background); lineView.background = null; }
  3919. } else if (cls) {
  3920. var wrap = ensureLineWrapped(lineView);
  3921. lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild);
  3922. cm.display.input.setUneditable(lineView.background);
  3923. }
  3924. }
  3925. // Wrapper around buildLineContent which will reuse the structure
  3926. // in display.externalMeasured when possible.
  3927. function getLineContent(cm, lineView) {
  3928. var ext = cm.display.externalMeasured;
  3929. if (ext && ext.line == lineView.line) {
  3930. cm.display.externalMeasured = null;
  3931. lineView.measure = ext.measure;
  3932. return ext.built
  3933. }
  3934. return buildLineContent(cm, lineView)
  3935. }
  3936. // Redraw the line's text. Interacts with the background and text
  3937. // classes because the mode may output tokens that influence these
  3938. // classes.
  3939. function updateLineText(cm, lineView) {
  3940. var cls = lineView.text.className;
  3941. var built = getLineContent(cm, lineView);
  3942. if (lineView.text == lineView.node) { lineView.node = built.pre; }
  3943. lineView.text.parentNode.replaceChild(built.pre, lineView.text);
  3944. lineView.text = built.pre;
  3945. if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) {
  3946. lineView.bgClass = built.bgClass;
  3947. lineView.textClass = built.textClass;
  3948. updateLineClasses(cm, lineView);
  3949. } else if (cls) {
  3950. lineView.text.className = cls;
  3951. }
  3952. }
  3953. function updateLineClasses(cm, lineView) {
  3954. updateLineBackground(cm, lineView);
  3955. if (lineView.line.wrapClass)
  3956. { ensureLineWrapped(lineView).className = lineView.line.wrapClass; }
  3957. else if (lineView.node != lineView.text)
  3958. { lineView.node.className = ""; }
  3959. var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass;
  3960. lineView.text.className = textClass || "";
  3961. }
  3962. function updateLineGutter(cm, lineView, lineN, dims) {
  3963. if (lineView.gutter) {
  3964. lineView.node.removeChild(lineView.gutter);
  3965. lineView.gutter = null;
  3966. }
  3967. if (lineView.gutterBackground) {
  3968. lineView.node.removeChild(lineView.gutterBackground);
  3969. lineView.gutterBackground = null;
  3970. }
  3971. if (lineView.line.gutterClass) {
  3972. var wrap = ensureLineWrapped(lineView);
  3973. lineView.gutterBackground = elt("div", null, "CodeMirror-gutter-background " + lineView.line.gutterClass,
  3974. ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px; width: " + (dims.gutterTotalWidth) + "px"));
  3975. cm.display.input.setUneditable(lineView.gutterBackground);
  3976. wrap.insertBefore(lineView.gutterBackground, lineView.text);
  3977. }
  3978. var markers = lineView.line.gutterMarkers;
  3979. if (cm.options.lineNumbers || markers) {
  3980. var wrap$1 = ensureLineWrapped(lineView);
  3981. var gutterWrap = lineView.gutter = elt("div", null, "CodeMirror-gutter-wrapper", ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px"));
  3982. cm.display.input.setUneditable(gutterWrap);
  3983. wrap$1.insertBefore(gutterWrap, lineView.text);
  3984. if (lineView.line.gutterClass)
  3985. { gutterWrap.className += " " + lineView.line.gutterClass; }
  3986. if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"]))
  3987. { lineView.lineNumber = gutterWrap.appendChild(
  3988. elt("div", lineNumberFor(cm.options, lineN),
  3989. "CodeMirror-linenumber CodeMirror-gutter-elt",
  3990. ("left: " + (dims.gutterLeft["CodeMirror-linenumbers"]) + "px; width: " + (cm.display.lineNumInnerWidth) + "px"))); }
  3991. if (markers) { for (var k = 0; k < cm.options.gutters.length; ++k) {
  3992. var id = cm.options.gutters[k], found = markers.hasOwnProperty(id) && markers[id];
  3993. if (found)
  3994. { gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt",
  3995. ("left: " + (dims.gutterLeft[id]) + "px; width: " + (dims.gutterWidth[id]) + "px"))); }
  3996. } }
  3997. }
  3998. }
  3999. function updateLineWidgets(cm, lineView, dims) {
  4000. if (lineView.alignable) { lineView.alignable = null; }
  4001. for (var node = lineView.node.firstChild, next = (void 0); node; node = next) {
  4002. next = node.nextSibling;
  4003. if (node.className == "CodeMirror-linewidget")
  4004. { lineView.node.removeChild(node); }
  4005. }
  4006. insertLineWidgets(cm, lineView, dims);
  4007. }
  4008. // Build a line's DOM representation from scratch
  4009. function buildLineElement(cm, lineView, lineN, dims) {
  4010. var built = getLineContent(cm, lineView);
  4011. lineView.text = lineView.node = built.pre;
  4012. if (built.bgClass) { lineView.bgClass = built.bgClass; }
  4013. if (built.textClass) { lineView.textClass = built.textClass; }
  4014. updateLineClasses(cm, lineView);
  4015. updateLineGutter(cm, lineView, lineN, dims);
  4016. insertLineWidgets(cm, lineView, dims);
  4017. return lineView.node
  4018. }
  4019. // A lineView may contain multiple logical lines (when merged by
  4020. // collapsed spans). The widgets for all of them need to be drawn.
  4021. function insertLineWidgets(cm, lineView, dims) {
  4022. insertLineWidgetsFor(cm, lineView.line, lineView, dims, true);
  4023. if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++)
  4024. { insertLineWidgetsFor(cm, lineView.rest[i], lineView, dims, false); } }
  4025. }
  4026. function insertLineWidgetsFor(cm, line, lineView, dims, allowAbove) {
  4027. if (!line.widgets) { return }
  4028. var wrap = ensureLineWrapped(lineView);
  4029. for (var i = 0, ws = line.widgets; i < ws.length; ++i) {
  4030. var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget");
  4031. if (!widget.handleMouseEvents) { node.setAttribute("cm-ignore-events", "true"); }
  4032. positionLineWidget(widget, node, lineView, dims);
  4033. cm.display.input.setUneditable(node);
  4034. if (allowAbove && widget.above)
  4035. { wrap.insertBefore(node, lineView.gutter || lineView.text); }
  4036. else
  4037. { wrap.appendChild(node); }
  4038. signalLater(widget, "redraw");
  4039. }
  4040. }
  4041. function positionLineWidget(widget, node, lineView, dims) {
  4042. if (widget.noHScroll) {
  4043. (lineView.alignable || (lineView.alignable = [])).push(node);
  4044. var width = dims.wrapperWidth;
  4045. node.style.left = dims.fixedPos + "px";
  4046. if (!widget.coverGutter) {
  4047. width -= dims.gutterTotalWidth;
  4048. node.style.paddingLeft = dims.gutterTotalWidth + "px";
  4049. }
  4050. node.style.width = width + "px";
  4051. }
  4052. if (widget.coverGutter) {
  4053. node.style.zIndex = 5;
  4054. node.style.position = "relative";
  4055. if (!widget.noHScroll) { node.style.marginLeft = -dims.gutterTotalWidth + "px"; }
  4056. }
  4057. }
  4058. function widgetHeight(widget) {
  4059. if (widget.height != null) { return widget.height }
  4060. var cm = widget.doc.cm;
  4061. if (!cm) { return 0 }
  4062. if (!contains(document.body, widget.node)) {
  4063. var parentStyle = "position: relative;";
  4064. if (widget.coverGutter)
  4065. { parentStyle += "margin-left: -" + cm.display.gutters.offsetWidth + "px;"; }
  4066. if (widget.noHScroll)
  4067. { parentStyle += "width: " + cm.display.wrapper.clientWidth + "px;"; }
  4068. removeChildrenAndAdd(cm.display.measure, elt("div", [widget.node], null, parentStyle));
  4069. }
  4070. return widget.height = widget.node.parentNode.offsetHeight
  4071. }
  4072. // Return true when the given mouse event happened in a widget
  4073. function eventInWidget(display, e) {
  4074. for (var n = e_target(e); n != display.wrapper; n = n.parentNode) {
  4075. if (!n || (n.nodeType == 1 && n.getAttribute("cm-ignore-events") == "true") ||
  4076. (n.parentNode == display.sizer && n != display.mover))
  4077. { return true }
  4078. }
  4079. }
  4080. // POSITION MEASUREMENT
  4081. function paddingTop(display) {return display.lineSpace.offsetTop}
  4082. function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight}
  4083. function paddingH(display) {
  4084. if (display.cachedPaddingH) { return display.cachedPaddingH }
  4085. var e = removeChildrenAndAdd(display.measure, elt("pre", "x"));
  4086. var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle;
  4087. var data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)};
  4088. if (!isNaN(data.left) && !isNaN(data.right)) { display.cachedPaddingH = data; }
  4089. return data
  4090. }
  4091. function scrollGap(cm) { return scrollerGap - cm.display.nativeBarWidth }
  4092. function displayWidth(cm) {
  4093. return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth
  4094. }
  4095. function displayHeight(cm) {
  4096. return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight
  4097. }
  4098. // Ensure the lineView.wrapping.heights array is populated. This is
  4099. // an array of bottom offsets for the lines that make up a drawn
  4100. // line. When lineWrapping is on, there might be more than one
  4101. // height.
  4102. function ensureLineHeights(cm, lineView, rect) {
  4103. var wrapping = cm.options.lineWrapping;
  4104. var curWidth = wrapping && displayWidth(cm);
  4105. if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) {
  4106. var heights = lineView.measure.heights = [];
  4107. if (wrapping) {
  4108. lineView.measure.width = curWidth;
  4109. var rects = lineView.text.firstChild.getClientRects();
  4110. for (var i = 0; i < rects.length - 1; i++) {
  4111. var cur = rects[i], next = rects[i + 1];
  4112. if (Math.abs(cur.bottom - next.bottom) > 2)
  4113. { heights.push((cur.bottom + next.top) / 2 - rect.top); }
  4114. }
  4115. }
  4116. heights.push(rect.bottom - rect.top);
  4117. }
  4118. }
  4119. // Find a line map (mapping character offsets to text nodes) and a
  4120. // measurement cache for the given line number. (A line view might
  4121. // contain multiple lines when collapsed ranges are present.)
  4122. function mapFromLineView(lineView, line, lineN) {
  4123. if (lineView.line == line)
  4124. { return {map: lineView.measure.map, cache: lineView.measure.cache} }
  4125. for (var i = 0; i < lineView.rest.length; i++)
  4126. { if (lineView.rest[i] == line)
  4127. { return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i]} } }
  4128. for (var i$1 = 0; i$1 < lineView.rest.length; i$1++)
  4129. { if (lineNo(lineView.rest[i$1]) > lineN)
  4130. { return {map: lineView.measure.maps[i$1], cache: lineView.measure.caches[i$1], before: true} } }
  4131. }
  4132. // Render a line into the hidden node display.externalMeasured. Used
  4133. // when measurement is needed for a line that's not in the viewport.
  4134. function updateExternalMeasurement(cm, line) {
  4135. line = visualLine(line);
  4136. var lineN = lineNo(line);
  4137. var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN);
  4138. view.lineN = lineN;
  4139. var built = view.built = buildLineContent(cm, view);
  4140. view.text = built.pre;
  4141. removeChildrenAndAdd(cm.display.lineMeasure, built.pre);
  4142. return view
  4143. }
  4144. // Get a {top, bottom, left, right} box (in line-local coordinates)
  4145. // for a given character.
  4146. function measureChar(cm, line, ch, bias) {
  4147. return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias)
  4148. }
  4149. // Find a line view that corresponds to the given line number.
  4150. function findViewForLine(cm, lineN) {
  4151. if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo)
  4152. { return cm.display.view[findViewIndex(cm, lineN)] }
  4153. var ext = cm.display.externalMeasured;
  4154. if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size)
  4155. { return ext }
  4156. }
  4157. // Measurement can be split in two steps, the set-up work that
  4158. // applies to the whole line, and the measurement of the actual
  4159. // character. Functions like coordsChar, that need to do a lot of
  4160. // measurements in a row, can thus ensure that the set-up work is
  4161. // only done once.
  4162. function prepareMeasureForLine(cm, line) {
  4163. var lineN = lineNo(line);
  4164. var view = findViewForLine(cm, lineN);
  4165. if (view && !view.text) {
  4166. view = null;
  4167. } else if (view && view.changes) {
  4168. updateLineForChanges(cm, view, lineN, getDimensions(cm));
  4169. cm.curOp.forceUpdate = true;
  4170. }
  4171. if (!view)
  4172. { view = updateExternalMeasurement(cm, line); }
  4173. var info = mapFromLineView(view, line, lineN);
  4174. return {
  4175. line: line, view: view, rect: null,
  4176. map: info.map, cache: info.cache, before: info.before,
  4177. hasHeights: false
  4178. }
  4179. }
  4180. // Given a prepared measurement object, measures the position of an
  4181. // actual character (or fetches it from the cache).
  4182. function measureCharPrepared(cm, prepared, ch, bias, varHeight) {
  4183. if (prepared.before) { ch = -1; }
  4184. var key = ch + (bias || ""), found;
  4185. if (prepared.cache.hasOwnProperty(key)) {
  4186. found = prepared.cache[key];
  4187. } else {
  4188. if (!prepared.rect)
  4189. { prepared.rect = prepared.view.text.getBoundingClientRect(); }
  4190. if (!prepared.hasHeights) {
  4191. ensureLineHeights(cm, prepared.view, prepared.rect);
  4192. prepared.hasHeights = true;
  4193. }
  4194. found = measureCharInner(cm, prepared, ch, bias);
  4195. if (!found.bogus) { prepared.cache[key] = found; }
  4196. }
  4197. return {left: found.left, right: found.right,
  4198. top: varHeight ? found.rtop : found.top,
  4199. bottom: varHeight ? found.rbottom : found.bottom}
  4200. }
  4201. var nullRect = {left: 0, right: 0, top: 0, bottom: 0};
  4202. function nodeAndOffsetInLineMap(map$$1, ch, bias) {
  4203. var node, start, end, collapse, mStart, mEnd;
  4204. // First, search the line map for the text node corresponding to,
  4205. // or closest to, the target character.
  4206. for (var i = 0; i < map$$1.length; i += 3) {
  4207. mStart = map$$1[i];
  4208. mEnd = map$$1[i + 1];
  4209. if (ch < mStart) {
  4210. start = 0; end = 1;
  4211. collapse = "left";
  4212. } else if (ch < mEnd) {
  4213. start = ch - mStart;
  4214. end = start + 1;
  4215. } else if (i == map$$1.length - 3 || ch == mEnd && map$$1[i + 3] > ch) {
  4216. end = mEnd - mStart;
  4217. start = end - 1;
  4218. if (ch >= mEnd) { collapse = "right"; }
  4219. }
  4220. if (start != null) {
  4221. node = map$$1[i + 2];
  4222. if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right"))
  4223. { collapse = bias; }
  4224. if (bias == "left" && start == 0)
  4225. { while (i && map$$1[i - 2] == map$$1[i - 3] && map$$1[i - 1].insertLeft) {
  4226. node = map$$1[(i -= 3) + 2];
  4227. collapse = "left";
  4228. } }
  4229. if (bias == "right" && start == mEnd - mStart)
  4230. { while (i < map$$1.length - 3 && map$$1[i + 3] == map$$1[i + 4] && !map$$1[i + 5].insertLeft) {
  4231. node = map$$1[(i += 3) + 2];
  4232. collapse = "right";
  4233. } }
  4234. break
  4235. }
  4236. }
  4237. return {node: node, start: start, end: end, collapse: collapse, coverStart: mStart, coverEnd: mEnd}
  4238. }
  4239. function getUsefulRect(rects, bias) {
  4240. var rect = nullRect;
  4241. if (bias == "left") { for (var i = 0; i < rects.length; i++) {
  4242. if ((rect = rects[i]).left != rect.right) { break }
  4243. } } else { for (var i$1 = rects.length - 1; i$1 >= 0; i$1--) {
  4244. if ((rect = rects[i$1]).left != rect.right) { break }
  4245. } }
  4246. return rect
  4247. }
  4248. function measureCharInner(cm, prepared, ch, bias) {
  4249. var place = nodeAndOffsetInLineMap(prepared.map, ch, bias);
  4250. var node = place.node, start = place.start, end = place.end, collapse = place.collapse;
  4251. var rect;
  4252. if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates.
  4253. for (var i$1 = 0; i$1 < 4; i$1++) { // Retry a maximum of 4 times when nonsense rectangles are returned
  4254. while (start && isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) { --start; }
  4255. while (place.coverStart + end < place.coverEnd && isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) { ++end; }
  4256. if (ie && ie_version < 9 && start == 0 && end == place.coverEnd - place.coverStart)
  4257. { rect = node.parentNode.getBoundingClientRect(); }
  4258. else
  4259. { rect = getUsefulRect(range(node, start, end).getClientRects(), bias); }
  4260. if (rect.left || rect.right || start == 0) { break }
  4261. end = start;
  4262. start = start - 1;
  4263. collapse = "right";
  4264. }
  4265. if (ie && ie_version < 11) { rect = maybeUpdateRectForZooming(cm.display.measure, rect); }
  4266. } else { // If it is a widget, simply get the box for the whole widget.
  4267. if (start > 0) { collapse = bias = "right"; }
  4268. var rects;
  4269. if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1)
  4270. { rect = rects[bias == "right" ? rects.length - 1 : 0]; }
  4271. else
  4272. { rect = node.getBoundingClientRect(); }
  4273. }
  4274. if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) {
  4275. var rSpan = node.parentNode.getClientRects()[0];
  4276. if (rSpan)
  4277. { rect = {left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom}; }
  4278. else
  4279. { rect = nullRect; }
  4280. }
  4281. var rtop = rect.top - prepared.rect.top, rbot = rect.bottom - prepared.rect.top;
  4282. var mid = (rtop + rbot) / 2;
  4283. var heights = prepared.view.measure.heights;
  4284. var i = 0;
  4285. for (; i < heights.length - 1; i++)
  4286. { if (mid < heights[i]) { break } }
  4287. var top = i ? heights[i - 1] : 0, bot = heights[i];
  4288. var result = {left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left,
  4289. right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left,
  4290. top: top, bottom: bot};
  4291. if (!rect.left && !rect.right) { result.bogus = true; }
  4292. if (!cm.options.singleCursorHeightPerLine) { result.rtop = rtop; result.rbottom = rbot; }
  4293. return result
  4294. }
  4295. // Work around problem with bounding client rects on ranges being
  4296. // returned incorrectly when zoomed on IE10 and below.
  4297. function maybeUpdateRectForZooming(measure, rect) {
  4298. if (!window.screen || screen.logicalXDPI == null ||
  4299. screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure))
  4300. { return rect }
  4301. var scaleX = screen.logicalXDPI / screen.deviceXDPI;
  4302. var scaleY = screen.logicalYDPI / screen.deviceYDPI;
  4303. return {left: rect.left * scaleX, right: rect.right * scaleX,
  4304. top: rect.top * scaleY, bottom: rect.bottom * scaleY}
  4305. }
  4306. function clearLineMeasurementCacheFor(lineView) {
  4307. if (lineView.measure) {
  4308. lineView.measure.cache = {};
  4309. lineView.measure.heights = null;
  4310. if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++)
  4311. { lineView.measure.caches[i] = {}; } }
  4312. }
  4313. }
  4314. function clearLineMeasurementCache(cm) {
  4315. cm.display.externalMeasure = null;
  4316. removeChildren(cm.display.lineMeasure);
  4317. for (var i = 0; i < cm.display.view.length; i++)
  4318. { clearLineMeasurementCacheFor(cm.display.view[i]); }
  4319. }
  4320. function clearCaches(cm) {
  4321. clearLineMeasurementCache(cm);
  4322. cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null;
  4323. if (!cm.options.lineWrapping) { cm.display.maxLineChanged = true; }
  4324. cm.display.lineNumChars = null;
  4325. }
  4326. function pageScrollX() {
  4327. // Work around https://bugs.chromium.org/p/chromium/issues/detail?id=489206
  4328. // which causes page_Offset and bounding client rects to use
  4329. // different reference viewports and invalidate our calculations.
  4330. if (chrome && android) { return -(document.body.getBoundingClientRect().left - parseInt(getComputedStyle(document.body).marginLeft)) }
  4331. return window.pageXOffset || (document.documentElement || document.body).scrollLeft
  4332. }
  4333. function pageScrollY() {
  4334. if (chrome && android) { return -(document.body.getBoundingClientRect().top - parseInt(getComputedStyle(document.body).marginTop)) }
  4335. return window.pageYOffset || (document.documentElement || document.body).scrollTop
  4336. }
  4337. function widgetTopHeight(lineObj) {
  4338. var height = 0;
  4339. if (lineObj.widgets) { for (var i = 0; i < lineObj.widgets.length; ++i) { if (lineObj.widgets[i].above)
  4340. { height += widgetHeight(lineObj.widgets[i]); } } }
  4341. return height
  4342. }
  4343. // Converts a {top, bottom, left, right} box from line-local
  4344. // coordinates into another coordinate system. Context may be one of
  4345. // "line", "div" (display.lineDiv), "local"./null (editor), "window",
  4346. // or "page".
  4347. function intoCoordSystem(cm, lineObj, rect, context, includeWidgets) {
  4348. if (!includeWidgets) {
  4349. var height = widgetTopHeight(lineObj);
  4350. rect.top += height; rect.bottom += height;
  4351. }
  4352. if (context == "line") { return rect }
  4353. if (!context) { context = "local"; }
  4354. var yOff = heightAtLine(lineObj);
  4355. if (context == "local") { yOff += paddingTop(cm.display); }
  4356. else { yOff -= cm.display.viewOffset; }
  4357. if (context == "page" || context == "window") {
  4358. var lOff = cm.display.lineSpace.getBoundingClientRect();
  4359. yOff += lOff.top + (context == "window" ? 0 : pageScrollY());
  4360. var xOff = lOff.left + (context == "window" ? 0 : pageScrollX());
  4361. rect.left += xOff; rect.right += xOff;
  4362. }
  4363. rect.top += yOff; rect.bottom += yOff;
  4364. return rect
  4365. }
  4366. // Coverts a box from "div" coords to another coordinate system.
  4367. // Context may be "window", "page", "div", or "local"./null.
  4368. function fromCoordSystem(cm, coords, context) {
  4369. if (context == "div") { return coords }
  4370. var left = coords.left, top = coords.top;
  4371. // First move into "page" coordinate system
  4372. if (context == "page") {
  4373. left -= pageScrollX();
  4374. top -= pageScrollY();
  4375. } else if (context == "local" || !context) {
  4376. var localBox = cm.display.sizer.getBoundingClientRect();
  4377. left += localBox.left;
  4378. top += localBox.top;
  4379. }
  4380. var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect();
  4381. return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top}
  4382. }
  4383. function charCoords(cm, pos, context, lineObj, bias) {
  4384. if (!lineObj) { lineObj = getLine(cm.doc, pos.line); }
  4385. return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context)
  4386. }
  4387. // Returns a box for a given cursor position, which may have an
  4388. // 'other' property containing the position of the secondary cursor
  4389. // on a bidi boundary.
  4390. // A cursor Pos(line, char, "before") is on the same visual line as `char - 1`
  4391. // and after `char - 1` in writing order of `char - 1`
  4392. // A cursor Pos(line, char, "after") is on the same visual line as `char`
  4393. // and before `char` in writing order of `char`
  4394. // Examples (upper-case letters are RTL, lower-case are LTR):
  4395. // Pos(0, 1, ...)
  4396. // before after
  4397. // ab a|b a|b
  4398. // aB a|B aB|
  4399. // Ab |Ab A|b
  4400. // AB B|A B|A
  4401. // Every position after the last character on a line is considered to stick
  4402. // to the last character on the line.
  4403. function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) {
  4404. lineObj = lineObj || getLine(cm.doc, pos.line);
  4405. if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj); }
  4406. function get(ch, right) {
  4407. var m = measureCharPrepared(cm, preparedMeasure, ch, right ? "right" : "left", varHeight);
  4408. if (right) { m.left = m.right; } else { m.right = m.left; }
  4409. return intoCoordSystem(cm, lineObj, m, context)
  4410. }
  4411. var order = getOrder(lineObj, cm.doc.direction), ch = pos.ch, sticky = pos.sticky;
  4412. if (ch >= lineObj.text.length) {
  4413. ch = lineObj.text.length;
  4414. sticky = "before";
  4415. } else if (ch <= 0) {
  4416. ch = 0;
  4417. sticky = "after";
  4418. }
  4419. if (!order) { return get(sticky == "before" ? ch - 1 : ch, sticky == "before") }
  4420. function getBidi(ch, partPos, invert) {
  4421. var part = order[partPos], right = part.level == 1;
  4422. return get(invert ? ch - 1 : ch, right != invert)
  4423. }
  4424. var partPos = getBidiPartAt(order, ch, sticky);
  4425. var other = bidiOther;
  4426. var val = getBidi(ch, partPos, sticky == "before");
  4427. if (other != null) { val.other = getBidi(ch, other, sticky != "before"); }
  4428. return val
  4429. }
  4430. // Used to cheaply estimate the coordinates for a position. Used for
  4431. // intermediate scroll updates.
  4432. function estimateCoords(cm, pos) {
  4433. var left = 0;
  4434. pos = clipPos(cm.doc, pos);
  4435. if (!cm.options.lineWrapping) { left = charWidth(cm.display) * pos.ch; }
  4436. var lineObj = getLine(cm.doc, pos.line);
  4437. var top = heightAtLine(lineObj) + paddingTop(cm.display);
  4438. return {left: left, right: left, top: top, bottom: top + lineObj.height}
  4439. }
  4440. // Positions returned by coordsChar contain some extra information.
  4441. // xRel is the relative x position of the input coordinates compared
  4442. // to the found position (so xRel > 0 means the coordinates are to
  4443. // the right of the character position, for example). When outside
  4444. // is true, that means the coordinates lie outside the line's
  4445. // vertical range.
  4446. function PosWithInfo(line, ch, sticky, outside, xRel) {
  4447. var pos = Pos(line, ch, sticky);
  4448. pos.xRel = xRel;
  4449. if (outside) { pos.outside = true; }
  4450. return pos
  4451. }
  4452. // Compute the character position closest to the given coordinates.
  4453. // Input must be lineSpace-local ("div" coordinate system).
  4454. function coordsChar(cm, x, y) {
  4455. var doc = cm.doc;
  4456. y += cm.display.viewOffset;
  4457. if (y < 0) { return PosWithInfo(doc.first, 0, null, true, -1) }
  4458. var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1;
  4459. if (lineN > last)
  4460. { return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, null, true, 1) }
  4461. if (x < 0) { x = 0; }
  4462. var lineObj = getLine(doc, lineN);
  4463. for (;;) {
  4464. var found = coordsCharInner(cm, lineObj, lineN, x, y);
  4465. var merged = collapsedSpanAtEnd(lineObj);
  4466. var mergedPos = merged && merged.find(0, true);
  4467. if (merged && (found.ch > mergedPos.from.ch || found.ch == mergedPos.from.ch && found.xRel > 0))
  4468. { lineN = lineNo(lineObj = mergedPos.to.line); }
  4469. else
  4470. { return found }
  4471. }
  4472. }
  4473. function wrappedLineExtent(cm, lineObj, preparedMeasure, y) {
  4474. y -= widgetTopHeight(lineObj);
  4475. var end = lineObj.text.length;
  4476. var begin = findFirst(function (ch) { return measureCharPrepared(cm, preparedMeasure, ch - 1).bottom <= y; }, end, 0);
  4477. end = findFirst(function (ch) { return measureCharPrepared(cm, preparedMeasure, ch).top > y; }, begin, end);
  4478. return {begin: begin, end: end}
  4479. }
  4480. function wrappedLineExtentChar(cm, lineObj, preparedMeasure, target) {
  4481. if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj); }
  4482. var targetTop = intoCoordSystem(cm, lineObj, measureCharPrepared(cm, preparedMeasure, target), "line").top;
  4483. return wrappedLineExtent(cm, lineObj, preparedMeasure, targetTop)
  4484. }
  4485. // Returns true if the given side of a box is after the given
  4486. // coordinates, in top-to-bottom, left-to-right order.
  4487. function boxIsAfter(box, x, y, left) {
  4488. return box.bottom <= y ? false : box.top > y ? true : (left ? box.left : box.right) > x
  4489. }
  4490. function coordsCharInner(cm, lineObj, lineNo$$1, x, y) {
  4491. // Move y into line-local coordinate space
  4492. y -= heightAtLine(lineObj);
  4493. var preparedMeasure = prepareMeasureForLine(cm, lineObj);
  4494. // When directly calling `measureCharPrepared`, we have to adjust
  4495. // for the widgets at this line.
  4496. var widgetHeight$$1 = widgetTopHeight(lineObj);
  4497. var begin = 0, end = lineObj.text.length, ltr = true;
  4498. var order = getOrder(lineObj, cm.doc.direction);
  4499. // If the line isn't plain left-to-right text, first figure out
  4500. // which bidi section the coordinates fall into.
  4501. if (order) {
  4502. var part = (cm.options.lineWrapping ? coordsBidiPartWrapped : coordsBidiPart)
  4503. (cm, lineObj, lineNo$$1, preparedMeasure, order, x, y);
  4504. ltr = part.level != 1;
  4505. // The awkward -1 offsets are needed because findFirst (called
  4506. // on these below) will treat its first bound as inclusive,
  4507. // second as exclusive, but we want to actually address the
  4508. // characters in the part's range
  4509. begin = ltr ? part.from : part.to - 1;
  4510. end = ltr ? part.to : part.from - 1;
  4511. }
  4512. // A binary search to find the first character whose bounding box
  4513. // starts after the coordinates. If we run across any whose box wrap
  4514. // the coordinates, store that.
  4515. var chAround = null, boxAround = null;
  4516. var ch = findFirst(function (ch) {
  4517. var box = measureCharPrepared(cm, preparedMeasure, ch);
  4518. box.top += widgetHeight$$1; box.bottom += widgetHeight$$1;
  4519. if (!boxIsAfter(box, x, y, false)) { return false }
  4520. if (box.top <= y && box.left <= x) {
  4521. chAround = ch;
  4522. boxAround = box;
  4523. }
  4524. return true
  4525. }, begin, end);
  4526. var baseX, sticky, outside = false;
  4527. // If a box around the coordinates was found, use that
  4528. if (boxAround) {
  4529. // Distinguish coordinates nearer to the left or right side of the box
  4530. var atLeft = x - boxAround.left < boxAround.right - x, atStart = atLeft == ltr;
  4531. ch = chAround + (atStart ? 0 : 1);
  4532. sticky = atStart ? "after" : "before";
  4533. baseX = atLeft ? boxAround.left : boxAround.right;
  4534. } else {
  4535. // (Adjust for extended bound, if necessary.)
  4536. if (!ltr && (ch == end || ch == begin)) { ch++; }
  4537. // To determine which side to associate with, get the box to the
  4538. // left of the character and compare it's vertical position to the
  4539. // coordinates
  4540. sticky = ch == 0 ? "after" : ch == lineObj.text.length ? "before" :
  4541. (measureCharPrepared(cm, preparedMeasure, ch - (ltr ? 1 : 0)).bottom + widgetHeight$$1 <= y) == ltr ?
  4542. "after" : "before";
  4543. // Now get accurate coordinates for this place, in order to get a
  4544. // base X position
  4545. var coords = cursorCoords(cm, Pos(lineNo$$1, ch, sticky), "line", lineObj, preparedMeasure);
  4546. baseX = coords.left;
  4547. outside = y < coords.top || y >= coords.bottom;
  4548. }
  4549. ch = skipExtendingChars(lineObj.text, ch, 1);
  4550. return PosWithInfo(lineNo$$1, ch, sticky, outside, x - baseX)
  4551. }
  4552. function coordsBidiPart(cm, lineObj, lineNo$$1, preparedMeasure, order, x, y) {
  4553. // Bidi parts are sorted left-to-right, and in a non-line-wrapping
  4554. // situation, we can take this ordering to correspond to the visual
  4555. // ordering. This finds the first part whose end is after the given
  4556. // coordinates.
  4557. var index = findFirst(function (i) {
  4558. var part = order[i], ltr = part.level != 1;
  4559. return boxIsAfter(cursorCoords(cm, Pos(lineNo$$1, ltr ? part.to : part.from, ltr ? "before" : "after"),
  4560. "line", lineObj, preparedMeasure), x, y, true)
  4561. }, 0, order.length - 1);
  4562. var part = order[index];
  4563. // If this isn't the first part, the part's start is also after
  4564. // the coordinates, and the coordinates aren't on the same line as
  4565. // that start, move one part back.
  4566. if (index > 0) {
  4567. var ltr = part.level != 1;
  4568. var start = cursorCoords(cm, Pos(lineNo$$1, ltr ? part.from : part.to, ltr ? "after" : "before"),
  4569. "line", lineObj, preparedMeasure);
  4570. if (boxIsAfter(start, x, y, true) && start.top > y)
  4571. { part = order[index - 1]; }
  4572. }
  4573. return part
  4574. }
  4575. function coordsBidiPartWrapped(cm, lineObj, _lineNo, preparedMeasure, order, x, y) {
  4576. // In a wrapped line, rtl text on wrapping boundaries can do things
  4577. // that don't correspond to the ordering in our `order` array at
  4578. // all, so a binary search doesn't work, and we want to return a
  4579. // part that only spans one line so that the binary search in
  4580. // coordsCharInner is safe. As such, we first find the extent of the
  4581. // wrapped line, and then do a flat search in which we discard any
  4582. // spans that aren't on the line.
  4583. var ref = wrappedLineExtent(cm, lineObj, preparedMeasure, y);
  4584. var begin = ref.begin;
  4585. var end = ref.end;
  4586. if (/\s/.test(lineObj.text.charAt(end - 1))) { end--; }
  4587. var part = null, closestDist = null;
  4588. for (var i = 0; i < order.length; i++) {
  4589. var p = order[i];
  4590. if (p.from >= end || p.to <= begin) { continue }
  4591. var ltr = p.level != 1;
  4592. var endX = measureCharPrepared(cm, preparedMeasure, ltr ? Math.min(end, p.to) - 1 : Math.max(begin, p.from)).right;
  4593. // Weigh against spans ending before this, so that they are only
  4594. // picked if nothing ends after
  4595. var dist = endX < x ? x - endX + 1e9 : endX - x;
  4596. if (!part || closestDist > dist) {
  4597. part = p;
  4598. closestDist = dist;
  4599. }
  4600. }
  4601. if (!part) { part = order[order.length - 1]; }
  4602. // Clip the part to the wrapped line.
  4603. if (part.from < begin) { part = {from: begin, to: part.to, level: part.level}; }
  4604. if (part.to > end) { part = {from: part.from, to: end, level: part.level}; }
  4605. return part
  4606. }
  4607. var measureText;
  4608. // Compute the default text height.
  4609. function textHeight(display) {
  4610. if (display.cachedTextHeight != null) { return display.cachedTextHeight }
  4611. if (measureText == null) {
  4612. measureText = elt("pre");
  4613. // Measure a bunch of lines, for browsers that compute
  4614. // fractional heights.
  4615. for (var i = 0; i < 49; ++i) {
  4616. measureText.appendChild(document.createTextNode("x"));
  4617. measureText.appendChild(elt("br"));
  4618. }
  4619. measureText.appendChild(document.createTextNode("x"));
  4620. }
  4621. removeChildrenAndAdd(display.measure, measureText);
  4622. var height = measureText.offsetHeight / 50;
  4623. if (height > 3) { display.cachedTextHeight = height; }
  4624. removeChildren(display.measure);
  4625. return height || 1
  4626. }
  4627. // Compute the default character width.
  4628. function charWidth(display) {
  4629. if (display.cachedCharWidth != null) { return display.cachedCharWidth }
  4630. var anchor = elt("span", "xxxxxxxxxx");
  4631. var pre = elt("pre", [anchor]);
  4632. removeChildrenAndAdd(display.measure, pre);
  4633. var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10;
  4634. if (width > 2) { display.cachedCharWidth = width; }
  4635. return width || 10
  4636. }
  4637. // Do a bulk-read of the DOM positions and sizes needed to draw the
  4638. // view, so that we don't interleave reading and writing to the DOM.
  4639. function getDimensions(cm) {
  4640. var d = cm.display, left = {}, width = {};
  4641. var gutterLeft = d.gutters.clientLeft;
  4642. for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) {
  4643. left[cm.options.gutters[i]] = n.offsetLeft + n.clientLeft + gutterLeft;
  4644. width[cm.options.gutters[i]] = n.clientWidth;
  4645. }
  4646. return {fixedPos: compensateForHScroll(d),
  4647. gutterTotalWidth: d.gutters.offsetWidth,
  4648. gutterLeft: left,
  4649. gutterWidth: width,
  4650. wrapperWidth: d.wrapper.clientWidth}
  4651. }
  4652. // Computes display.scroller.scrollLeft + display.gutters.offsetWidth,
  4653. // but using getBoundingClientRect to get a sub-pixel-accurate
  4654. // result.
  4655. function compensateForHScroll(display) {
  4656. return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left
  4657. }
  4658. // Returns a function that estimates the height of a line, to use as
  4659. // first approximation until the line becomes visible (and is thus
  4660. // properly measurable).
  4661. function estimateHeight(cm) {
  4662. var th = textHeight(cm.display), wrapping = cm.options.lineWrapping;
  4663. var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3);
  4664. return function (line) {
  4665. if (lineIsHidden(cm.doc, line)) { return 0 }
  4666. var widgetsHeight = 0;
  4667. if (line.widgets) { for (var i = 0; i < line.widgets.length; i++) {
  4668. if (line.widgets[i].height) { widgetsHeight += line.widgets[i].height; }
  4669. } }
  4670. if (wrapping)
  4671. { return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th }
  4672. else
  4673. { return widgetsHeight + th }
  4674. }
  4675. }
  4676. function estimateLineHeights(cm) {
  4677. var doc = cm.doc, est = estimateHeight(cm);
  4678. doc.iter(function (line) {
  4679. var estHeight = est(line);
  4680. if (estHeight != line.height) { updateLineHeight(line, estHeight); }
  4681. });
  4682. }
  4683. // Given a mouse event, find the corresponding position. If liberal
  4684. // is false, it checks whether a gutter or scrollbar was clicked,
  4685. // and returns null if it was. forRect is used by rectangular
  4686. // selections, and tries to estimate a character position even for
  4687. // coordinates beyond the right of the text.
  4688. function posFromMouse(cm, e, liberal, forRect) {
  4689. var display = cm.display;
  4690. if (!liberal && e_target(e).getAttribute("cm-not-content") == "true") { return null }
  4691. var x, y, space = display.lineSpace.getBoundingClientRect();
  4692. // Fails unpredictably on IE[67] when mouse is dragged around quickly.
  4693. try { x = e.clientX - space.left; y = e.clientY - space.top; }
  4694. catch (e) { return null }
  4695. var coords = coordsChar(cm, x, y), line;
  4696. if (forRect && coords.xRel == 1 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) {
  4697. var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length;
  4698. coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff));
  4699. }
  4700. return coords
  4701. }
  4702. // Find the view element corresponding to a given line. Return null
  4703. // when the line isn't visible.
  4704. function findViewIndex(cm, n) {
  4705. if (n >= cm.display.viewTo) { return null }
  4706. n -= cm.display.viewFrom;
  4707. if (n < 0) { return null }
  4708. var view = cm.display.view;
  4709. for (var i = 0; i < view.length; i++) {
  4710. n -= view[i].size;
  4711. if (n < 0) { return i }
  4712. }
  4713. }
  4714. function updateSelection(cm) {
  4715. cm.display.input.showSelection(cm.display.input.prepareSelection());
  4716. }
  4717. function prepareSelection(cm, primary) {
  4718. if ( primary === void 0 ) primary = true;
  4719. var doc = cm.doc, result = {};
  4720. var curFragment = result.cursors = document.createDocumentFragment();
  4721. var selFragment = result.selection = document.createDocumentFragment();
  4722. for (var i = 0; i < doc.sel.ranges.length; i++) {
  4723. if (!primary && i == doc.sel.primIndex) { continue }
  4724. var range$$1 = doc.sel.ranges[i];
  4725. if (range$$1.from().line >= cm.display.viewTo || range$$1.to().line < cm.display.viewFrom) { continue }
  4726. var collapsed = range$$1.empty();
  4727. if (collapsed || cm.options.showCursorWhenSelecting)
  4728. { drawSelectionCursor(cm, range$$1.head, curFragment); }
  4729. if (!collapsed)
  4730. { drawSelectionRange(cm, range$$1, selFragment); }
  4731. }
  4732. return result
  4733. }
  4734. // Draws a cursor for the given range
  4735. function drawSelectionCursor(cm, head, output) {
  4736. var pos = cursorCoords(cm, head, "div", null, null, !cm.options.singleCursorHeightPerLine);
  4737. var cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor"));
  4738. cursor.style.left = pos.left + "px";
  4739. cursor.style.top = pos.top + "px";
  4740. cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px";
  4741. if (pos.other) {
  4742. // Secondary cursor, shown when on a 'jump' in bi-directional text
  4743. var otherCursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor"));
  4744. otherCursor.style.display = "";
  4745. otherCursor.style.left = pos.other.left + "px";
  4746. otherCursor.style.top = pos.other.top + "px";
  4747. otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px";
  4748. }
  4749. }
  4750. function cmpCoords(a, b) { return a.top - b.top || a.left - b.left }
  4751. // Draws the given range as a highlighted selection
  4752. function drawSelectionRange(cm, range$$1, output) {
  4753. var display = cm.display, doc = cm.doc;
  4754. var fragment = document.createDocumentFragment();
  4755. var padding = paddingH(cm.display), leftSide = padding.left;
  4756. var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right;
  4757. var docLTR = doc.direction == "ltr";
  4758. function add(left, top, width, bottom) {
  4759. if (top < 0) { top = 0; }
  4760. top = Math.round(top);
  4761. bottom = Math.round(bottom);
  4762. 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")));
  4763. }
  4764. function drawForLine(line, fromArg, toArg) {
  4765. var lineObj = getLine(doc, line);
  4766. var lineLen = lineObj.text.length;
  4767. var start, end;
  4768. function coords(ch, bias) {
  4769. return charCoords(cm, Pos(line, ch), "div", lineObj, bias)
  4770. }
  4771. function wrapX(pos, dir, side) {
  4772. var extent = wrappedLineExtentChar(cm, lineObj, null, pos);
  4773. var prop = (dir == "ltr") == (side == "after") ? "left" : "right";
  4774. var ch = side == "after" ? extent.begin : extent.end - (/\s/.test(lineObj.text.charAt(extent.end - 1)) ? 2 : 1);
  4775. return coords(ch, prop)[prop]
  4776. }
  4777. var order = getOrder(lineObj, doc.direction);
  4778. iterateBidiSections(order, fromArg || 0, toArg == null ? lineLen : toArg, function (from, to, dir, i) {
  4779. var ltr = dir == "ltr";
  4780. var fromPos = coords(from, ltr ? "left" : "right");
  4781. var toPos = coords(to - 1, ltr ? "right" : "left");
  4782. var openStart = fromArg == null && from == 0, openEnd = toArg == null && to == lineLen;
  4783. var first = i == 0, last = !order || i == order.length - 1;
  4784. if (toPos.top - fromPos.top <= 3) { // Single line
  4785. var openLeft = (docLTR ? openStart : openEnd) && first;
  4786. var openRight = (docLTR ? openEnd : openStart) && last;
  4787. var left = openLeft ? leftSide : (ltr ? fromPos : toPos).left;
  4788. var right = openRight ? rightSide : (ltr ? toPos : fromPos).right;
  4789. add(left, fromPos.top, right - left, fromPos.bottom);
  4790. } else { // Multiple lines
  4791. var topLeft, topRight, botLeft, botRight;
  4792. if (ltr) {
  4793. topLeft = docLTR && openStart && first ? leftSide : fromPos.left;
  4794. topRight = docLTR ? rightSide : wrapX(from, dir, "before");
  4795. botLeft = docLTR ? leftSide : wrapX(to, dir, "after");
  4796. botRight = docLTR && openEnd && last ? rightSide : toPos.right;
  4797. } else {
  4798. topLeft = !docLTR ? leftSide : wrapX(from, dir, "before");
  4799. topRight = !docLTR && openStart && first ? rightSide : fromPos.right;
  4800. botLeft = !docLTR && openEnd && last ? leftSide : toPos.left;
  4801. botRight = !docLTR ? rightSide : wrapX(to, dir, "after");
  4802. }
  4803. add(topLeft, fromPos.top, topRight - topLeft, fromPos.bottom);
  4804. if (fromPos.bottom < toPos.top) { add(leftSide, fromPos.bottom, null, toPos.top); }
  4805. add(botLeft, toPos.top, botRight - botLeft, toPos.bottom);
  4806. }
  4807. if (!start || cmpCoords(fromPos, start) < 0) { start = fromPos; }
  4808. if (cmpCoords(toPos, start) < 0) { start = toPos; }
  4809. if (!end || cmpCoords(fromPos, end) < 0) { end = fromPos; }
  4810. if (cmpCoords(toPos, end) < 0) { end = toPos; }
  4811. });
  4812. return {start: start, end: end}
  4813. }
  4814. var sFrom = range$$1.from(), sTo = range$$1.to();
  4815. if (sFrom.line == sTo.line) {
  4816. drawForLine(sFrom.line, sFrom.ch, sTo.ch);
  4817. } else {
  4818. var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line);
  4819. var singleVLine = visualLine(fromLine) == visualLine(toLine);
  4820. var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end;
  4821. var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start;
  4822. if (singleVLine) {
  4823. if (leftEnd.top < rightStart.top - 2) {
  4824. add(leftEnd.right, leftEnd.top, null, leftEnd.bottom);
  4825. add(leftSide, rightStart.top, rightStart.left, rightStart.bottom);
  4826. } else {
  4827. add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom);
  4828. }
  4829. }
  4830. if (leftEnd.bottom < rightStart.top)
  4831. { add(leftSide, leftEnd.bottom, null, rightStart.top); }
  4832. }
  4833. output.appendChild(fragment);
  4834. }
  4835. // Cursor-blinking
  4836. function restartBlink(cm) {
  4837. if (!cm.state.focused) { return }
  4838. var display = cm.display;
  4839. clearInterval(display.blinker);
  4840. var on = true;
  4841. display.cursorDiv.style.visibility = "";
  4842. if (cm.options.cursorBlinkRate > 0)
  4843. { display.blinker = setInterval(function () { return display.cursorDiv.style.visibility = (on = !on) ? "" : "hidden"; },
  4844. cm.options.cursorBlinkRate); }
  4845. else if (cm.options.cursorBlinkRate < 0)
  4846. { display.cursorDiv.style.visibility = "hidden"; }
  4847. }
  4848. function ensureFocus(cm) {
  4849. if (!cm.state.focused) { cm.display.input.focus(); onFocus(cm); }
  4850. }
  4851. function delayBlurEvent(cm) {
  4852. cm.state.delayingBlurEvent = true;
  4853. setTimeout(function () { if (cm.state.delayingBlurEvent) {
  4854. cm.state.delayingBlurEvent = false;
  4855. onBlur(cm);
  4856. } }, 100);
  4857. }
  4858. function onFocus(cm, e) {
  4859. if (cm.state.delayingBlurEvent) { cm.state.delayingBlurEvent = false; }
  4860. if (cm.options.readOnly == "nocursor") { return }
  4861. if (!cm.state.focused) {
  4862. signal(cm, "focus", cm, e);
  4863. cm.state.focused = true;
  4864. addClass(cm.display.wrapper, "CodeMirror-focused");
  4865. // This test prevents this from firing when a context
  4866. // menu is closed (since the input reset would kill the
  4867. // select-all detection hack)
  4868. if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) {
  4869. cm.display.input.reset();
  4870. if (webkit) { setTimeout(function () { return cm.display.input.reset(true); }, 20); } // Issue #1730
  4871. }
  4872. cm.display.input.receivedFocus();
  4873. }
  4874. restartBlink(cm);
  4875. }
  4876. function onBlur(cm, e) {
  4877. if (cm.state.delayingBlurEvent) { return }
  4878. if (cm.state.focused) {
  4879. signal(cm, "blur", cm, e);
  4880. cm.state.focused = false;
  4881. rmClass(cm.display.wrapper, "CodeMirror-focused");
  4882. }
  4883. clearInterval(cm.display.blinker);
  4884. setTimeout(function () { if (!cm.state.focused) { cm.display.shift = false; } }, 150);
  4885. }
  4886. // Read the actual heights of the rendered lines, and update their
  4887. // stored heights to match.
  4888. function updateHeightsInViewport(cm) {
  4889. var display = cm.display;
  4890. var prevBottom = display.lineDiv.offsetTop;
  4891. for (var i = 0; i < display.view.length; i++) {
  4892. var cur = display.view[i], height = (void 0);
  4893. if (cur.hidden) { continue }
  4894. if (ie && ie_version < 8) {
  4895. var bot = cur.node.offsetTop + cur.node.offsetHeight;
  4896. height = bot - prevBottom;
  4897. prevBottom = bot;
  4898. } else {
  4899. var box = cur.node.getBoundingClientRect();
  4900. height = box.bottom - box.top;
  4901. }
  4902. var diff = cur.line.height - height;
  4903. if (height < 2) { height = textHeight(display); }
  4904. if (diff > .005 || diff < -.005) {
  4905. updateLineHeight(cur.line, height);
  4906. updateWidgetHeight(cur.line);
  4907. if (cur.rest) { for (var j = 0; j < cur.rest.length; j++)
  4908. { updateWidgetHeight(cur.rest[j]); } }
  4909. }
  4910. }
  4911. }
  4912. // Read and store the height of line widgets associated with the
  4913. // given line.
  4914. function updateWidgetHeight(line) {
  4915. if (line.widgets) { for (var i = 0; i < line.widgets.length; ++i) {
  4916. var w = line.widgets[i], parent = w.node.parentNode;
  4917. if (parent) { w.height = parent.offsetHeight; }
  4918. } }
  4919. }
  4920. // Compute the lines that are visible in a given viewport (defaults
  4921. // the the current scroll position). viewport may contain top,
  4922. // height, and ensure (see op.scrollToPos) properties.
  4923. function visibleLines(display, doc, viewport) {
  4924. var top = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop;
  4925. top = Math.floor(top - paddingTop(display));
  4926. var bottom = viewport && viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight;
  4927. var from = lineAtHeight(doc, top), to = lineAtHeight(doc, bottom);
  4928. // Ensure is a {from: {line, ch}, to: {line, ch}} object, and
  4929. // forces those lines into the viewport (if possible).
  4930. if (viewport && viewport.ensure) {
  4931. var ensureFrom = viewport.ensure.from.line, ensureTo = viewport.ensure.to.line;
  4932. if (ensureFrom < from) {
  4933. from = ensureFrom;
  4934. to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight);
  4935. } else if (Math.min(ensureTo, doc.lastLine()) >= to) {
  4936. from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight);
  4937. to = ensureTo;
  4938. }
  4939. }
  4940. return {from: from, to: Math.max(to, from + 1)}
  4941. }
  4942. // Re-align line numbers and gutter marks to compensate for
  4943. // horizontal scrolling.
  4944. function alignHorizontally(cm) {
  4945. var display = cm.display, view = display.view;
  4946. if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) { return }
  4947. var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft;
  4948. var gutterW = display.gutters.offsetWidth, left = comp + "px";
  4949. for (var i = 0; i < view.length; i++) { if (!view[i].hidden) {
  4950. if (cm.options.fixedGutter) {
  4951. if (view[i].gutter)
  4952. { view[i].gutter.style.left = left; }
  4953. if (view[i].gutterBackground)
  4954. { view[i].gutterBackground.style.left = left; }
  4955. }
  4956. var align = view[i].alignable;
  4957. if (align) { for (var j = 0; j < align.length; j++)
  4958. { align[j].style.left = left; } }
  4959. } }
  4960. if (cm.options.fixedGutter)
  4961. { display.gutters.style.left = (comp + gutterW) + "px"; }
  4962. }
  4963. // Used to ensure that the line number gutter is still the right
  4964. // size for the current document size. Returns true when an update
  4965. // is needed.
  4966. function maybeUpdateLineNumberWidth(cm) {
  4967. if (!cm.options.lineNumbers) { return false }
  4968. var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display;
  4969. if (last.length != display.lineNumChars) {
  4970. var test = display.measure.appendChild(elt("div", [elt("div", last)],
  4971. "CodeMirror-linenumber CodeMirror-gutter-elt"));
  4972. var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW;
  4973. display.lineGutter.style.width = "";
  4974. display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding) + 1;
  4975. display.lineNumWidth = display.lineNumInnerWidth + padding;
  4976. display.lineNumChars = display.lineNumInnerWidth ? last.length : -1;
  4977. display.lineGutter.style.width = display.lineNumWidth + "px";
  4978. updateGutterSpace(cm);
  4979. return true
  4980. }
  4981. return false
  4982. }
  4983. // SCROLLING THINGS INTO VIEW
  4984. // If an editor sits on the top or bottom of the window, partially
  4985. // scrolled out of view, this ensures that the cursor is visible.
  4986. function maybeScrollWindow(cm, rect) {
  4987. if (signalDOMEvent(cm, "scrollCursorIntoView")) { return }
  4988. var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null;
  4989. if (rect.top + box.top < 0) { doScroll = true; }
  4990. else if (rect.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) { doScroll = false; }
  4991. if (doScroll != null && !phantom) {
  4992. 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;"));
  4993. cm.display.lineSpace.appendChild(scrollNode);
  4994. scrollNode.scrollIntoView(doScroll);
  4995. cm.display.lineSpace.removeChild(scrollNode);
  4996. }
  4997. }
  4998. // Scroll a given position into view (immediately), verifying that
  4999. // it actually became visible (as line heights are accurately
  5000. // measured, the position of something may 'drift' during drawing).
  5001. function scrollPosIntoView(cm, pos, end, margin) {
  5002. if (margin == null) { margin = 0; }
  5003. var rect;
  5004. if (!cm.options.lineWrapping && pos == end) {
  5005. // Set pos and end to the cursor positions around the character pos sticks to
  5006. // If pos.sticky == "before", that is around pos.ch - 1, otherwise around pos.ch
  5007. // If pos == Pos(_, 0, "before"), pos and end are unchanged
  5008. pos = pos.ch ? Pos(pos.line, pos.sticky == "before" ? pos.ch - 1 : pos.ch, "after") : pos;
  5009. end = pos.sticky == "before" ? Pos(pos.line, pos.ch + 1, "before") : pos;
  5010. }
  5011. for (var limit = 0; limit < 5; limit++) {
  5012. var changed = false;
  5013. var coords = cursorCoords(cm, pos);
  5014. var endCoords = !end || end == pos ? coords : cursorCoords(cm, end);
  5015. rect = {left: Math.min(coords.left, endCoords.left),
  5016. top: Math.min(coords.top, endCoords.top) - margin,
  5017. right: Math.max(coords.left, endCoords.left),
  5018. bottom: Math.max(coords.bottom, endCoords.bottom) + margin};
  5019. var scrollPos = calculateScrollPos(cm, rect);
  5020. var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft;
  5021. if (scrollPos.scrollTop != null) {
  5022. updateScrollTop(cm, scrollPos.scrollTop);
  5023. if (Math.abs(cm.doc.scrollTop - startTop) > 1) { changed = true; }
  5024. }
  5025. if (scrollPos.scrollLeft != null) {
  5026. setScrollLeft(cm, scrollPos.scrollLeft);
  5027. if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) { changed = true; }
  5028. }
  5029. if (!changed) { break }
  5030. }
  5031. return rect
  5032. }
  5033. // Scroll a given set of coordinates into view (immediately).
  5034. function scrollIntoView(cm, rect) {
  5035. var scrollPos = calculateScrollPos(cm, rect);
  5036. if (scrollPos.scrollTop != null) { updateScrollTop(cm, scrollPos.scrollTop); }
  5037. if (scrollPos.scrollLeft != null) { setScrollLeft(cm, scrollPos.scrollLeft); }
  5038. }
  5039. // Calculate a new scroll position needed to scroll the given
  5040. // rectangle into view. Returns an object with scrollTop and
  5041. // scrollLeft properties. When these are undefined, the
  5042. // vertical/horizontal position does not need to be adjusted.
  5043. function calculateScrollPos(cm, rect) {
  5044. var display = cm.display, snapMargin = textHeight(cm.display);
  5045. if (rect.top < 0) { rect.top = 0; }
  5046. var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop;
  5047. var screen = displayHeight(cm), result = {};
  5048. if (rect.bottom - rect.top > screen) { rect.bottom = rect.top + screen; }
  5049. var docBottom = cm.doc.height + paddingVert(display);
  5050. var atTop = rect.top < snapMargin, atBottom = rect.bottom > docBottom - snapMargin;
  5051. if (rect.top < screentop) {
  5052. result.scrollTop = atTop ? 0 : rect.top;
  5053. } else if (rect.bottom > screentop + screen) {
  5054. var newTop = Math.min(rect.top, (atBottom ? docBottom : rect.bottom) - screen);
  5055. if (newTop != screentop) { result.scrollTop = newTop; }
  5056. }
  5057. var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft;
  5058. var screenw = displayWidth(cm) - (cm.options.fixedGutter ? display.gutters.offsetWidth : 0);
  5059. var tooWide = rect.right - rect.left > screenw;
  5060. if (tooWide) { rect.right = rect.left + screenw; }
  5061. if (rect.left < 10)
  5062. { result.scrollLeft = 0; }
  5063. else if (rect.left < screenleft)
  5064. { result.scrollLeft = Math.max(0, rect.left - (tooWide ? 0 : 10)); }
  5065. else if (rect.right > screenw + screenleft - 3)
  5066. { result.scrollLeft = rect.right + (tooWide ? 0 : 10) - screenw; }
  5067. return result
  5068. }
  5069. // Store a relative adjustment to the scroll position in the current
  5070. // operation (to be applied when the operation finishes).
  5071. function addToScrollTop(cm, top) {
  5072. if (top == null) { return }
  5073. resolveScrollToPos(cm);
  5074. cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top;
  5075. }
  5076. // Make sure that at the end of the operation the current cursor is
  5077. // shown.
  5078. function ensureCursorVisible(cm) {
  5079. resolveScrollToPos(cm);
  5080. var cur = cm.getCursor();
  5081. cm.curOp.scrollToPos = {from: cur, to: cur, margin: cm.options.cursorScrollMargin};
  5082. }
  5083. function scrollToCoords(cm, x, y) {
  5084. if (x != null || y != null) { resolveScrollToPos(cm); }
  5085. if (x != null) { cm.curOp.scrollLeft = x; }
  5086. if (y != null) { cm.curOp.scrollTop = y; }
  5087. }
  5088. function scrollToRange(cm, range$$1) {
  5089. resolveScrollToPos(cm);
  5090. cm.curOp.scrollToPos = range$$1;
  5091. }
  5092. // When an operation has its scrollToPos property set, and another
  5093. // scroll action is applied before the end of the operation, this
  5094. // 'simulates' scrolling that position into view in a cheap way, so
  5095. // that the effect of intermediate scroll commands is not ignored.
  5096. function resolveScrollToPos(cm) {
  5097. var range$$1 = cm.curOp.scrollToPos;
  5098. if (range$$1) {
  5099. cm.curOp.scrollToPos = null;
  5100. var from = estimateCoords(cm, range$$1.from), to = estimateCoords(cm, range$$1.to);
  5101. scrollToCoordsRange(cm, from, to, range$$1.margin);
  5102. }
  5103. }
  5104. function scrollToCoordsRange(cm, from, to, margin) {
  5105. var sPos = calculateScrollPos(cm, {
  5106. left: Math.min(from.left, to.left),
  5107. top: Math.min(from.top, to.top) - margin,
  5108. right: Math.max(from.right, to.right),
  5109. bottom: Math.max(from.bottom, to.bottom) + margin
  5110. });
  5111. scrollToCoords(cm, sPos.scrollLeft, sPos.scrollTop);
  5112. }
  5113. // Sync the scrollable area and scrollbars, ensure the viewport
  5114. // covers the visible area.
  5115. function updateScrollTop(cm, val) {
  5116. if (Math.abs(cm.doc.scrollTop - val) < 2) { return }
  5117. if (!gecko) { updateDisplaySimple(cm, {top: val}); }
  5118. setScrollTop(cm, val, true);
  5119. if (gecko) { updateDisplaySimple(cm); }
  5120. startWorker(cm, 100);
  5121. }
  5122. function setScrollTop(cm, val, forceScroll) {
  5123. val = Math.min(cm.display.scroller.scrollHeight - cm.display.scroller.clientHeight, val);
  5124. if (cm.display.scroller.scrollTop == val && !forceScroll) { return }
  5125. cm.doc.scrollTop = val;
  5126. cm.display.scrollbars.setScrollTop(val);
  5127. if (cm.display.scroller.scrollTop != val) { cm.display.scroller.scrollTop = val; }
  5128. }
  5129. // Sync scroller and scrollbar, ensure the gutter elements are
  5130. // aligned.
  5131. function setScrollLeft(cm, val, isScroller, forceScroll) {
  5132. val = Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth);
  5133. if ((isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) && !forceScroll) { return }
  5134. cm.doc.scrollLeft = val;
  5135. alignHorizontally(cm);
  5136. if (cm.display.scroller.scrollLeft != val) { cm.display.scroller.scrollLeft = val; }
  5137. cm.display.scrollbars.setScrollLeft(val);
  5138. }
  5139. // SCROLLBARS
  5140. // Prepare DOM reads needed to update the scrollbars. Done in one
  5141. // shot to minimize update/measure roundtrips.
  5142. function measureForScrollbars(cm) {
  5143. var d = cm.display, gutterW = d.gutters.offsetWidth;
  5144. var docH = Math.round(cm.doc.height + paddingVert(cm.display));
  5145. return {
  5146. clientHeight: d.scroller.clientHeight,
  5147. viewHeight: d.wrapper.clientHeight,
  5148. scrollWidth: d.scroller.scrollWidth, clientWidth: d.scroller.clientWidth,
  5149. viewWidth: d.wrapper.clientWidth,
  5150. barLeft: cm.options.fixedGutter ? gutterW : 0,
  5151. docHeight: docH,
  5152. scrollHeight: docH + scrollGap(cm) + d.barHeight,
  5153. nativeBarWidth: d.nativeBarWidth,
  5154. gutterWidth: gutterW
  5155. }
  5156. }
  5157. var NativeScrollbars = function(place, scroll, cm) {
  5158. this.cm = cm;
  5159. var vert = this.vert = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar");
  5160. var horiz = this.horiz = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar");
  5161. place(vert); place(horiz);
  5162. on(vert, "scroll", function () {
  5163. if (vert.clientHeight) { scroll(vert.scrollTop, "vertical"); }
  5164. });
  5165. on(horiz, "scroll", function () {
  5166. if (horiz.clientWidth) { scroll(horiz.scrollLeft, "horizontal"); }
  5167. });
  5168. this.checkedZeroWidth = false;
  5169. // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8).
  5170. if (ie && ie_version < 8) { this.horiz.style.minHeight = this.vert.style.minWidth = "18px"; }
  5171. };
  5172. NativeScrollbars.prototype.update = function (measure) {
  5173. var needsH = measure.scrollWidth > measure.clientWidth + 1;
  5174. var needsV = measure.scrollHeight > measure.clientHeight + 1;
  5175. var sWidth = measure.nativeBarWidth;
  5176. if (needsV) {
  5177. this.vert.style.display = "block";
  5178. this.vert.style.bottom = needsH ? sWidth + "px" : "0";
  5179. var totalHeight = measure.viewHeight - (needsH ? sWidth : 0);
  5180. // A bug in IE8 can cause this value to be negative, so guard it.
  5181. this.vert.firstChild.style.height =
  5182. Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + "px";
  5183. } else {
  5184. this.vert.style.display = "";
  5185. this.vert.firstChild.style.height = "0";
  5186. }
  5187. if (needsH) {
  5188. this.horiz.style.display = "block";
  5189. this.horiz.style.right = needsV ? sWidth + "px" : "0";
  5190. this.horiz.style.left = measure.barLeft + "px";
  5191. var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0);
  5192. this.horiz.firstChild.style.width =
  5193. Math.max(0, measure.scrollWidth - measure.clientWidth + totalWidth) + "px";
  5194. } else {
  5195. this.horiz.style.display = "";
  5196. this.horiz.firstChild.style.width = "0";
  5197. }
  5198. if (!this.checkedZeroWidth && measure.clientHeight > 0) {
  5199. if (sWidth == 0) { this.zeroWidthHack(); }
  5200. this.checkedZeroWidth = true;
  5201. }
  5202. return {right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0}
  5203. };
  5204. NativeScrollbars.prototype.setScrollLeft = function (pos) {
  5205. if (this.horiz.scrollLeft != pos) { this.horiz.scrollLeft = pos; }
  5206. if (this.disableHoriz) { this.enableZeroWidthBar(this.horiz, this.disableHoriz, "horiz"); }
  5207. };
  5208. NativeScrollbars.prototype.setScrollTop = function (pos) {
  5209. if (this.vert.scrollTop != pos) { this.vert.scrollTop = pos; }
  5210. if (this.disableVert) { this.enableZeroWidthBar(this.vert, this.disableVert, "vert"); }
  5211. };
  5212. NativeScrollbars.prototype.zeroWidthHack = function () {
  5213. var w = mac && !mac_geMountainLion ? "12px" : "18px";
  5214. this.horiz.style.height = this.vert.style.width = w;
  5215. this.horiz.style.pointerEvents = this.vert.style.pointerEvents = "none";
  5216. this.disableHoriz = new Delayed;
  5217. this.disableVert = new Delayed;
  5218. };
  5219. NativeScrollbars.prototype.enableZeroWidthBar = function (bar, delay, type) {
  5220. bar.style.pointerEvents = "auto";
  5221. function maybeDisable() {
  5222. // To find out whether the scrollbar is still visible, we
  5223. // check whether the element under the pixel in the bottom
  5224. // right corner of the scrollbar box is the scrollbar box
  5225. // itself (when the bar is still visible) or its filler child
  5226. // (when the bar is hidden). If it is still visible, we keep
  5227. // it enabled, if it's hidden, we disable pointer events.
  5228. var box = bar.getBoundingClientRect();
  5229. var elt$$1 = type == "vert" ? document.elementFromPoint(box.right - 1, (box.top + box.bottom) / 2)
  5230. : document.elementFromPoint((box.right + box.left) / 2, box.bottom - 1);
  5231. if (elt$$1 != bar) { bar.style.pointerEvents = "none"; }
  5232. else { delay.set(1000, maybeDisable); }
  5233. }
  5234. delay.set(1000, maybeDisable);
  5235. };
  5236. NativeScrollbars.prototype.clear = function () {
  5237. var parent = this.horiz.parentNode;
  5238. parent.removeChild(this.horiz);
  5239. parent.removeChild(this.vert);
  5240. };
  5241. var NullScrollbars = function () {};
  5242. NullScrollbars.prototype.update = function () { return {bottom: 0, right: 0} };
  5243. NullScrollbars.prototype.setScrollLeft = function () {};
  5244. NullScrollbars.prototype.setScrollTop = function () {};
  5245. NullScrollbars.prototype.clear = function () {};
  5246. function updateScrollbars(cm, measure) {
  5247. if (!measure) { measure = measureForScrollbars(cm); }
  5248. var startWidth = cm.display.barWidth, startHeight = cm.display.barHeight;
  5249. updateScrollbarsInner(cm, measure);
  5250. for (var i = 0; i < 4 && startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i++) {
  5251. if (startWidth != cm.display.barWidth && cm.options.lineWrapping)
  5252. { updateHeightsInViewport(cm); }
  5253. updateScrollbarsInner(cm, measureForScrollbars(cm));
  5254. startWidth = cm.display.barWidth; startHeight = cm.display.barHeight;
  5255. }
  5256. }
  5257. // Re-synchronize the fake scrollbars with the actual size of the
  5258. // content.
  5259. function updateScrollbarsInner(cm, measure) {
  5260. var d = cm.display;
  5261. var sizes = d.scrollbars.update(measure);
  5262. d.sizer.style.paddingRight = (d.barWidth = sizes.right) + "px";
  5263. d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + "px";
  5264. d.heightForcer.style.borderBottom = sizes.bottom + "px solid transparent";
  5265. if (sizes.right && sizes.bottom) {
  5266. d.scrollbarFiller.style.display = "block";
  5267. d.scrollbarFiller.style.height = sizes.bottom + "px";
  5268. d.scrollbarFiller.style.width = sizes.right + "px";
  5269. } else { d.scrollbarFiller.style.display = ""; }
  5270. if (sizes.bottom && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) {
  5271. d.gutterFiller.style.display = "block";
  5272. d.gutterFiller.style.height = sizes.bottom + "px";
  5273. d.gutterFiller.style.width = measure.gutterWidth + "px";
  5274. } else { d.gutterFiller.style.display = ""; }
  5275. }
  5276. var scrollbarModel = {"native": NativeScrollbars, "null": NullScrollbars};
  5277. function initScrollbars(cm) {
  5278. if (cm.display.scrollbars) {
  5279. cm.display.scrollbars.clear();
  5280. if (cm.display.scrollbars.addClass)
  5281. { rmClass(cm.display.wrapper, cm.display.scrollbars.addClass); }
  5282. }
  5283. cm.display.scrollbars = new scrollbarModel[cm.options.scrollbarStyle](function (node) {
  5284. cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller);
  5285. // Prevent clicks in the scrollbars from killing focus
  5286. on(node, "mousedown", function () {
  5287. if (cm.state.focused) { setTimeout(function () { return cm.display.input.focus(); }, 0); }
  5288. });
  5289. node.setAttribute("cm-not-content", "true");
  5290. }, function (pos, axis) {
  5291. if (axis == "horizontal") { setScrollLeft(cm, pos); }
  5292. else { updateScrollTop(cm, pos); }
  5293. }, cm);
  5294. if (cm.display.scrollbars.addClass)
  5295. { addClass(cm.display.wrapper, cm.display.scrollbars.addClass); }
  5296. }
  5297. // Operations are used to wrap a series of changes to the editor
  5298. // state in such a way that each change won't have to update the
  5299. // cursor and display (which would be awkward, slow, and
  5300. // error-prone). Instead, display updates are batched and then all
  5301. // combined and executed at once.
  5302. var nextOpId = 0;
  5303. // Start a new operation.
  5304. function startOperation(cm) {
  5305. cm.curOp = {
  5306. cm: cm,
  5307. viewChanged: false, // Flag that indicates that lines might need to be redrawn
  5308. startHeight: cm.doc.height, // Used to detect need to update scrollbar
  5309. forceUpdate: false, // Used to force a redraw
  5310. updateInput: null, // Whether to reset the input textarea
  5311. typing: false, // Whether this reset should be careful to leave existing text (for compositing)
  5312. changeObjs: null, // Accumulated changes, for firing change events
  5313. cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on
  5314. cursorActivityCalled: 0, // Tracks which cursorActivity handlers have been called already
  5315. selectionChanged: false, // Whether the selection needs to be redrawn
  5316. updateMaxLine: false, // Set when the widest line needs to be determined anew
  5317. scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet
  5318. scrollToPos: null, // Used to scroll to a specific position
  5319. focus: false,
  5320. id: ++nextOpId // Unique ID
  5321. };
  5322. pushOperation(cm.curOp);
  5323. }
  5324. // Finish an operation, updating the display and signalling delayed events
  5325. function endOperation(cm) {
  5326. var op = cm.curOp;
  5327. finishOperation(op, function (group) {
  5328. for (var i = 0; i < group.ops.length; i++)
  5329. { group.ops[i].cm.curOp = null; }
  5330. endOperations(group);
  5331. });
  5332. }
  5333. // The DOM updates done when an operation finishes are batched so
  5334. // that the minimum number of relayouts are required.
  5335. function endOperations(group) {
  5336. var ops = group.ops;
  5337. for (var i = 0; i < ops.length; i++) // Read DOM
  5338. { endOperation_R1(ops[i]); }
  5339. for (var i$1 = 0; i$1 < ops.length; i$1++) // Write DOM (maybe)
  5340. { endOperation_W1(ops[i$1]); }
  5341. for (var i$2 = 0; i$2 < ops.length; i$2++) // Read DOM
  5342. { endOperation_R2(ops[i$2]); }
  5343. for (var i$3 = 0; i$3 < ops.length; i$3++) // Write DOM (maybe)
  5344. { endOperation_W2(ops[i$3]); }
  5345. for (var i$4 = 0; i$4 < ops.length; i$4++) // Read DOM
  5346. { endOperation_finish(ops[i$4]); }
  5347. }
  5348. function endOperation_R1(op) {
  5349. var cm = op.cm, display = cm.display;
  5350. maybeClipScrollbars(cm);
  5351. if (op.updateMaxLine) { findMaxLine(cm); }
  5352. op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null ||
  5353. op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom ||
  5354. op.scrollToPos.to.line >= display.viewTo) ||
  5355. display.maxLineChanged && cm.options.lineWrapping;
  5356. op.update = op.mustUpdate &&
  5357. new DisplayUpdate(cm, op.mustUpdate && {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate);
  5358. }
  5359. function endOperation_W1(op) {
  5360. op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update);
  5361. }
  5362. function endOperation_R2(op) {
  5363. var cm = op.cm, display = cm.display;
  5364. if (op.updatedDisplay) { updateHeightsInViewport(cm); }
  5365. op.barMeasure = measureForScrollbars(cm);
  5366. // If the max line changed since it was last measured, measure it,
  5367. // and ensure the document's width matches it.
  5368. // updateDisplay_W2 will use these properties to do the actual resizing
  5369. if (display.maxLineChanged && !cm.options.lineWrapping) {
  5370. op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3;
  5371. cm.display.sizerWidth = op.adjustWidthTo;
  5372. op.barMeasure.scrollWidth =
  5373. Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth);
  5374. op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm));
  5375. }
  5376. if (op.updatedDisplay || op.selectionChanged)
  5377. { op.preparedSelection = display.input.prepareSelection(); }
  5378. }
  5379. function endOperation_W2(op) {
  5380. var cm = op.cm;
  5381. if (op.adjustWidthTo != null) {
  5382. cm.display.sizer.style.minWidth = op.adjustWidthTo + "px";
  5383. if (op.maxScrollLeft < cm.doc.scrollLeft)
  5384. { setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true); }
  5385. cm.display.maxLineChanged = false;
  5386. }
  5387. var takeFocus = op.focus && op.focus == activeElt();
  5388. if (op.preparedSelection)
  5389. { cm.display.input.showSelection(op.preparedSelection, takeFocus); }
  5390. if (op.updatedDisplay || op.startHeight != cm.doc.height)
  5391. { updateScrollbars(cm, op.barMeasure); }
  5392. if (op.updatedDisplay)
  5393. { setDocumentHeight(cm, op.barMeasure); }
  5394. if (op.selectionChanged) { restartBlink(cm); }
  5395. if (cm.state.focused && op.updateInput)
  5396. { cm.display.input.reset(op.typing); }
  5397. if (takeFocus) { ensureFocus(op.cm); }
  5398. }
  5399. function endOperation_finish(op) {
  5400. var cm = op.cm, display = cm.display, doc = cm.doc;
  5401. if (op.updatedDisplay) { postUpdateDisplay(cm, op.update); }
  5402. // Abort mouse wheel delta measurement, when scrolling explicitly
  5403. if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos))
  5404. { display.wheelStartX = display.wheelStartY = null; }
  5405. // Propagate the scroll position to the actual DOM scroller
  5406. if (op.scrollTop != null) { setScrollTop(cm, op.scrollTop, op.forceScroll); }
  5407. if (op.scrollLeft != null) { setScrollLeft(cm, op.scrollLeft, true, true); }
  5408. // If we need to scroll a specific position into view, do so.
  5409. if (op.scrollToPos) {
  5410. var rect = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from),
  5411. clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin);
  5412. maybeScrollWindow(cm, rect);
  5413. }
  5414. // Fire events for markers that are hidden/unidden by editing or
  5415. // undoing
  5416. var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers;
  5417. if (hidden) { for (var i = 0; i < hidden.length; ++i)
  5418. { if (!hidden[i].lines.length) { signal(hidden[i], "hide"); } } }
  5419. if (unhidden) { for (var i$1 = 0; i$1 < unhidden.length; ++i$1)
  5420. { if (unhidden[i$1].lines.length) { signal(unhidden[i$1], "unhide"); } } }
  5421. if (display.wrapper.offsetHeight)
  5422. { doc.scrollTop = cm.display.scroller.scrollTop; }
  5423. // Fire change events, and delayed event handlers
  5424. if (op.changeObjs)
  5425. { signal(cm, "changes", cm, op.changeObjs); }
  5426. if (op.update)
  5427. { op.update.finish(); }
  5428. }
  5429. // Run the given function in an operation
  5430. function runInOp(cm, f) {
  5431. if (cm.curOp) { return f() }
  5432. startOperation(cm);
  5433. try { return f() }
  5434. finally { endOperation(cm); }
  5435. }
  5436. // Wraps a function in an operation. Returns the wrapped function.
  5437. function operation(cm, f) {
  5438. return function() {
  5439. if (cm.curOp) { return f.apply(cm, arguments) }
  5440. startOperation(cm);
  5441. try { return f.apply(cm, arguments) }
  5442. finally { endOperation(cm); }
  5443. }
  5444. }
  5445. // Used to add methods to editor and doc instances, wrapping them in
  5446. // operations.
  5447. function methodOp(f) {
  5448. return function() {
  5449. if (this.curOp) { return f.apply(this, arguments) }
  5450. startOperation(this);
  5451. try { return f.apply(this, arguments) }
  5452. finally { endOperation(this); }
  5453. }
  5454. }
  5455. function docMethodOp(f) {
  5456. return function() {
  5457. var cm = this.cm;
  5458. if (!cm || cm.curOp) { return f.apply(this, arguments) }
  5459. startOperation(cm);
  5460. try { return f.apply(this, arguments) }
  5461. finally { endOperation(cm); }
  5462. }
  5463. }
  5464. // Updates the display.view data structure for a given change to the
  5465. // document. From and to are in pre-change coordinates. Lendiff is
  5466. // the amount of lines added or subtracted by the change. This is
  5467. // used for changes that span multiple lines, or change the way
  5468. // lines are divided into visual lines. regLineChange (below)
  5469. // registers single-line changes.
  5470. function regChange(cm, from, to, lendiff) {
  5471. if (from == null) { from = cm.doc.first; }
  5472. if (to == null) { to = cm.doc.first + cm.doc.size; }
  5473. if (!lendiff) { lendiff = 0; }
  5474. var display = cm.display;
  5475. if (lendiff && to < display.viewTo &&
  5476. (display.updateLineNumbers == null || display.updateLineNumbers > from))
  5477. { display.updateLineNumbers = from; }
  5478. cm.curOp.viewChanged = true;
  5479. if (from >= display.viewTo) { // Change after
  5480. if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo)
  5481. { resetView(cm); }
  5482. } else if (to <= display.viewFrom) { // Change before
  5483. if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) {
  5484. resetView(cm);
  5485. } else {
  5486. display.viewFrom += lendiff;
  5487. display.viewTo += lendiff;
  5488. }
  5489. } else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap
  5490. resetView(cm);
  5491. } else if (from <= display.viewFrom) { // Top overlap
  5492. var cut = viewCuttingPoint(cm, to, to + lendiff, 1);
  5493. if (cut) {
  5494. display.view = display.view.slice(cut.index);
  5495. display.viewFrom = cut.lineN;
  5496. display.viewTo += lendiff;
  5497. } else {
  5498. resetView(cm);
  5499. }
  5500. } else if (to >= display.viewTo) { // Bottom overlap
  5501. var cut$1 = viewCuttingPoint(cm, from, from, -1);
  5502. if (cut$1) {
  5503. display.view = display.view.slice(0, cut$1.index);
  5504. display.viewTo = cut$1.lineN;
  5505. } else {
  5506. resetView(cm);
  5507. }
  5508. } else { // Gap in the middle
  5509. var cutTop = viewCuttingPoint(cm, from, from, -1);
  5510. var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1);
  5511. if (cutTop && cutBot) {
  5512. display.view = display.view.slice(0, cutTop.index)
  5513. .concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN))
  5514. .concat(display.view.slice(cutBot.index));
  5515. display.viewTo += lendiff;
  5516. } else {
  5517. resetView(cm);
  5518. }
  5519. }
  5520. var ext = display.externalMeasured;
  5521. if (ext) {
  5522. if (to < ext.lineN)
  5523. { ext.lineN += lendiff; }
  5524. else if (from < ext.lineN + ext.size)
  5525. { display.externalMeasured = null; }
  5526. }
  5527. }
  5528. // Register a change to a single line. Type must be one of "text",
  5529. // "gutter", "class", "widget"
  5530. function regLineChange(cm, line, type) {
  5531. cm.curOp.viewChanged = true;
  5532. var display = cm.display, ext = cm.display.externalMeasured;
  5533. if (ext && line >= ext.lineN && line < ext.lineN + ext.size)
  5534. { display.externalMeasured = null; }
  5535. if (line < display.viewFrom || line >= display.viewTo) { return }
  5536. var lineView = display.view[findViewIndex(cm, line)];
  5537. if (lineView.node == null) { return }
  5538. var arr = lineView.changes || (lineView.changes = []);
  5539. if (indexOf(arr, type) == -1) { arr.push(type); }
  5540. }
  5541. // Clear the view.
  5542. function resetView(cm) {
  5543. cm.display.viewFrom = cm.display.viewTo = cm.doc.first;
  5544. cm.display.view = [];
  5545. cm.display.viewOffset = 0;
  5546. }
  5547. function viewCuttingPoint(cm, oldN, newN, dir) {
  5548. var index = findViewIndex(cm, oldN), diff, view = cm.display.view;
  5549. if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size)
  5550. { return {index: index, lineN: newN} }
  5551. var n = cm.display.viewFrom;
  5552. for (var i = 0; i < index; i++)
  5553. { n += view[i].size; }
  5554. if (n != oldN) {
  5555. if (dir > 0) {
  5556. if (index == view.length - 1) { return null }
  5557. diff = (n + view[index].size) - oldN;
  5558. index++;
  5559. } else {
  5560. diff = n - oldN;
  5561. }
  5562. oldN += diff; newN += diff;
  5563. }
  5564. while (visualLineNo(cm.doc, newN) != newN) {
  5565. if (index == (dir < 0 ? 0 : view.length - 1)) { return null }
  5566. newN += dir * view[index - (dir < 0 ? 1 : 0)].size;
  5567. index += dir;
  5568. }
  5569. return {index: index, lineN: newN}
  5570. }
  5571. // Force the view to cover a given range, adding empty view element
  5572. // or clipping off existing ones as needed.
  5573. function adjustView(cm, from, to) {
  5574. var display = cm.display, view = display.view;
  5575. if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) {
  5576. display.view = buildViewArray(cm, from, to);
  5577. display.viewFrom = from;
  5578. } else {
  5579. if (display.viewFrom > from)
  5580. { display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view); }
  5581. else if (display.viewFrom < from)
  5582. { display.view = display.view.slice(findViewIndex(cm, from)); }
  5583. display.viewFrom = from;
  5584. if (display.viewTo < to)
  5585. { display.view = display.view.concat(buildViewArray(cm, display.viewTo, to)); }
  5586. else if (display.viewTo > to)
  5587. { display.view = display.view.slice(0, findViewIndex(cm, to)); }
  5588. }
  5589. display.viewTo = to;
  5590. }
  5591. // Count the number of lines in the view whose DOM representation is
  5592. // out of date (or nonexistent).
  5593. function countDirtyView(cm) {
  5594. var view = cm.display.view, dirty = 0;
  5595. for (var i = 0; i < view.length; i++) {
  5596. var lineView = view[i];
  5597. if (!lineView.hidden && (!lineView.node || lineView.changes)) { ++dirty; }
  5598. }
  5599. return dirty
  5600. }
  5601. // HIGHLIGHT WORKER
  5602. function startWorker(cm, time) {
  5603. if (cm.doc.highlightFrontier < cm.display.viewTo)
  5604. { cm.state.highlight.set(time, bind(highlightWorker, cm)); }
  5605. }
  5606. function highlightWorker(cm) {
  5607. var doc = cm.doc;
  5608. if (doc.highlightFrontier >= cm.display.viewTo) { return }
  5609. var end = +new Date + cm.options.workTime;
  5610. var context = getContextBefore(cm, doc.highlightFrontier);
  5611. var changedLines = [];
  5612. doc.iter(context.line, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function (line) {
  5613. if (context.line >= cm.display.viewFrom) { // Visible
  5614. var oldStyles = line.styles;
  5615. var resetState = line.text.length > cm.options.maxHighlightLength ? copyState(doc.mode, context.state) : null;
  5616. var highlighted = highlightLine(cm, line, context, true);
  5617. if (resetState) { context.state = resetState; }
  5618. line.styles = highlighted.styles;
  5619. var oldCls = line.styleClasses, newCls = highlighted.classes;
  5620. if (newCls) { line.styleClasses = newCls; }
  5621. else if (oldCls) { line.styleClasses = null; }
  5622. var ischange = !oldStyles || oldStyles.length != line.styles.length ||
  5623. oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass);
  5624. for (var i = 0; !ischange && i < oldStyles.length; ++i) { ischange = oldStyles[i] != line.styles[i]; }
  5625. if (ischange) { changedLines.push(context.line); }
  5626. line.stateAfter = context.save();
  5627. context.nextLine();
  5628. } else {
  5629. if (line.text.length <= cm.options.maxHighlightLength)
  5630. { processLine(cm, line.text, context); }
  5631. line.stateAfter = context.line % 5 == 0 ? context.save() : null;
  5632. context.nextLine();
  5633. }
  5634. if (+new Date > end) {
  5635. startWorker(cm, cm.options.workDelay);
  5636. return true
  5637. }
  5638. });
  5639. doc.highlightFrontier = context.line;
  5640. doc.modeFrontier = Math.max(doc.modeFrontier, context.line);
  5641. if (changedLines.length) { runInOp(cm, function () {
  5642. for (var i = 0; i < changedLines.length; i++)
  5643. { regLineChange(cm, changedLines[i], "text"); }
  5644. }); }
  5645. }
  5646. // DISPLAY DRAWING
  5647. var DisplayUpdate = function(cm, viewport, force) {
  5648. var display = cm.display;
  5649. this.viewport = viewport;
  5650. // Store some values that we'll need later (but don't want to force a relayout for)
  5651. this.visible = visibleLines(display, cm.doc, viewport);
  5652. this.editorIsHidden = !display.wrapper.offsetWidth;
  5653. this.wrapperHeight = display.wrapper.clientHeight;
  5654. this.wrapperWidth = display.wrapper.clientWidth;
  5655. this.oldDisplayWidth = displayWidth(cm);
  5656. this.force = force;
  5657. this.dims = getDimensions(cm);
  5658. this.events = [];
  5659. };
  5660. DisplayUpdate.prototype.signal = function (emitter, type) {
  5661. if (hasHandler(emitter, type))
  5662. { this.events.push(arguments); }
  5663. };
  5664. DisplayUpdate.prototype.finish = function () {
  5665. var this$1 = this;
  5666. for (var i = 0; i < this.events.length; i++)
  5667. { signal.apply(null, this$1.events[i]); }
  5668. };
  5669. function maybeClipScrollbars(cm) {
  5670. var display = cm.display;
  5671. if (!display.scrollbarsClipped && display.scroller.offsetWidth) {
  5672. display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth;
  5673. display.heightForcer.style.height = scrollGap(cm) + "px";
  5674. display.sizer.style.marginBottom = -display.nativeBarWidth + "px";
  5675. display.sizer.style.borderRightWidth = scrollGap(cm) + "px";
  5676. display.scrollbarsClipped = true;
  5677. }
  5678. }
  5679. function selectionSnapshot(cm) {
  5680. if (cm.hasFocus()) { return null }
  5681. var active = activeElt();
  5682. if (!active || !contains(cm.display.lineDiv, active)) { return null }
  5683. var result = {activeElt: active};
  5684. if (window.getSelection) {
  5685. var sel = window.getSelection();
  5686. if (sel.anchorNode && sel.extend && contains(cm.display.lineDiv, sel.anchorNode)) {
  5687. result.anchorNode = sel.anchorNode;
  5688. result.anchorOffset = sel.anchorOffset;
  5689. result.focusNode = sel.focusNode;
  5690. result.focusOffset = sel.focusOffset;
  5691. }
  5692. }
  5693. return result
  5694. }
  5695. function restoreSelection(snapshot) {
  5696. if (!snapshot || !snapshot.activeElt || snapshot.activeElt == activeElt()) { return }
  5697. snapshot.activeElt.focus();
  5698. if (snapshot.anchorNode && contains(document.body, snapshot.anchorNode) && contains(document.body, snapshot.focusNode)) {
  5699. var sel = window.getSelection(), range$$1 = document.createRange();
  5700. range$$1.setEnd(snapshot.anchorNode, snapshot.anchorOffset);
  5701. range$$1.collapse(false);
  5702. sel.removeAllRanges();
  5703. sel.addRange(range$$1);
  5704. sel.extend(snapshot.focusNode, snapshot.focusOffset);
  5705. }
  5706. }
  5707. // Does the actual updating of the line display. Bails out
  5708. // (returning false) when there is nothing to be done and forced is
  5709. // false.
  5710. function updateDisplayIfNeeded(cm, update) {
  5711. var display = cm.display, doc = cm.doc;
  5712. if (update.editorIsHidden) {
  5713. resetView(cm);
  5714. return false
  5715. }
  5716. // Bail out if the visible area is already rendered and nothing changed.
  5717. if (!update.force &&
  5718. update.visible.from >= display.viewFrom && update.visible.to <= display.viewTo &&
  5719. (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) &&
  5720. display.renderedView == display.view && countDirtyView(cm) == 0)
  5721. { return false }
  5722. if (maybeUpdateLineNumberWidth(cm)) {
  5723. resetView(cm);
  5724. update.dims = getDimensions(cm);
  5725. }
  5726. // Compute a suitable new viewport (from & to)
  5727. var end = doc.first + doc.size;
  5728. var from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first);
  5729. var to = Math.min(end, update.visible.to + cm.options.viewportMargin);
  5730. if (display.viewFrom < from && from - display.viewFrom < 20) { from = Math.max(doc.first, display.viewFrom); }
  5731. if (display.viewTo > to && display.viewTo - to < 20) { to = Math.min(end, display.viewTo); }
  5732. if (sawCollapsedSpans) {
  5733. from = visualLineNo(cm.doc, from);
  5734. to = visualLineEndNo(cm.doc, to);
  5735. }
  5736. var different = from != display.viewFrom || to != display.viewTo ||
  5737. display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth;
  5738. adjustView(cm, from, to);
  5739. display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom));
  5740. // Position the mover div to align with the current scroll position
  5741. cm.display.mover.style.top = display.viewOffset + "px";
  5742. var toUpdate = countDirtyView(cm);
  5743. if (!different && toUpdate == 0 && !update.force && display.renderedView == display.view &&
  5744. (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo))
  5745. { return false }
  5746. // For big changes, we hide the enclosing element during the
  5747. // update, since that speeds up the operations on most browsers.
  5748. var selSnapshot = selectionSnapshot(cm);
  5749. if (toUpdate > 4) { display.lineDiv.style.display = "none"; }
  5750. patchDisplay(cm, display.updateLineNumbers, update.dims);
  5751. if (toUpdate > 4) { display.lineDiv.style.display = ""; }
  5752. display.renderedView = display.view;
  5753. // There might have been a widget with a focused element that got
  5754. // hidden or updated, if so re-focus it.
  5755. restoreSelection(selSnapshot);
  5756. // Prevent selection and cursors from interfering with the scroll
  5757. // width and height.
  5758. removeChildren(display.cursorDiv);
  5759. removeChildren(display.selectionDiv);
  5760. display.gutters.style.height = display.sizer.style.minHeight = 0;
  5761. if (different) {
  5762. display.lastWrapHeight = update.wrapperHeight;
  5763. display.lastWrapWidth = update.wrapperWidth;
  5764. startWorker(cm, 400);
  5765. }
  5766. display.updateLineNumbers = null;
  5767. return true
  5768. }
  5769. function postUpdateDisplay(cm, update) {
  5770. var viewport = update.viewport;
  5771. for (var first = true;; first = false) {
  5772. if (!first || !cm.options.lineWrapping || update.oldDisplayWidth == displayWidth(cm)) {
  5773. // Clip forced viewport to actual scrollable area.
  5774. if (viewport && viewport.top != null)
  5775. { viewport = {top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top)}; }
  5776. // Updated line heights might result in the drawn area not
  5777. // actually covering the viewport. Keep looping until it does.
  5778. update.visible = visibleLines(cm.display, cm.doc, viewport);
  5779. if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo)
  5780. { break }
  5781. }
  5782. if (!updateDisplayIfNeeded(cm, update)) { break }
  5783. updateHeightsInViewport(cm);
  5784. var barMeasure = measureForScrollbars(cm);
  5785. updateSelection(cm);
  5786. updateScrollbars(cm, barMeasure);
  5787. setDocumentHeight(cm, barMeasure);
  5788. update.force = false;
  5789. }
  5790. update.signal(cm, "update", cm);
  5791. if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) {
  5792. update.signal(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo);
  5793. cm.display.reportedViewFrom = cm.display.viewFrom; cm.display.reportedViewTo = cm.display.viewTo;
  5794. }
  5795. }
  5796. function updateDisplaySimple(cm, viewport) {
  5797. var update = new DisplayUpdate(cm, viewport);
  5798. if (updateDisplayIfNeeded(cm, update)) {
  5799. updateHeightsInViewport(cm);
  5800. postUpdateDisplay(cm, update);
  5801. var barMeasure = measureForScrollbars(cm);
  5802. updateSelection(cm);
  5803. updateScrollbars(cm, barMeasure);
  5804. setDocumentHeight(cm, barMeasure);
  5805. update.finish();
  5806. }
  5807. }
  5808. // Sync the actual display DOM structure with display.view, removing
  5809. // nodes for lines that are no longer in view, and creating the ones
  5810. // that are not there yet, and updating the ones that are out of
  5811. // date.
  5812. function patchDisplay(cm, updateNumbersFrom, dims) {
  5813. var display = cm.display, lineNumbers = cm.options.lineNumbers;
  5814. var container = display.lineDiv, cur = container.firstChild;
  5815. function rm(node) {
  5816. var next = node.nextSibling;
  5817. // Works around a throw-scroll bug in OS X Webkit
  5818. if (webkit && mac && cm.display.currentWheelTarget == node)
  5819. { node.style.display = "none"; }
  5820. else
  5821. { node.parentNode.removeChild(node); }
  5822. return next
  5823. }
  5824. var view = display.view, lineN = display.viewFrom;
  5825. // Loop over the elements in the view, syncing cur (the DOM nodes
  5826. // in display.lineDiv) with the view as we go.
  5827. for (var i = 0; i < view.length; i++) {
  5828. var lineView = view[i];
  5829. if (lineView.hidden) {
  5830. } else if (!lineView.node || lineView.node.parentNode != container) { // Not drawn yet
  5831. var node = buildLineElement(cm, lineView, lineN, dims);
  5832. container.insertBefore(node, cur);
  5833. } else { // Already drawn
  5834. while (cur != lineView.node) { cur = rm(cur); }
  5835. var updateNumber = lineNumbers && updateNumbersFrom != null &&
  5836. updateNumbersFrom <= lineN && lineView.lineNumber;
  5837. if (lineView.changes) {
  5838. if (indexOf(lineView.changes, "gutter") > -1) { updateNumber = false; }
  5839. updateLineForChanges(cm, lineView, lineN, dims);
  5840. }
  5841. if (updateNumber) {
  5842. removeChildren(lineView.lineNumber);
  5843. lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN)));
  5844. }
  5845. cur = lineView.node.nextSibling;
  5846. }
  5847. lineN += lineView.size;
  5848. }
  5849. while (cur) { cur = rm(cur); }
  5850. }
  5851. function updateGutterSpace(cm) {
  5852. var width = cm.display.gutters.offsetWidth;
  5853. cm.display.sizer.style.marginLeft = width + "px";
  5854. }
  5855. function setDocumentHeight(cm, measure) {
  5856. cm.display.sizer.style.minHeight = measure.docHeight + "px";
  5857. cm.display.heightForcer.style.top = measure.docHeight + "px";
  5858. cm.display.gutters.style.height = (measure.docHeight + cm.display.barHeight + scrollGap(cm)) + "px";
  5859. }
  5860. // Rebuild the gutter elements, ensure the margin to the left of the
  5861. // code matches their width.
  5862. function updateGutters(cm) {
  5863. var gutters = cm.display.gutters, specs = cm.options.gutters;
  5864. removeChildren(gutters);
  5865. var i = 0;
  5866. for (; i < specs.length; ++i) {
  5867. var gutterClass = specs[i];
  5868. var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + gutterClass));
  5869. if (gutterClass == "CodeMirror-linenumbers") {
  5870. cm.display.lineGutter = gElt;
  5871. gElt.style.width = (cm.display.lineNumWidth || 1) + "px";
  5872. }
  5873. }
  5874. gutters.style.display = i ? "" : "none";
  5875. updateGutterSpace(cm);
  5876. }
  5877. // Make sure the gutters options contains the element
  5878. // "CodeMirror-linenumbers" when the lineNumbers option is true.
  5879. function setGuttersForLineNumbers(options) {
  5880. var found = indexOf(options.gutters, "CodeMirror-linenumbers");
  5881. if (found == -1 && options.lineNumbers) {
  5882. options.gutters = options.gutters.concat(["CodeMirror-linenumbers"]);
  5883. } else if (found > -1 && !options.lineNumbers) {
  5884. options.gutters = options.gutters.slice(0);
  5885. options.gutters.splice(found, 1);
  5886. }
  5887. }
  5888. // Since the delta values reported on mouse wheel events are
  5889. // unstandardized between browsers and even browser versions, and
  5890. // generally horribly unpredictable, this code starts by measuring
  5891. // the scroll effect that the first few mouse wheel events have,
  5892. // and, from that, detects the way it can convert deltas to pixel
  5893. // offsets afterwards.
  5894. //
  5895. // The reason we want to know the amount a wheel event will scroll
  5896. // is that it gives us a chance to update the display before the
  5897. // actual scrolling happens, reducing flickering.
  5898. var wheelSamples = 0;
  5899. var wheelPixelsPerUnit = null;
  5900. // Fill in a browser-detected starting value on browsers where we
  5901. // know one. These don't have to be accurate -- the result of them
  5902. // being wrong would just be a slight flicker on the first wheel
  5903. // scroll (if it is large enough).
  5904. if (ie) { wheelPixelsPerUnit = -.53; }
  5905. else if (gecko) { wheelPixelsPerUnit = 15; }
  5906. else if (chrome) { wheelPixelsPerUnit = -.7; }
  5907. else if (safari) { wheelPixelsPerUnit = -1/3; }
  5908. function wheelEventDelta(e) {
  5909. var dx = e.wheelDeltaX, dy = e.wheelDeltaY;
  5910. if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) { dx = e.detail; }
  5911. if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) { dy = e.detail; }
  5912. else if (dy == null) { dy = e.wheelDelta; }
  5913. return {x: dx, y: dy}
  5914. }
  5915. function wheelEventPixels(e) {
  5916. var delta = wheelEventDelta(e);
  5917. delta.x *= wheelPixelsPerUnit;
  5918. delta.y *= wheelPixelsPerUnit;
  5919. return delta
  5920. }
  5921. function onScrollWheel(cm, e) {
  5922. var delta = wheelEventDelta(e), dx = delta.x, dy = delta.y;
  5923. var display = cm.display, scroll = display.scroller;
  5924. // Quit if there's nothing to scroll here
  5925. var canScrollX = scroll.scrollWidth > scroll.clientWidth;
  5926. var canScrollY = scroll.scrollHeight > scroll.clientHeight;
  5927. if (!(dx && canScrollX || dy && canScrollY)) { return }
  5928. // Webkit browsers on OS X abort momentum scrolls when the target
  5929. // of the scroll event is removed from the scrollable element.
  5930. // This hack (see related code in patchDisplay) makes sure the
  5931. // element is kept around.
  5932. if (dy && mac && webkit) {
  5933. outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) {
  5934. for (var i = 0; i < view.length; i++) {
  5935. if (view[i].node == cur) {
  5936. cm.display.currentWheelTarget = cur;
  5937. break outer
  5938. }
  5939. }
  5940. }
  5941. }
  5942. // On some browsers, horizontal scrolling will cause redraws to
  5943. // happen before the gutter has been realigned, causing it to
  5944. // wriggle around in a most unseemly way. When we have an
  5945. // estimated pixels/delta value, we just handle horizontal
  5946. // scrolling entirely here. It'll be slightly off from native, but
  5947. // better than glitching out.
  5948. if (dx && !gecko && !presto && wheelPixelsPerUnit != null) {
  5949. if (dy && canScrollY)
  5950. { updateScrollTop(cm, Math.max(0, scroll.scrollTop + dy * wheelPixelsPerUnit)); }
  5951. setScrollLeft(cm, Math.max(0, scroll.scrollLeft + dx * wheelPixelsPerUnit));
  5952. // Only prevent default scrolling if vertical scrolling is
  5953. // actually possible. Otherwise, it causes vertical scroll
  5954. // jitter on OSX trackpads when deltaX is small and deltaY
  5955. // is large (issue #3579)
  5956. if (!dy || (dy && canScrollY))
  5957. { e_preventDefault(e); }
  5958. display.wheelStartX = null; // Abort measurement, if in progress
  5959. return
  5960. }
  5961. // 'Project' the visible viewport to cover the area that is being
  5962. // scrolled into view (if we know enough to estimate it).
  5963. if (dy && wheelPixelsPerUnit != null) {
  5964. var pixels = dy * wheelPixelsPerUnit;
  5965. var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight;
  5966. if (pixels < 0) { top = Math.max(0, top + pixels - 50); }
  5967. else { bot = Math.min(cm.doc.height, bot + pixels + 50); }
  5968. updateDisplaySimple(cm, {top: top, bottom: bot});
  5969. }
  5970. if (wheelSamples < 20) {
  5971. if (display.wheelStartX == null) {
  5972. display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop;
  5973. display.wheelDX = dx; display.wheelDY = dy;
  5974. setTimeout(function () {
  5975. if (display.wheelStartX == null) { return }
  5976. var movedX = scroll.scrollLeft - display.wheelStartX;
  5977. var movedY = scroll.scrollTop - display.wheelStartY;
  5978. var sample = (movedY && display.wheelDY && movedY / display.wheelDY) ||
  5979. (movedX && display.wheelDX && movedX / display.wheelDX);
  5980. display.wheelStartX = display.wheelStartY = null;
  5981. if (!sample) { return }
  5982. wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1);
  5983. ++wheelSamples;
  5984. }, 200);
  5985. } else {
  5986. display.wheelDX += dx; display.wheelDY += dy;
  5987. }
  5988. }
  5989. }
  5990. // Selection objects are immutable. A new one is created every time
  5991. // the selection changes. A selection is one or more non-overlapping
  5992. // (and non-touching) ranges, sorted, and an integer that indicates
  5993. // which one is the primary selection (the one that's scrolled into
  5994. // view, that getCursor returns, etc).
  5995. var Selection = function(ranges, primIndex) {
  5996. this.ranges = ranges;
  5997. this.primIndex = primIndex;
  5998. };
  5999. Selection.prototype.primary = function () { return this.ranges[this.primIndex] };
  6000. Selection.prototype.equals = function (other) {
  6001. var this$1 = this;
  6002. if (other == this) { return true }
  6003. if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) { return false }
  6004. for (var i = 0; i < this.ranges.length; i++) {
  6005. var here = this$1.ranges[i], there = other.ranges[i];
  6006. if (!equalCursorPos(here.anchor, there.anchor) || !equalCursorPos(here.head, there.head)) { return false }
  6007. }
  6008. return true
  6009. };
  6010. Selection.prototype.deepCopy = function () {
  6011. var this$1 = this;
  6012. var out = [];
  6013. for (var i = 0; i < this.ranges.length; i++)
  6014. { out[i] = new Range(copyPos(this$1.ranges[i].anchor), copyPos(this$1.ranges[i].head)); }
  6015. return new Selection(out, this.primIndex)
  6016. };
  6017. Selection.prototype.somethingSelected = function () {
  6018. var this$1 = this;
  6019. for (var i = 0; i < this.ranges.length; i++)
  6020. { if (!this$1.ranges[i].empty()) { return true } }
  6021. return false
  6022. };
  6023. Selection.prototype.contains = function (pos, end) {
  6024. var this$1 = this;
  6025. if (!end) { end = pos; }
  6026. for (var i = 0; i < this.ranges.length; i++) {
  6027. var range = this$1.ranges[i];
  6028. if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0)
  6029. { return i }
  6030. }
  6031. return -1
  6032. };
  6033. var Range = function(anchor, head) {
  6034. this.anchor = anchor; this.head = head;
  6035. };
  6036. Range.prototype.from = function () { return minPos(this.anchor, this.head) };
  6037. Range.prototype.to = function () { return maxPos(this.anchor, this.head) };
  6038. Range.prototype.empty = function () { return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch };
  6039. // Take an unsorted, potentially overlapping set of ranges, and
  6040. // build a selection out of it. 'Consumes' ranges array (modifying
  6041. // it).
  6042. function normalizeSelection(ranges, primIndex) {
  6043. var prim = ranges[primIndex];
  6044. ranges.sort(function (a, b) { return cmp(a.from(), b.from()); });
  6045. primIndex = indexOf(ranges, prim);
  6046. for (var i = 1; i < ranges.length; i++) {
  6047. var cur = ranges[i], prev = ranges[i - 1];
  6048. if (cmp(prev.to(), cur.from()) >= 0) {
  6049. var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to());
  6050. var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head;
  6051. if (i <= primIndex) { --primIndex; }
  6052. ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to));
  6053. }
  6054. }
  6055. return new Selection(ranges, primIndex)
  6056. }
  6057. function simpleSelection(anchor, head) {
  6058. return new Selection([new Range(anchor, head || anchor)], 0)
  6059. }
  6060. // Compute the position of the end of a change (its 'to' property
  6061. // refers to the pre-change end).
  6062. function changeEnd(change) {
  6063. if (!change.text) { return change.to }
  6064. return Pos(change.from.line + change.text.length - 1,
  6065. lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0))
  6066. }
  6067. // Adjust a position to refer to the post-change position of the
  6068. // same text, or the end of the change if the change covers it.
  6069. function adjustForChange(pos, change) {
  6070. if (cmp(pos, change.from) < 0) { return pos }
  6071. if (cmp(pos, change.to) <= 0) { return changeEnd(change) }
  6072. var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch;
  6073. if (pos.line == change.to.line) { ch += changeEnd(change).ch - change.to.ch; }
  6074. return Pos(line, ch)
  6075. }
  6076. function computeSelAfterChange(doc, change) {
  6077. var out = [];
  6078. for (var i = 0; i < doc.sel.ranges.length; i++) {
  6079. var range = doc.sel.ranges[i];
  6080. out.push(new Range(adjustForChange(range.anchor, change),
  6081. adjustForChange(range.head, change)));
  6082. }
  6083. return normalizeSelection(out, doc.sel.primIndex)
  6084. }
  6085. function offsetPos(pos, old, nw) {
  6086. if (pos.line == old.line)
  6087. { return Pos(nw.line, pos.ch - old.ch + nw.ch) }
  6088. else
  6089. { return Pos(nw.line + (pos.line - old.line), pos.ch) }
  6090. }
  6091. // Used by replaceSelections to allow moving the selection to the
  6092. // start or around the replaced test. Hint may be "start" or "around".
  6093. function computeReplacedSel(doc, changes, hint) {
  6094. var out = [];
  6095. var oldPrev = Pos(doc.first, 0), newPrev = oldPrev;
  6096. for (var i = 0; i < changes.length; i++) {
  6097. var change = changes[i];
  6098. var from = offsetPos(change.from, oldPrev, newPrev);
  6099. var to = offsetPos(changeEnd(change), oldPrev, newPrev);
  6100. oldPrev = change.to;
  6101. newPrev = to;
  6102. if (hint == "around") {
  6103. var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) < 0;
  6104. out[i] = new Range(inv ? to : from, inv ? from : to);
  6105. } else {
  6106. out[i] = new Range(from, from);
  6107. }
  6108. }
  6109. return new Selection(out, doc.sel.primIndex)
  6110. }
  6111. // Used to get the editor into a consistent state again when options change.
  6112. function loadMode(cm) {
  6113. cm.doc.mode = getMode(cm.options, cm.doc.modeOption);
  6114. resetModeState(cm);
  6115. }
  6116. function resetModeState(cm) {
  6117. cm.doc.iter(function (line) {
  6118. if (line.stateAfter) { line.stateAfter = null; }
  6119. if (line.styles) { line.styles = null; }
  6120. });
  6121. cm.doc.modeFrontier = cm.doc.highlightFrontier = cm.doc.first;
  6122. startWorker(cm, 100);
  6123. cm.state.modeGen++;
  6124. if (cm.curOp) { regChange(cm); }
  6125. }
  6126. // DOCUMENT DATA STRUCTURE
  6127. // By default, updates that start and end at the beginning of a line
  6128. // are treated specially, in order to make the association of line
  6129. // widgets and marker elements with the text behave more intuitive.
  6130. function isWholeLineUpdate(doc, change) {
  6131. return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" &&
  6132. (!doc.cm || doc.cm.options.wholeLineUpdateBefore)
  6133. }
  6134. // Perform a change on the document data structure.
  6135. function updateDoc(doc, change, markedSpans, estimateHeight$$1) {
  6136. function spansFor(n) {return markedSpans ? markedSpans[n] : null}
  6137. function update(line, text, spans) {
  6138. updateLine(line, text, spans, estimateHeight$$1);
  6139. signalLater(line, "change", line, change);
  6140. }
  6141. function linesFor(start, end) {
  6142. var result = [];
  6143. for (var i = start; i < end; ++i)
  6144. { result.push(new Line(text[i], spansFor(i), estimateHeight$$1)); }
  6145. return result
  6146. }
  6147. var from = change.from, to = change.to, text = change.text;
  6148. var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line);
  6149. var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line;
  6150. // Adjust the line structure
  6151. if (change.full) {
  6152. doc.insert(0, linesFor(0, text.length));
  6153. doc.remove(text.length, doc.size - text.length);
  6154. } else if (isWholeLineUpdate(doc, change)) {
  6155. // This is a whole-line replace. Treated specially to make
  6156. // sure line objects move the way they are supposed to.
  6157. var added = linesFor(0, text.length - 1);
  6158. update(lastLine, lastLine.text, lastSpans);
  6159. if (nlines) { doc.remove(from.line, nlines); }
  6160. if (added.length) { doc.insert(from.line, added); }
  6161. } else if (firstLine == lastLine) {
  6162. if (text.length == 1) {
  6163. update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans);
  6164. } else {
  6165. var added$1 = linesFor(1, text.length - 1);
  6166. added$1.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight$$1));
  6167. update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
  6168. doc.insert(from.line + 1, added$1);
  6169. }
  6170. } else if (text.length == 1) {
  6171. update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0));
  6172. doc.remove(from.line + 1, nlines);
  6173. } else {
  6174. update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
  6175. update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans);
  6176. var added$2 = linesFor(1, text.length - 1);
  6177. if (nlines > 1) { doc.remove(from.line + 1, nlines - 1); }
  6178. doc.insert(from.line + 1, added$2);
  6179. }
  6180. signalLater(doc, "change", doc, change);
  6181. }
  6182. // Call f for all linked documents.
  6183. function linkedDocs(doc, f, sharedHistOnly) {
  6184. function propagate(doc, skip, sharedHist) {
  6185. if (doc.linked) { for (var i = 0; i < doc.linked.length; ++i) {
  6186. var rel = doc.linked[i];
  6187. if (rel.doc == skip) { continue }
  6188. var shared = sharedHist && rel.sharedHist;
  6189. if (sharedHistOnly && !shared) { continue }
  6190. f(rel.doc, shared);
  6191. propagate(rel.doc, doc, shared);
  6192. } }
  6193. }
  6194. propagate(doc, null, true);
  6195. }
  6196. // Attach a document to an editor.
  6197. function attachDoc(cm, doc) {
  6198. if (doc.cm) { throw new Error("This document is already in use.") }
  6199. cm.doc = doc;
  6200. doc.cm = cm;
  6201. estimateLineHeights(cm);
  6202. loadMode(cm);
  6203. setDirectionClass(cm);
  6204. if (!cm.options.lineWrapping) { findMaxLine(cm); }
  6205. cm.options.mode = doc.modeOption;
  6206. regChange(cm);
  6207. }
  6208. function setDirectionClass(cm) {
  6209. (cm.doc.direction == "rtl" ? addClass : rmClass)(cm.display.lineDiv, "CodeMirror-rtl");
  6210. }
  6211. function directionChanged(cm) {
  6212. runInOp(cm, function () {
  6213. setDirectionClass(cm);
  6214. regChange(cm);
  6215. });
  6216. }
  6217. function History(startGen) {
  6218. // Arrays of change events and selections. Doing something adds an
  6219. // event to done and clears undo. Undoing moves events from done
  6220. // to undone, redoing moves them in the other direction.
  6221. this.done = []; this.undone = [];
  6222. this.undoDepth = Infinity;
  6223. // Used to track when changes can be merged into a single undo
  6224. // event
  6225. this.lastModTime = this.lastSelTime = 0;
  6226. this.lastOp = this.lastSelOp = null;
  6227. this.lastOrigin = this.lastSelOrigin = null;
  6228. // Used by the isClean() method
  6229. this.generation = this.maxGeneration = startGen || 1;
  6230. }
  6231. // Create a history change event from an updateDoc-style change
  6232. // object.
  6233. function historyChangeFromChange(doc, change) {
  6234. var histChange = {from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to)};
  6235. attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);
  6236. linkedDocs(doc, function (doc) { return attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1); }, true);
  6237. return histChange
  6238. }
  6239. // Pop all selection events off the end of a history array. Stop at
  6240. // a change event.
  6241. function clearSelectionEvents(array) {
  6242. while (array.length) {
  6243. var last = lst(array);
  6244. if (last.ranges) { array.pop(); }
  6245. else { break }
  6246. }
  6247. }
  6248. // Find the top change event in the history. Pop off selection
  6249. // events that are in the way.
  6250. function lastChangeEvent(hist, force) {
  6251. if (force) {
  6252. clearSelectionEvents(hist.done);
  6253. return lst(hist.done)
  6254. } else if (hist.done.length && !lst(hist.done).ranges) {
  6255. return lst(hist.done)
  6256. } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) {
  6257. hist.done.pop();
  6258. return lst(hist.done)
  6259. }
  6260. }
  6261. // Register a change in the history. Merges changes that are within
  6262. // a single operation, or are close together with an origin that
  6263. // allows merging (starting with "+") into a single event.
  6264. function addChangeToHistory(doc, change, selAfter, opId) {
  6265. var hist = doc.history;
  6266. hist.undone.length = 0;
  6267. var time = +new Date, cur;
  6268. var last;
  6269. if ((hist.lastOp == opId ||
  6270. hist.lastOrigin == change.origin && change.origin &&
  6271. ((change.origin.charAt(0) == "+" && doc.cm && hist.lastModTime > time - doc.cm.options.historyEventDelay) ||
  6272. change.origin.charAt(0) == "*")) &&
  6273. (cur = lastChangeEvent(hist, hist.lastOp == opId))) {
  6274. // Merge this change into the last event
  6275. last = lst(cur.changes);
  6276. if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) {
  6277. // Optimized case for simple insertion -- don't want to add
  6278. // new changesets for every character typed
  6279. last.to = changeEnd(change);
  6280. } else {
  6281. // Add new sub-event
  6282. cur.changes.push(historyChangeFromChange(doc, change));
  6283. }
  6284. } else {
  6285. // Can not be merged, start a new event.
  6286. var before = lst(hist.done);
  6287. if (!before || !before.ranges)
  6288. { pushSelectionToHistory(doc.sel, hist.done); }
  6289. cur = {changes: [historyChangeFromChange(doc, change)],
  6290. generation: hist.generation};
  6291. hist.done.push(cur);
  6292. while (hist.done.length > hist.undoDepth) {
  6293. hist.done.shift();
  6294. if (!hist.done[0].ranges) { hist.done.shift(); }
  6295. }
  6296. }
  6297. hist.done.push(selAfter);
  6298. hist.generation = ++hist.maxGeneration;
  6299. hist.lastModTime = hist.lastSelTime = time;
  6300. hist.lastOp = hist.lastSelOp = opId;
  6301. hist.lastOrigin = hist.lastSelOrigin = change.origin;
  6302. if (!last) { signal(doc, "historyAdded"); }
  6303. }
  6304. function selectionEventCanBeMerged(doc, origin, prev, sel) {
  6305. var ch = origin.charAt(0);
  6306. return ch == "*" ||
  6307. ch == "+" &&
  6308. prev.ranges.length == sel.ranges.length &&
  6309. prev.somethingSelected() == sel.somethingSelected() &&
  6310. new Date - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500)
  6311. }
  6312. // Called whenever the selection changes, sets the new selection as
  6313. // the pending selection in the history, and pushes the old pending
  6314. // selection into the 'done' array when it was significantly
  6315. // different (in number of selected ranges, emptiness, or time).
  6316. function addSelectionToHistory(doc, sel, opId, options) {
  6317. var hist = doc.history, origin = options && options.origin;
  6318. // A new event is started when the previous origin does not match
  6319. // the current, or the origins don't allow matching. Origins
  6320. // starting with * are always merged, those starting with + are
  6321. // merged when similar and close together in time.
  6322. if (opId == hist.lastSelOp ||
  6323. (origin && hist.lastSelOrigin == origin &&
  6324. (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin ||
  6325. selectionEventCanBeMerged(doc, origin, lst(hist.done), sel))))
  6326. { hist.done[hist.done.length - 1] = sel; }
  6327. else
  6328. { pushSelectionToHistory(sel, hist.done); }
  6329. hist.lastSelTime = +new Date;
  6330. hist.lastSelOrigin = origin;
  6331. hist.lastSelOp = opId;
  6332. if (options && options.clearRedo !== false)
  6333. { clearSelectionEvents(hist.undone); }
  6334. }
  6335. function pushSelectionToHistory(sel, dest) {
  6336. var top = lst(dest);
  6337. if (!(top && top.ranges && top.equals(sel)))
  6338. { dest.push(sel); }
  6339. }
  6340. // Used to store marked span information in the history.
  6341. function attachLocalSpans(doc, change, from, to) {
  6342. var existing = change["spans_" + doc.id], n = 0;
  6343. doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function (line) {
  6344. if (line.markedSpans)
  6345. { (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans; }
  6346. ++n;
  6347. });
  6348. }
  6349. // When un/re-doing restores text containing marked spans, those
  6350. // that have been explicitly cleared should not be restored.
  6351. function removeClearedSpans(spans) {
  6352. if (!spans) { return null }
  6353. var out;
  6354. for (var i = 0; i < spans.length; ++i) {
  6355. if (spans[i].marker.explicitlyCleared) { if (!out) { out = spans.slice(0, i); } }
  6356. else if (out) { out.push(spans[i]); }
  6357. }
  6358. return !out ? spans : out.length ? out : null
  6359. }
  6360. // Retrieve and filter the old marked spans stored in a change event.
  6361. function getOldSpans(doc, change) {
  6362. var found = change["spans_" + doc.id];
  6363. if (!found) { return null }
  6364. var nw = [];
  6365. for (var i = 0; i < change.text.length; ++i)
  6366. { nw.push(removeClearedSpans(found[i])); }
  6367. return nw
  6368. }
  6369. // Used for un/re-doing changes from the history. Combines the
  6370. // result of computing the existing spans with the set of spans that
  6371. // existed in the history (so that deleting around a span and then
  6372. // undoing brings back the span).
  6373. function mergeOldSpans(doc, change) {
  6374. var old = getOldSpans(doc, change);
  6375. var stretched = stretchSpansOverChange(doc, change);
  6376. if (!old) { return stretched }
  6377. if (!stretched) { return old }
  6378. for (var i = 0; i < old.length; ++i) {
  6379. var oldCur = old[i], stretchCur = stretched[i];
  6380. if (oldCur && stretchCur) {
  6381. spans: for (var j = 0; j < stretchCur.length; ++j) {
  6382. var span = stretchCur[j];
  6383. for (var k = 0; k < oldCur.length; ++k)
  6384. { if (oldCur[k].marker == span.marker) { continue spans } }
  6385. oldCur.push(span);
  6386. }
  6387. } else if (stretchCur) {
  6388. old[i] = stretchCur;
  6389. }
  6390. }
  6391. return old
  6392. }
  6393. // Used both to provide a JSON-safe object in .getHistory, and, when
  6394. // detaching a document, to split the history in two
  6395. function copyHistoryArray(events, newGroup, instantiateSel) {
  6396. var copy = [];
  6397. for (var i = 0; i < events.length; ++i) {
  6398. var event = events[i];
  6399. if (event.ranges) {
  6400. copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event);
  6401. continue
  6402. }
  6403. var changes = event.changes, newChanges = [];
  6404. copy.push({changes: newChanges});
  6405. for (var j = 0; j < changes.length; ++j) {
  6406. var change = changes[j], m = (void 0);
  6407. newChanges.push({from: change.from, to: change.to, text: change.text});
  6408. if (newGroup) { for (var prop in change) { if (m = prop.match(/^spans_(\d+)$/)) {
  6409. if (indexOf(newGroup, Number(m[1])) > -1) {
  6410. lst(newChanges)[prop] = change[prop];
  6411. delete change[prop];
  6412. }
  6413. } } }
  6414. }
  6415. }
  6416. return copy
  6417. }
  6418. // The 'scroll' parameter given to many of these indicated whether
  6419. // the new cursor position should be scrolled into view after
  6420. // modifying the selection.
  6421. // If shift is held or the extend flag is set, extends a range to
  6422. // include a given position (and optionally a second position).
  6423. // Otherwise, simply returns the range between the given positions.
  6424. // Used for cursor motion and such.
  6425. function extendRange(range, head, other, extend) {
  6426. if (extend) {
  6427. var anchor = range.anchor;
  6428. if (other) {
  6429. var posBefore = cmp(head, anchor) < 0;
  6430. if (posBefore != (cmp(other, anchor) < 0)) {
  6431. anchor = head;
  6432. head = other;
  6433. } else if (posBefore != (cmp(head, other) < 0)) {
  6434. head = other;
  6435. }
  6436. }
  6437. return new Range(anchor, head)
  6438. } else {
  6439. return new Range(other || head, head)
  6440. }
  6441. }
  6442. // Extend the primary selection range, discard the rest.
  6443. function extendSelection(doc, head, other, options, extend) {
  6444. if (extend == null) { extend = doc.cm && (doc.cm.display.shift || doc.extend); }
  6445. setSelection(doc, new Selection([extendRange(doc.sel.primary(), head, other, extend)], 0), options);
  6446. }
  6447. // Extend all selections (pos is an array of selections with length
  6448. // equal the number of selections)
  6449. function extendSelections(doc, heads, options) {
  6450. var out = [];
  6451. var extend = doc.cm && (doc.cm.display.shift || doc.extend);
  6452. for (var i = 0; i < doc.sel.ranges.length; i++)
  6453. { out[i] = extendRange(doc.sel.ranges[i], heads[i], null, extend); }
  6454. var newSel = normalizeSelection(out, doc.sel.primIndex);
  6455. setSelection(doc, newSel, options);
  6456. }
  6457. // Updates a single range in the selection.
  6458. function replaceOneSelection(doc, i, range, options) {
  6459. var ranges = doc.sel.ranges.slice(0);
  6460. ranges[i] = range;
  6461. setSelection(doc, normalizeSelection(ranges, doc.sel.primIndex), options);
  6462. }
  6463. // Reset the selection to a single range.
  6464. function setSimpleSelection(doc, anchor, head, options) {
  6465. setSelection(doc, simpleSelection(anchor, head), options);
  6466. }
  6467. // Give beforeSelectionChange handlers a change to influence a
  6468. // selection update.
  6469. function filterSelectionChange(doc, sel, options) {
  6470. var obj = {
  6471. ranges: sel.ranges,
  6472. update: function(ranges) {
  6473. var this$1 = this;
  6474. this.ranges = [];
  6475. for (var i = 0; i < ranges.length; i++)
  6476. { this$1.ranges[i] = new Range(clipPos(doc, ranges[i].anchor),
  6477. clipPos(doc, ranges[i].head)); }
  6478. },
  6479. origin: options && options.origin
  6480. };
  6481. signal(doc, "beforeSelectionChange", doc, obj);
  6482. if (doc.cm) { signal(doc.cm, "beforeSelectionChange", doc.cm, obj); }
  6483. if (obj.ranges != sel.ranges) { return normalizeSelection(obj.ranges, obj.ranges.length - 1) }
  6484. else { return sel }
  6485. }
  6486. function setSelectionReplaceHistory(doc, sel, options) {
  6487. var done = doc.history.done, last = lst(done);
  6488. if (last && last.ranges) {
  6489. done[done.length - 1] = sel;
  6490. setSelectionNoUndo(doc, sel, options);
  6491. } else {
  6492. setSelection(doc, sel, options);
  6493. }
  6494. }
  6495. // Set a new selection.
  6496. function setSelection(doc, sel, options) {
  6497. setSelectionNoUndo(doc, sel, options);
  6498. addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options);
  6499. }
  6500. function setSelectionNoUndo(doc, sel, options) {
  6501. if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange"))
  6502. { sel = filterSelectionChange(doc, sel, options); }
  6503. var bias = options && options.bias ||
  6504. (cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1);
  6505. setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true));
  6506. if (!(options && options.scroll === false) && doc.cm)
  6507. { ensureCursorVisible(doc.cm); }
  6508. }
  6509. function setSelectionInner(doc, sel) {
  6510. if (sel.equals(doc.sel)) { return }
  6511. doc.sel = sel;
  6512. if (doc.cm) {
  6513. doc.cm.curOp.updateInput = doc.cm.curOp.selectionChanged = true;
  6514. signalCursorActivity(doc.cm);
  6515. }
  6516. signalLater(doc, "cursorActivity", doc);
  6517. }
  6518. // Verify that the selection does not partially select any atomic
  6519. // marked ranges.
  6520. function reCheckSelection(doc) {
  6521. setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false));
  6522. }
  6523. // Return a selection that does not partially select any atomic
  6524. // ranges.
  6525. function skipAtomicInSelection(doc, sel, bias, mayClear) {
  6526. var out;
  6527. for (var i = 0; i < sel.ranges.length; i++) {
  6528. var range = sel.ranges[i];
  6529. var old = sel.ranges.length == doc.sel.ranges.length && doc.sel.ranges[i];
  6530. var newAnchor = skipAtomic(doc, range.anchor, old && old.anchor, bias, mayClear);
  6531. var newHead = skipAtomic(doc, range.head, old && old.head, bias, mayClear);
  6532. if (out || newAnchor != range.anchor || newHead != range.head) {
  6533. if (!out) { out = sel.ranges.slice(0, i); }
  6534. out[i] = new Range(newAnchor, newHead);
  6535. }
  6536. }
  6537. return out ? normalizeSelection(out, sel.primIndex) : sel
  6538. }
  6539. function skipAtomicInner(doc, pos, oldPos, dir, mayClear) {
  6540. var line = getLine(doc, pos.line);
  6541. if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) {
  6542. var sp = line.markedSpans[i], m = sp.marker;
  6543. if ((sp.from == null || (m.inclusiveLeft ? sp.from <= pos.ch : sp.from < pos.ch)) &&
  6544. (sp.to == null || (m.inclusiveRight ? sp.to >= pos.ch : sp.to > pos.ch))) {
  6545. if (mayClear) {
  6546. signal(m, "beforeCursorEnter");
  6547. if (m.explicitlyCleared) {
  6548. if (!line.markedSpans) { break }
  6549. else {--i; continue}
  6550. }
  6551. }
  6552. if (!m.atomic) { continue }
  6553. if (oldPos) {
  6554. var near = m.find(dir < 0 ? 1 : -1), diff = (void 0);
  6555. if (dir < 0 ? m.inclusiveRight : m.inclusiveLeft)
  6556. { near = movePos(doc, near, -dir, near && near.line == pos.line ? line : null); }
  6557. if (near && near.line == pos.line && (diff = cmp(near, oldPos)) && (dir < 0 ? diff < 0 : diff > 0))
  6558. { return skipAtomicInner(doc, near, pos, dir, mayClear) }
  6559. }
  6560. var far = m.find(dir < 0 ? -1 : 1);
  6561. if (dir < 0 ? m.inclusiveLeft : m.inclusiveRight)
  6562. { far = movePos(doc, far, dir, far.line == pos.line ? line : null); }
  6563. return far ? skipAtomicInner(doc, far, pos, dir, mayClear) : null
  6564. }
  6565. } }
  6566. return pos
  6567. }
  6568. // Ensure a given position is not inside an atomic range.
  6569. function skipAtomic(doc, pos, oldPos, bias, mayClear) {
  6570. var dir = bias || 1;
  6571. var found = skipAtomicInner(doc, pos, oldPos, dir, mayClear) ||
  6572. (!mayClear && skipAtomicInner(doc, pos, oldPos, dir, true)) ||
  6573. skipAtomicInner(doc, pos, oldPos, -dir, mayClear) ||
  6574. (!mayClear && skipAtomicInner(doc, pos, oldPos, -dir, true));
  6575. if (!found) {
  6576. doc.cantEdit = true;
  6577. return Pos(doc.first, 0)
  6578. }
  6579. return found
  6580. }
  6581. function movePos(doc, pos, dir, line) {
  6582. if (dir < 0 && pos.ch == 0) {
  6583. if (pos.line > doc.first) { return clipPos(doc, Pos(pos.line - 1)) }
  6584. else { return null }
  6585. } else if (dir > 0 && pos.ch == (line || getLine(doc, pos.line)).text.length) {
  6586. if (pos.line < doc.first + doc.size - 1) { return Pos(pos.line + 1, 0) }
  6587. else { return null }
  6588. } else {
  6589. return new Pos(pos.line, pos.ch + dir)
  6590. }
  6591. }
  6592. function selectAll(cm) {
  6593. cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll);
  6594. }
  6595. // UPDATING
  6596. // Allow "beforeChange" event handlers to influence a change
  6597. function filterChange(doc, change, update) {
  6598. var obj = {
  6599. canceled: false,
  6600. from: change.from,
  6601. to: change.to,
  6602. text: change.text,
  6603. origin: change.origin,
  6604. cancel: function () { return obj.canceled = true; }
  6605. };
  6606. if (update) { obj.update = function (from, to, text, origin) {
  6607. if (from) { obj.from = clipPos(doc, from); }
  6608. if (to) { obj.to = clipPos(doc, to); }
  6609. if (text) { obj.text = text; }
  6610. if (origin !== undefined) { obj.origin = origin; }
  6611. }; }
  6612. signal(doc, "beforeChange", doc, obj);
  6613. if (doc.cm) { signal(doc.cm, "beforeChange", doc.cm, obj); }
  6614. if (obj.canceled) { return null }
  6615. return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin}
  6616. }
  6617. // Apply a change to a document, and add it to the document's
  6618. // history, and propagating it to all linked documents.
  6619. function makeChange(doc, change, ignoreReadOnly) {
  6620. if (doc.cm) {
  6621. if (!doc.cm.curOp) { return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly) }
  6622. if (doc.cm.state.suppressEdits) { return }
  6623. }
  6624. if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) {
  6625. change = filterChange(doc, change, true);
  6626. if (!change) { return }
  6627. }
  6628. // Possibly split or suppress the update based on the presence
  6629. // of read-only spans in its range.
  6630. var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to);
  6631. if (split) {
  6632. for (var i = split.length - 1; i >= 0; --i)
  6633. { makeChangeInner(doc, {from: split[i].from, to: split[i].to, text: i ? [""] : change.text, origin: change.origin}); }
  6634. } else {
  6635. makeChangeInner(doc, change);
  6636. }
  6637. }
  6638. function makeChangeInner(doc, change) {
  6639. if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) { return }
  6640. var selAfter = computeSelAfterChange(doc, change);
  6641. addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN);
  6642. makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change));
  6643. var rebased = [];
  6644. linkedDocs(doc, function (doc, sharedHist) {
  6645. if (!sharedHist && indexOf(rebased, doc.history) == -1) {
  6646. rebaseHist(doc.history, change);
  6647. rebased.push(doc.history);
  6648. }
  6649. makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change));
  6650. });
  6651. }
  6652. // Revert a change stored in a document's history.
  6653. function makeChangeFromHistory(doc, type, allowSelectionOnly) {
  6654. if (doc.cm && doc.cm.state.suppressEdits && !allowSelectionOnly) { return }
  6655. var hist = doc.history, event, selAfter = doc.sel;
  6656. var source = type == "undo" ? hist.done : hist.undone, dest = type == "undo" ? hist.undone : hist.done;
  6657. // Verify that there is a useable event (so that ctrl-z won't
  6658. // needlessly clear selection events)
  6659. var i = 0;
  6660. for (; i < source.length; i++) {
  6661. event = source[i];
  6662. if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges)
  6663. { break }
  6664. }
  6665. if (i == source.length) { return }
  6666. hist.lastOrigin = hist.lastSelOrigin = null;
  6667. for (;;) {
  6668. event = source.pop();
  6669. if (event.ranges) {
  6670. pushSelectionToHistory(event, dest);
  6671. if (allowSelectionOnly && !event.equals(doc.sel)) {
  6672. setSelection(doc, event, {clearRedo: false});
  6673. return
  6674. }
  6675. selAfter = event;
  6676. }
  6677. else { break }
  6678. }
  6679. // Build up a reverse change object to add to the opposite history
  6680. // stack (redo when undoing, and vice versa).
  6681. var antiChanges = [];
  6682. pushSelectionToHistory(selAfter, dest);
  6683. dest.push({changes: antiChanges, generation: hist.generation});
  6684. hist.generation = event.generation || ++hist.maxGeneration;
  6685. var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange");
  6686. var loop = function ( i ) {
  6687. var change = event.changes[i];
  6688. change.origin = type;
  6689. if (filter && !filterChange(doc, change, false)) {
  6690. source.length = 0;
  6691. return {}
  6692. }
  6693. antiChanges.push(historyChangeFromChange(doc, change));
  6694. var after = i ? computeSelAfterChange(doc, change) : lst(source);
  6695. makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change));
  6696. if (!i && doc.cm) { doc.cm.scrollIntoView({from: change.from, to: changeEnd(change)}); }
  6697. var rebased = [];
  6698. // Propagate to the linked documents
  6699. linkedDocs(doc, function (doc, sharedHist) {
  6700. if (!sharedHist && indexOf(rebased, doc.history) == -1) {
  6701. rebaseHist(doc.history, change);
  6702. rebased.push(doc.history);
  6703. }
  6704. makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change));
  6705. });
  6706. };
  6707. for (var i$1 = event.changes.length - 1; i$1 >= 0; --i$1) {
  6708. var returned = loop( i$1 );
  6709. if ( returned ) return returned.v;
  6710. }
  6711. }
  6712. // Sub-views need their line numbers shifted when text is added
  6713. // above or below them in the parent document.
  6714. function shiftDoc(doc, distance) {
  6715. if (distance == 0) { return }
  6716. doc.first += distance;
  6717. doc.sel = new Selection(map(doc.sel.ranges, function (range) { return new Range(
  6718. Pos(range.anchor.line + distance, range.anchor.ch),
  6719. Pos(range.head.line + distance, range.head.ch)
  6720. ); }), doc.sel.primIndex);
  6721. if (doc.cm) {
  6722. regChange(doc.cm, doc.first, doc.first - distance, distance);
  6723. for (var d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++)
  6724. { regLineChange(doc.cm, l, "gutter"); }
  6725. }
  6726. }
  6727. // More lower-level change function, handling only a single document
  6728. // (not linked ones).
  6729. function makeChangeSingleDoc(doc, change, selAfter, spans) {
  6730. if (doc.cm && !doc.cm.curOp)
  6731. { return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans) }
  6732. if (change.to.line < doc.first) {
  6733. shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line));
  6734. return
  6735. }
  6736. if (change.from.line > doc.lastLine()) { return }
  6737. // Clip the change to the size of this doc
  6738. if (change.from.line < doc.first) {
  6739. var shift = change.text.length - 1 - (doc.first - change.from.line);
  6740. shiftDoc(doc, shift);
  6741. change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch),
  6742. text: [lst(change.text)], origin: change.origin};
  6743. }
  6744. var last = doc.lastLine();
  6745. if (change.to.line > last) {
  6746. change = {from: change.from, to: Pos(last, getLine(doc, last).text.length),
  6747. text: [change.text[0]], origin: change.origin};
  6748. }
  6749. change.removed = getBetween(doc, change.from, change.to);
  6750. if (!selAfter) { selAfter = computeSelAfterChange(doc, change); }
  6751. if (doc.cm) { makeChangeSingleDocInEditor(doc.cm, change, spans); }
  6752. else { updateDoc(doc, change, spans); }
  6753. setSelectionNoUndo(doc, selAfter, sel_dontScroll);
  6754. }
  6755. // Handle the interaction of a change to a document with the editor
  6756. // that this document is part of.
  6757. function makeChangeSingleDocInEditor(cm, change, spans) {
  6758. var doc = cm.doc, display = cm.display, from = change.from, to = change.to;
  6759. var recomputeMaxLength = false, checkWidthStart = from.line;
  6760. if (!cm.options.lineWrapping) {
  6761. checkWidthStart = lineNo(visualLine(getLine(doc, from.line)));
  6762. doc.iter(checkWidthStart, to.line + 1, function (line) {
  6763. if (line == display.maxLine) {
  6764. recomputeMaxLength = true;
  6765. return true
  6766. }
  6767. });
  6768. }
  6769. if (doc.sel.contains(change.from, change.to) > -1)
  6770. { signalCursorActivity(cm); }
  6771. updateDoc(doc, change, spans, estimateHeight(cm));
  6772. if (!cm.options.lineWrapping) {
  6773. doc.iter(checkWidthStart, from.line + change.text.length, function (line) {
  6774. var len = lineLength(line);
  6775. if (len > display.maxLineLength) {
  6776. display.maxLine = line;
  6777. display.maxLineLength = len;
  6778. display.maxLineChanged = true;
  6779. recomputeMaxLength = false;
  6780. }
  6781. });
  6782. if (recomputeMaxLength) { cm.curOp.updateMaxLine = true; }
  6783. }
  6784. retreatFrontier(doc, from.line);
  6785. startWorker(cm, 400);
  6786. var lendiff = change.text.length - (to.line - from.line) - 1;
  6787. // Remember that these lines changed, for updating the display
  6788. if (change.full)
  6789. { regChange(cm); }
  6790. else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change))
  6791. { regLineChange(cm, from.line, "text"); }
  6792. else
  6793. { regChange(cm, from.line, to.line + 1, lendiff); }
  6794. var changesHandler = hasHandler(cm, "changes"), changeHandler = hasHandler(cm, "change");
  6795. if (changeHandler || changesHandler) {
  6796. var obj = {
  6797. from: from, to: to,
  6798. text: change.text,
  6799. removed: change.removed,
  6800. origin: change.origin
  6801. };
  6802. if (changeHandler) { signalLater(cm, "change", cm, obj); }
  6803. if (changesHandler) { (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj); }
  6804. }
  6805. cm.display.selForContextMenu = null;
  6806. }
  6807. function replaceRange(doc, code, from, to, origin) {
  6808. if (!to) { to = from; }
  6809. if (cmp(to, from) < 0) { var assign;
  6810. (assign = [to, from], from = assign[0], to = assign[1], assign); }
  6811. if (typeof code == "string") { code = doc.splitLines(code); }
  6812. makeChange(doc, {from: from, to: to, text: code, origin: origin});
  6813. }
  6814. // Rebasing/resetting history to deal with externally-sourced changes
  6815. function rebaseHistSelSingle(pos, from, to, diff) {
  6816. if (to < pos.line) {
  6817. pos.line += diff;
  6818. } else if (from < pos.line) {
  6819. pos.line = from;
  6820. pos.ch = 0;
  6821. }
  6822. }
  6823. // Tries to rebase an array of history events given a change in the
  6824. // document. If the change touches the same lines as the event, the
  6825. // event, and everything 'behind' it, is discarded. If the change is
  6826. // before the event, the event's positions are updated. Uses a
  6827. // copy-on-write scheme for the positions, to avoid having to
  6828. // reallocate them all on every rebase, but also avoid problems with
  6829. // shared position objects being unsafely updated.
  6830. function rebaseHistArray(array, from, to, diff) {
  6831. for (var i = 0; i < array.length; ++i) {
  6832. var sub = array[i], ok = true;
  6833. if (sub.ranges) {
  6834. if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true; }
  6835. for (var j = 0; j < sub.ranges.length; j++) {
  6836. rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff);
  6837. rebaseHistSelSingle(sub.ranges[j].head, from, to, diff);
  6838. }
  6839. continue
  6840. }
  6841. for (var j$1 = 0; j$1 < sub.changes.length; ++j$1) {
  6842. var cur = sub.changes[j$1];
  6843. if (to < cur.from.line) {
  6844. cur.from = Pos(cur.from.line + diff, cur.from.ch);
  6845. cur.to = Pos(cur.to.line + diff, cur.to.ch);
  6846. } else if (from <= cur.to.line) {
  6847. ok = false;
  6848. break
  6849. }
  6850. }
  6851. if (!ok) {
  6852. array.splice(0, i + 1);
  6853. i = 0;
  6854. }
  6855. }
  6856. }
  6857. function rebaseHist(hist, change) {
  6858. var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1;
  6859. rebaseHistArray(hist.done, from, to, diff);
  6860. rebaseHistArray(hist.undone, from, to, diff);
  6861. }
  6862. // Utility for applying a change to a line by handle or number,
  6863. // returning the number and optionally registering the line as
  6864. // changed.
  6865. function changeLine(doc, handle, changeType, op) {
  6866. var no = handle, line = handle;
  6867. if (typeof handle == "number") { line = getLine(doc, clipLine(doc, handle)); }
  6868. else { no = lineNo(handle); }
  6869. if (no == null) { return null }
  6870. if (op(line, no) && doc.cm) { regLineChange(doc.cm, no, changeType); }
  6871. return line
  6872. }
  6873. // The document is represented as a BTree consisting of leaves, with
  6874. // chunk of lines in them, and branches, with up to ten leaves or
  6875. // other branch nodes below them. The top node is always a branch
  6876. // node, and is the document object itself (meaning it has
  6877. // additional methods and properties).
  6878. //
  6879. // All nodes have parent links. The tree is used both to go from
  6880. // line numbers to line objects, and to go from objects to numbers.
  6881. // It also indexes by height, and is used to convert between height
  6882. // and line object, and to find the total height of the document.
  6883. //
  6884. // See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html
  6885. function LeafChunk(lines) {
  6886. var this$1 = this;
  6887. this.lines = lines;
  6888. this.parent = null;
  6889. var height = 0;
  6890. for (var i = 0; i < lines.length; ++i) {
  6891. lines[i].parent = this$1;
  6892. height += lines[i].height;
  6893. }
  6894. this.height = height;
  6895. }
  6896. LeafChunk.prototype = {
  6897. chunkSize: function chunkSize() { return this.lines.length },
  6898. // Remove the n lines at offset 'at'.
  6899. removeInner: function removeInner(at, n) {
  6900. var this$1 = this;
  6901. for (var i = at, e = at + n; i < e; ++i) {
  6902. var line = this$1.lines[i];
  6903. this$1.height -= line.height;
  6904. cleanUpLine(line);
  6905. signalLater(line, "delete");
  6906. }
  6907. this.lines.splice(at, n);
  6908. },
  6909. // Helper used to collapse a small branch into a single leaf.
  6910. collapse: function collapse(lines) {
  6911. lines.push.apply(lines, this.lines);
  6912. },
  6913. // Insert the given array of lines at offset 'at', count them as
  6914. // having the given height.
  6915. insertInner: function insertInner(at, lines, height) {
  6916. var this$1 = this;
  6917. this.height += height;
  6918. this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at));
  6919. for (var i = 0; i < lines.length; ++i) { lines[i].parent = this$1; }
  6920. },
  6921. // Used to iterate over a part of the tree.
  6922. iterN: function iterN(at, n, op) {
  6923. var this$1 = this;
  6924. for (var e = at + n; at < e; ++at)
  6925. { if (op(this$1.lines[at])) { return true } }
  6926. }
  6927. };
  6928. function BranchChunk(children) {
  6929. var this$1 = this;
  6930. this.children = children;
  6931. var size = 0, height = 0;
  6932. for (var i = 0; i < children.length; ++i) {
  6933. var ch = children[i];
  6934. size += ch.chunkSize(); height += ch.height;
  6935. ch.parent = this$1;
  6936. }
  6937. this.size = size;
  6938. this.height = height;
  6939. this.parent = null;
  6940. }
  6941. BranchChunk.prototype = {
  6942. chunkSize: function chunkSize() { return this.size },
  6943. removeInner: function removeInner(at, n) {
  6944. var this$1 = this;
  6945. this.size -= n;
  6946. for (var i = 0; i < this.children.length; ++i) {
  6947. var child = this$1.children[i], sz = child.chunkSize();
  6948. if (at < sz) {
  6949. var rm = Math.min(n, sz - at), oldHeight = child.height;
  6950. child.removeInner(at, rm);
  6951. this$1.height -= oldHeight - child.height;
  6952. if (sz == rm) { this$1.children.splice(i--, 1); child.parent = null; }
  6953. if ((n -= rm) == 0) { break }
  6954. at = 0;
  6955. } else { at -= sz; }
  6956. }
  6957. // If the result is smaller than 25 lines, ensure that it is a
  6958. // single leaf node.
  6959. if (this.size - n < 25 &&
  6960. (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) {
  6961. var lines = [];
  6962. this.collapse(lines);
  6963. this.children = [new LeafChunk(lines)];
  6964. this.children[0].parent = this;
  6965. }
  6966. },
  6967. collapse: function collapse(lines) {
  6968. var this$1 = this;
  6969. for (var i = 0; i < this.children.length; ++i) { this$1.children[i].collapse(lines); }
  6970. },
  6971. insertInner: function insertInner(at, lines, height) {
  6972. var this$1 = this;
  6973. this.size += lines.length;
  6974. this.height += height;
  6975. for (var i = 0; i < this.children.length; ++i) {
  6976. var child = this$1.children[i], sz = child.chunkSize();
  6977. if (at <= sz) {
  6978. child.insertInner(at, lines, height);
  6979. if (child.lines && child.lines.length > 50) {
  6980. // To avoid memory thrashing when child.lines is huge (e.g. first view of a large file), it's never spliced.
  6981. // Instead, small slices are taken. They're taken in order because sequential memory accesses are fastest.
  6982. var remaining = child.lines.length % 25 + 25;
  6983. for (var pos = remaining; pos < child.lines.length;) {
  6984. var leaf = new LeafChunk(child.lines.slice(pos, pos += 25));
  6985. child.height -= leaf.height;
  6986. this$1.children.splice(++i, 0, leaf);
  6987. leaf.parent = this$1;
  6988. }
  6989. child.lines = child.lines.slice(0, remaining);
  6990. this$1.maybeSpill();
  6991. }
  6992. break
  6993. }
  6994. at -= sz;
  6995. }
  6996. },
  6997. // When a node has grown, check whether it should be split.
  6998. maybeSpill: function maybeSpill() {
  6999. if (this.children.length <= 10) { return }
  7000. var me = this;
  7001. do {
  7002. var spilled = me.children.splice(me.children.length - 5, 5);
  7003. var sibling = new BranchChunk(spilled);
  7004. if (!me.parent) { // Become the parent node
  7005. var copy = new BranchChunk(me.children);
  7006. copy.parent = me;
  7007. me.children = [copy, sibling];
  7008. me = copy;
  7009. } else {
  7010. me.size -= sibling.size;
  7011. me.height -= sibling.height;
  7012. var myIndex = indexOf(me.parent.children, me);
  7013. me.parent.children.splice(myIndex + 1, 0, sibling);
  7014. }
  7015. sibling.parent = me.parent;
  7016. } while (me.children.length > 10)
  7017. me.parent.maybeSpill();
  7018. },
  7019. iterN: function iterN(at, n, op) {
  7020. var this$1 = this;
  7021. for (var i = 0; i < this.children.length; ++i) {
  7022. var child = this$1.children[i], sz = child.chunkSize();
  7023. if (at < sz) {
  7024. var used = Math.min(n, sz - at);
  7025. if (child.iterN(at, used, op)) { return true }
  7026. if ((n -= used) == 0) { break }
  7027. at = 0;
  7028. } else { at -= sz; }
  7029. }
  7030. }
  7031. };
  7032. // Line widgets are block elements displayed above or below a line.
  7033. var LineWidget = function(doc, node, options) {
  7034. var this$1 = this;
  7035. if (options) { for (var opt in options) { if (options.hasOwnProperty(opt))
  7036. { this$1[opt] = options[opt]; } } }
  7037. this.doc = doc;
  7038. this.node = node;
  7039. };
  7040. LineWidget.prototype.clear = function () {
  7041. var this$1 = this;
  7042. var cm = this.doc.cm, ws = this.line.widgets, line = this.line, no = lineNo(line);
  7043. if (no == null || !ws) { return }
  7044. for (var i = 0; i < ws.length; ++i) { if (ws[i] == this$1) { ws.splice(i--, 1); } }
  7045. if (!ws.length) { line.widgets = null; }
  7046. var height = widgetHeight(this);
  7047. updateLineHeight(line, Math.max(0, line.height - height));
  7048. if (cm) {
  7049. runInOp(cm, function () {
  7050. adjustScrollWhenAboveVisible(cm, line, -height);
  7051. regLineChange(cm, no, "widget");
  7052. });
  7053. signalLater(cm, "lineWidgetCleared", cm, this, no);
  7054. }
  7055. };
  7056. LineWidget.prototype.changed = function () {
  7057. var this$1 = this;
  7058. var oldH = this.height, cm = this.doc.cm, line = this.line;
  7059. this.height = null;
  7060. var diff = widgetHeight(this) - oldH;
  7061. if (!diff) { return }
  7062. updateLineHeight(line, line.height + diff);
  7063. if (cm) {
  7064. runInOp(cm, function () {
  7065. cm.curOp.forceUpdate = true;
  7066. adjustScrollWhenAboveVisible(cm, line, diff);
  7067. signalLater(cm, "lineWidgetChanged", cm, this$1, lineNo(line));
  7068. });
  7069. }
  7070. };
  7071. eventMixin(LineWidget);
  7072. function adjustScrollWhenAboveVisible(cm, line, diff) {
  7073. if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop))
  7074. { addToScrollTop(cm, diff); }
  7075. }
  7076. function addLineWidget(doc, handle, node, options) {
  7077. var widget = new LineWidget(doc, node, options);
  7078. var cm = doc.cm;
  7079. if (cm && widget.noHScroll) { cm.display.alignWidgets = true; }
  7080. changeLine(doc, handle, "widget", function (line) {
  7081. var widgets = line.widgets || (line.widgets = []);
  7082. if (widget.insertAt == null) { widgets.push(widget); }
  7083. else { widgets.splice(Math.min(widgets.length - 1, Math.max(0, widget.insertAt)), 0, widget); }
  7084. widget.line = line;
  7085. if (cm && !lineIsHidden(doc, line)) {
  7086. var aboveVisible = heightAtLine(line) < doc.scrollTop;
  7087. updateLineHeight(line, line.height + widgetHeight(widget));
  7088. if (aboveVisible) { addToScrollTop(cm, widget.height); }
  7089. cm.curOp.forceUpdate = true;
  7090. }
  7091. return true
  7092. });
  7093. signalLater(cm, "lineWidgetAdded", cm, widget, typeof handle == "number" ? handle : lineNo(handle));
  7094. return widget
  7095. }
  7096. // TEXTMARKERS
  7097. // Created with markText and setBookmark methods. A TextMarker is a
  7098. // handle that can be used to clear or find a marked position in the
  7099. // document. Line objects hold arrays (markedSpans) containing
  7100. // {from, to, marker} object pointing to such marker objects, and
  7101. // indicating that such a marker is present on that line. Multiple
  7102. // lines may point to the same marker when it spans across lines.
  7103. // The spans will have null for their from/to properties when the
  7104. // marker continues beyond the start/end of the line. Markers have
  7105. // links back to the lines they currently touch.
  7106. // Collapsed markers have unique ids, in order to be able to order
  7107. // them, which is needed for uniquely determining an outer marker
  7108. // when they overlap (they may nest, but not partially overlap).
  7109. var nextMarkerId = 0;
  7110. var TextMarker = function(doc, type) {
  7111. this.lines = [];
  7112. this.type = type;
  7113. this.doc = doc;
  7114. this.id = ++nextMarkerId;
  7115. };
  7116. // Clear the marker.
  7117. TextMarker.prototype.clear = function () {
  7118. var this$1 = this;
  7119. if (this.explicitlyCleared) { return }
  7120. var cm = this.doc.cm, withOp = cm && !cm.curOp;
  7121. if (withOp) { startOperation(cm); }
  7122. if (hasHandler(this, "clear")) {
  7123. var found = this.find();
  7124. if (found) { signalLater(this, "clear", found.from, found.to); }
  7125. }
  7126. var min = null, max = null;
  7127. for (var i = 0; i < this.lines.length; ++i) {
  7128. var line = this$1.lines[i];
  7129. var span = getMarkedSpanFor(line.markedSpans, this$1);
  7130. if (cm && !this$1.collapsed) { regLineChange(cm, lineNo(line), "text"); }
  7131. else if (cm) {
  7132. if (span.to != null) { max = lineNo(line); }
  7133. if (span.from != null) { min = lineNo(line); }
  7134. }
  7135. line.markedSpans = removeMarkedSpan(line.markedSpans, span);
  7136. if (span.from == null && this$1.collapsed && !lineIsHidden(this$1.doc, line) && cm)
  7137. { updateLineHeight(line, textHeight(cm.display)); }
  7138. }
  7139. if (cm && this.collapsed && !cm.options.lineWrapping) { for (var i$1 = 0; i$1 < this.lines.length; ++i$1) {
  7140. var visual = visualLine(this$1.lines[i$1]), len = lineLength(visual);
  7141. if (len > cm.display.maxLineLength) {
  7142. cm.display.maxLine = visual;
  7143. cm.display.maxLineLength = len;
  7144. cm.display.maxLineChanged = true;
  7145. }
  7146. } }
  7147. if (min != null && cm && this.collapsed) { regChange(cm, min, max + 1); }
  7148. this.lines.length = 0;
  7149. this.explicitlyCleared = true;
  7150. if (this.atomic && this.doc.cantEdit) {
  7151. this.doc.cantEdit = false;
  7152. if (cm) { reCheckSelection(cm.doc); }
  7153. }
  7154. if (cm) { signalLater(cm, "markerCleared", cm, this, min, max); }
  7155. if (withOp) { endOperation(cm); }
  7156. if (this.parent) { this.parent.clear(); }
  7157. };
  7158. // Find the position of the marker in the document. Returns a {from,
  7159. // to} object by default. Side can be passed to get a specific side
  7160. // -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the
  7161. // Pos objects returned contain a line object, rather than a line
  7162. // number (used to prevent looking up the same line twice).
  7163. TextMarker.prototype.find = function (side, lineObj) {
  7164. var this$1 = this;
  7165. if (side == null && this.type == "bookmark") { side = 1; }
  7166. var from, to;
  7167. for (var i = 0; i < this.lines.length; ++i) {
  7168. var line = this$1.lines[i];
  7169. var span = getMarkedSpanFor(line.markedSpans, this$1);
  7170. if (span.from != null) {
  7171. from = Pos(lineObj ? line : lineNo(line), span.from);
  7172. if (side == -1) { return from }
  7173. }
  7174. if (span.to != null) {
  7175. to = Pos(lineObj ? line : lineNo(line), span.to);
  7176. if (side == 1) { return to }
  7177. }
  7178. }
  7179. return from && {from: from, to: to}
  7180. };
  7181. // Signals that the marker's widget changed, and surrounding layout
  7182. // should be recomputed.
  7183. TextMarker.prototype.changed = function () {
  7184. var this$1 = this;
  7185. var pos = this.find(-1, true), widget = this, cm = this.doc.cm;
  7186. if (!pos || !cm) { return }
  7187. runInOp(cm, function () {
  7188. var line = pos.line, lineN = lineNo(pos.line);
  7189. var view = findViewForLine(cm, lineN);
  7190. if (view) {
  7191. clearLineMeasurementCacheFor(view);
  7192. cm.curOp.selectionChanged = cm.curOp.forceUpdate = true;
  7193. }
  7194. cm.curOp.updateMaxLine = true;
  7195. if (!lineIsHidden(widget.doc, line) && widget.height != null) {
  7196. var oldHeight = widget.height;
  7197. widget.height = null;
  7198. var dHeight = widgetHeight(widget) - oldHeight;
  7199. if (dHeight)
  7200. { updateLineHeight(line, line.height + dHeight); }
  7201. }
  7202. signalLater(cm, "markerChanged", cm, this$1);
  7203. });
  7204. };
  7205. TextMarker.prototype.attachLine = function (line) {
  7206. if (!this.lines.length && this.doc.cm) {
  7207. var op = this.doc.cm.curOp;
  7208. if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1)
  7209. { (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this); }
  7210. }
  7211. this.lines.push(line);
  7212. };
  7213. TextMarker.prototype.detachLine = function (line) {
  7214. this.lines.splice(indexOf(this.lines, line), 1);
  7215. if (!this.lines.length && this.doc.cm) {
  7216. var op = this.doc.cm.curOp;(op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this);
  7217. }
  7218. };
  7219. eventMixin(TextMarker);
  7220. // Create a marker, wire it up to the right lines, and
  7221. function markText(doc, from, to, options, type) {
  7222. // Shared markers (across linked documents) are handled separately
  7223. // (markTextShared will call out to this again, once per
  7224. // document).
  7225. if (options && options.shared) { return markTextShared(doc, from, to, options, type) }
  7226. // Ensure we are in an operation.
  7227. if (doc.cm && !doc.cm.curOp) { return operation(doc.cm, markText)(doc, from, to, options, type) }
  7228. var marker = new TextMarker(doc, type), diff = cmp(from, to);
  7229. if (options) { copyObj(options, marker, false); }
  7230. // Don't connect empty markers unless clearWhenEmpty is false
  7231. if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false)
  7232. { return marker }
  7233. if (marker.replacedWith) {
  7234. // Showing up as a widget implies collapsed (widget replaces text)
  7235. marker.collapsed = true;
  7236. marker.widgetNode = eltP("span", [marker.replacedWith], "CodeMirror-widget");
  7237. if (!options.handleMouseEvents) { marker.widgetNode.setAttribute("cm-ignore-events", "true"); }
  7238. if (options.insertLeft) { marker.widgetNode.insertLeft = true; }
  7239. }
  7240. if (marker.collapsed) {
  7241. if (conflictingCollapsedRange(doc, from.line, from, to, marker) ||
  7242. from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker))
  7243. { throw new Error("Inserting collapsed marker partially overlapping an existing one") }
  7244. seeCollapsedSpans();
  7245. }
  7246. if (marker.addToHistory)
  7247. { addChangeToHistory(doc, {from: from, to: to, origin: "markText"}, doc.sel, NaN); }
  7248. var curLine = from.line, cm = doc.cm, updateMaxLine;
  7249. doc.iter(curLine, to.line + 1, function (line) {
  7250. if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine)
  7251. { updateMaxLine = true; }
  7252. if (marker.collapsed && curLine != from.line) { updateLineHeight(line, 0); }
  7253. addMarkedSpan(line, new MarkedSpan(marker,
  7254. curLine == from.line ? from.ch : null,
  7255. curLine == to.line ? to.ch : null));
  7256. ++curLine;
  7257. });
  7258. // lineIsHidden depends on the presence of the spans, so needs a second pass
  7259. if (marker.collapsed) { doc.iter(from.line, to.line + 1, function (line) {
  7260. if (lineIsHidden(doc, line)) { updateLineHeight(line, 0); }
  7261. }); }
  7262. if (marker.clearOnEnter) { on(marker, "beforeCursorEnter", function () { return marker.clear(); }); }
  7263. if (marker.readOnly) {
  7264. seeReadOnlySpans();
  7265. if (doc.history.done.length || doc.history.undone.length)
  7266. { doc.clearHistory(); }
  7267. }
  7268. if (marker.collapsed) {
  7269. marker.id = ++nextMarkerId;
  7270. marker.atomic = true;
  7271. }
  7272. if (cm) {
  7273. // Sync editor state
  7274. if (updateMaxLine) { cm.curOp.updateMaxLine = true; }
  7275. if (marker.collapsed)
  7276. { regChange(cm, from.line, to.line + 1); }
  7277. else if (marker.className || marker.title || marker.startStyle || marker.endStyle || marker.css)
  7278. { for (var i = from.line; i <= to.line; i++) { regLineChange(cm, i, "text"); } }
  7279. if (marker.atomic) { reCheckSelection(cm.doc); }
  7280. signalLater(cm, "markerAdded", cm, marker);
  7281. }
  7282. return marker
  7283. }
  7284. // SHARED TEXTMARKERS
  7285. // A shared marker spans multiple linked documents. It is
  7286. // implemented as a meta-marker-object controlling multiple normal
  7287. // markers.
  7288. var SharedTextMarker = function(markers, primary) {
  7289. var this$1 = this;
  7290. this.markers = markers;
  7291. this.primary = primary;
  7292. for (var i = 0; i < markers.length; ++i)
  7293. { markers[i].parent = this$1; }
  7294. };
  7295. SharedTextMarker.prototype.clear = function () {
  7296. var this$1 = this;
  7297. if (this.explicitlyCleared) { return }
  7298. this.explicitlyCleared = true;
  7299. for (var i = 0; i < this.markers.length; ++i)
  7300. { this$1.markers[i].clear(); }
  7301. signalLater(this, "clear");
  7302. };
  7303. SharedTextMarker.prototype.find = function (side, lineObj) {
  7304. return this.primary.find(side, lineObj)
  7305. };
  7306. eventMixin(SharedTextMarker);
  7307. function markTextShared(doc, from, to, options, type) {
  7308. options = copyObj(options);
  7309. options.shared = false;
  7310. var markers = [markText(doc, from, to, options, type)], primary = markers[0];
  7311. var widget = options.widgetNode;
  7312. linkedDocs(doc, function (doc) {
  7313. if (widget) { options.widgetNode = widget.cloneNode(true); }
  7314. markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type));
  7315. for (var i = 0; i < doc.linked.length; ++i)
  7316. { if (doc.linked[i].isParent) { return } }
  7317. primary = lst(markers);
  7318. });
  7319. return new SharedTextMarker(markers, primary)
  7320. }
  7321. function findSharedMarkers(doc) {
  7322. return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())), function (m) { return m.parent; })
  7323. }
  7324. function copySharedMarkers(doc, markers) {
  7325. for (var i = 0; i < markers.length; i++) {
  7326. var marker = markers[i], pos = marker.find();
  7327. var mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to);
  7328. if (cmp(mFrom, mTo)) {
  7329. var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type);
  7330. marker.markers.push(subMark);
  7331. subMark.parent = marker;
  7332. }
  7333. }
  7334. }
  7335. function detachSharedMarkers(markers) {
  7336. var loop = function ( i ) {
  7337. var marker = markers[i], linked = [marker.primary.doc];
  7338. linkedDocs(marker.primary.doc, function (d) { return linked.push(d); });
  7339. for (var j = 0; j < marker.markers.length; j++) {
  7340. var subMarker = marker.markers[j];
  7341. if (indexOf(linked, subMarker.doc) == -1) {
  7342. subMarker.parent = null;
  7343. marker.markers.splice(j--, 1);
  7344. }
  7345. }
  7346. };
  7347. for (var i = 0; i < markers.length; i++) loop( i );
  7348. }
  7349. var nextDocId = 0;
  7350. var Doc = function(text, mode, firstLine, lineSep, direction) {
  7351. if (!(this instanceof Doc)) { return new Doc(text, mode, firstLine, lineSep, direction) }
  7352. if (firstLine == null) { firstLine = 0; }
  7353. BranchChunk.call(this, [new LeafChunk([new Line("", null)])]);
  7354. this.first = firstLine;
  7355. this.scrollTop = this.scrollLeft = 0;
  7356. this.cantEdit = false;
  7357. this.cleanGeneration = 1;
  7358. this.modeFrontier = this.highlightFrontier = firstLine;
  7359. var start = Pos(firstLine, 0);
  7360. this.sel = simpleSelection(start);
  7361. this.history = new History(null);
  7362. this.id = ++nextDocId;
  7363. this.modeOption = mode;
  7364. this.lineSep = lineSep;
  7365. this.direction = (direction == "rtl") ? "rtl" : "ltr";
  7366. this.extend = false;
  7367. if (typeof text == "string") { text = this.splitLines(text); }
  7368. updateDoc(this, {from: start, to: start, text: text});
  7369. setSelection(this, simpleSelection(start), sel_dontScroll);
  7370. };
  7371. Doc.prototype = createObj(BranchChunk.prototype, {
  7372. constructor: Doc,
  7373. // Iterate over the document. Supports two forms -- with only one
  7374. // argument, it calls that for each line in the document. With
  7375. // three, it iterates over the range given by the first two (with
  7376. // the second being non-inclusive).
  7377. iter: function(from, to, op) {
  7378. if (op) { this.iterN(from - this.first, to - from, op); }
  7379. else { this.iterN(this.first, this.first + this.size, from); }
  7380. },
  7381. // Non-public interface for adding and removing lines.
  7382. insert: function(at, lines) {
  7383. var height = 0;
  7384. for (var i = 0; i < lines.length; ++i) { height += lines[i].height; }
  7385. this.insertInner(at - this.first, lines, height);
  7386. },
  7387. remove: function(at, n) { this.removeInner(at - this.first, n); },
  7388. // From here, the methods are part of the public interface. Most
  7389. // are also available from CodeMirror (editor) instances.
  7390. getValue: function(lineSep) {
  7391. var lines = getLines(this, this.first, this.first + this.size);
  7392. if (lineSep === false) { return lines }
  7393. return lines.join(lineSep || this.lineSeparator())
  7394. },
  7395. setValue: docMethodOp(function(code) {
  7396. var top = Pos(this.first, 0), last = this.first + this.size - 1;
  7397. makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length),
  7398. text: this.splitLines(code), origin: "setValue", full: true}, true);
  7399. if (this.cm) { scrollToCoords(this.cm, 0, 0); }
  7400. setSelection(this, simpleSelection(top), sel_dontScroll);
  7401. }),
  7402. replaceRange: function(code, from, to, origin) {
  7403. from = clipPos(this, from);
  7404. to = to ? clipPos(this, to) : from;
  7405. replaceRange(this, code, from, to, origin);
  7406. },
  7407. getRange: function(from, to, lineSep) {
  7408. var lines = getBetween(this, clipPos(this, from), clipPos(this, to));
  7409. if (lineSep === false) { return lines }
  7410. return lines.join(lineSep || this.lineSeparator())
  7411. },
  7412. getLine: function(line) {var l = this.getLineHandle(line); return l && l.text},
  7413. getLineHandle: function(line) {if (isLine(this, line)) { return getLine(this, line) }},
  7414. getLineNumber: function(line) {return lineNo(line)},
  7415. getLineHandleVisualStart: function(line) {
  7416. if (typeof line == "number") { line = getLine(this, line); }
  7417. return visualLine(line)
  7418. },
  7419. lineCount: function() {return this.size},
  7420. firstLine: function() {return this.first},
  7421. lastLine: function() {return this.first + this.size - 1},
  7422. clipPos: function(pos) {return clipPos(this, pos)},
  7423. getCursor: function(start) {
  7424. var range$$1 = this.sel.primary(), pos;
  7425. if (start == null || start == "head") { pos = range$$1.head; }
  7426. else if (start == "anchor") { pos = range$$1.anchor; }
  7427. else if (start == "end" || start == "to" || start === false) { pos = range$$1.to(); }
  7428. else { pos = range$$1.from(); }
  7429. return pos
  7430. },
  7431. listSelections: function() { return this.sel.ranges },
  7432. somethingSelected: function() {return this.sel.somethingSelected()},
  7433. setCursor: docMethodOp(function(line, ch, options) {
  7434. setSimpleSelection(this, clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line), null, options);
  7435. }),
  7436. setSelection: docMethodOp(function(anchor, head, options) {
  7437. setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options);
  7438. }),
  7439. extendSelection: docMethodOp(function(head, other, options) {
  7440. extendSelection(this, clipPos(this, head), other && clipPos(this, other), options);
  7441. }),
  7442. extendSelections: docMethodOp(function(heads, options) {
  7443. extendSelections(this, clipPosArray(this, heads), options);
  7444. }),
  7445. extendSelectionsBy: docMethodOp(function(f, options) {
  7446. var heads = map(this.sel.ranges, f);
  7447. extendSelections(this, clipPosArray(this, heads), options);
  7448. }),
  7449. setSelections: docMethodOp(function(ranges, primary, options) {
  7450. var this$1 = this;
  7451. if (!ranges.length) { return }
  7452. var out = [];
  7453. for (var i = 0; i < ranges.length; i++)
  7454. { out[i] = new Range(clipPos(this$1, ranges[i].anchor),
  7455. clipPos(this$1, ranges[i].head)); }
  7456. if (primary == null) { primary = Math.min(ranges.length - 1, this.sel.primIndex); }
  7457. setSelection(this, normalizeSelection(out, primary), options);
  7458. }),
  7459. addSelection: docMethodOp(function(anchor, head, options) {
  7460. var ranges = this.sel.ranges.slice(0);
  7461. ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor)));
  7462. setSelection(this, normalizeSelection(ranges, ranges.length - 1), options);
  7463. }),
  7464. getSelection: function(lineSep) {
  7465. var this$1 = this;
  7466. var ranges = this.sel.ranges, lines;
  7467. for (var i = 0; i < ranges.length; i++) {
  7468. var sel = getBetween(this$1, ranges[i].from(), ranges[i].to());
  7469. lines = lines ? lines.concat(sel) : sel;
  7470. }
  7471. if (lineSep === false) { return lines }
  7472. else { return lines.join(lineSep || this.lineSeparator()) }
  7473. },
  7474. getSelections: function(lineSep) {
  7475. var this$1 = this;
  7476. var parts = [], ranges = this.sel.ranges;
  7477. for (var i = 0; i < ranges.length; i++) {
  7478. var sel = getBetween(this$1, ranges[i].from(), ranges[i].to());
  7479. if (lineSep !== false) { sel = sel.join(lineSep || this$1.lineSeparator()); }
  7480. parts[i] = sel;
  7481. }
  7482. return parts
  7483. },
  7484. replaceSelection: function(code, collapse, origin) {
  7485. var dup = [];
  7486. for (var i = 0; i < this.sel.ranges.length; i++)
  7487. { dup[i] = code; }
  7488. this.replaceSelections(dup, collapse, origin || "+input");
  7489. },
  7490. replaceSelections: docMethodOp(function(code, collapse, origin) {
  7491. var this$1 = this;
  7492. var changes = [], sel = this.sel;
  7493. for (var i = 0; i < sel.ranges.length; i++) {
  7494. var range$$1 = sel.ranges[i];
  7495. changes[i] = {from: range$$1.from(), to: range$$1.to(), text: this$1.splitLines(code[i]), origin: origin};
  7496. }
  7497. var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse);
  7498. for (var i$1 = changes.length - 1; i$1 >= 0; i$1--)
  7499. { makeChange(this$1, changes[i$1]); }
  7500. if (newSel) { setSelectionReplaceHistory(this, newSel); }
  7501. else if (this.cm) { ensureCursorVisible(this.cm); }
  7502. }),
  7503. undo: docMethodOp(function() {makeChangeFromHistory(this, "undo");}),
  7504. redo: docMethodOp(function() {makeChangeFromHistory(this, "redo");}),
  7505. undoSelection: docMethodOp(function() {makeChangeFromHistory(this, "undo", true);}),
  7506. redoSelection: docMethodOp(function() {makeChangeFromHistory(this, "redo", true);}),
  7507. setExtending: function(val) {this.extend = val;},
  7508. getExtending: function() {return this.extend},
  7509. historySize: function() {
  7510. var hist = this.history, done = 0, undone = 0;
  7511. for (var i = 0; i < hist.done.length; i++) { if (!hist.done[i].ranges) { ++done; } }
  7512. for (var i$1 = 0; i$1 < hist.undone.length; i$1++) { if (!hist.undone[i$1].ranges) { ++undone; } }
  7513. return {undo: done, redo: undone}
  7514. },
  7515. clearHistory: function() {this.history = new History(this.history.maxGeneration);},
  7516. markClean: function() {
  7517. this.cleanGeneration = this.changeGeneration(true);
  7518. },
  7519. changeGeneration: function(forceSplit) {
  7520. if (forceSplit)
  7521. { this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null; }
  7522. return this.history.generation
  7523. },
  7524. isClean: function (gen) {
  7525. return this.history.generation == (gen || this.cleanGeneration)
  7526. },
  7527. getHistory: function() {
  7528. return {done: copyHistoryArray(this.history.done),
  7529. undone: copyHistoryArray(this.history.undone)}
  7530. },
  7531. setHistory: function(histData) {
  7532. var hist = this.history = new History(this.history.maxGeneration);
  7533. hist.done = copyHistoryArray(histData.done.slice(0), null, true);
  7534. hist.undone = copyHistoryArray(histData.undone.slice(0), null, true);
  7535. },
  7536. setGutterMarker: docMethodOp(function(line, gutterID, value) {
  7537. return changeLine(this, line, "gutter", function (line) {
  7538. var markers = line.gutterMarkers || (line.gutterMarkers = {});
  7539. markers[gutterID] = value;
  7540. if (!value && isEmpty(markers)) { line.gutterMarkers = null; }
  7541. return true
  7542. })
  7543. }),
  7544. clearGutter: docMethodOp(function(gutterID) {
  7545. var this$1 = this;
  7546. this.iter(function (line) {
  7547. if (line.gutterMarkers && line.gutterMarkers[gutterID]) {
  7548. changeLine(this$1, line, "gutter", function () {
  7549. line.gutterMarkers[gutterID] = null;
  7550. if (isEmpty(line.gutterMarkers)) { line.gutterMarkers = null; }
  7551. return true
  7552. });
  7553. }
  7554. });
  7555. }),
  7556. lineInfo: function(line) {
  7557. var n;
  7558. if (typeof line == "number") {
  7559. if (!isLine(this, line)) { return null }
  7560. n = line;
  7561. line = getLine(this, line);
  7562. if (!line) { return null }
  7563. } else {
  7564. n = lineNo(line);
  7565. if (n == null) { return null }
  7566. }
  7567. return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers,
  7568. textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass,
  7569. widgets: line.widgets}
  7570. },
  7571. addLineClass: docMethodOp(function(handle, where, cls) {
  7572. return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) {
  7573. var prop = where == "text" ? "textClass"
  7574. : where == "background" ? "bgClass"
  7575. : where == "gutter" ? "gutterClass" : "wrapClass";
  7576. if (!line[prop]) { line[prop] = cls; }
  7577. else if (classTest(cls).test(line[prop])) { return false }
  7578. else { line[prop] += " " + cls; }
  7579. return true
  7580. })
  7581. }),
  7582. removeLineClass: docMethodOp(function(handle, where, cls) {
  7583. return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) {
  7584. var prop = where == "text" ? "textClass"
  7585. : where == "background" ? "bgClass"
  7586. : where == "gutter" ? "gutterClass" : "wrapClass";
  7587. var cur = line[prop];
  7588. if (!cur) { return false }
  7589. else if (cls == null) { line[prop] = null; }
  7590. else {
  7591. var found = cur.match(classTest(cls));
  7592. if (!found) { return false }
  7593. var end = found.index + found[0].length;
  7594. line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null;
  7595. }
  7596. return true
  7597. })
  7598. }),
  7599. addLineWidget: docMethodOp(function(handle, node, options) {
  7600. return addLineWidget(this, handle, node, options)
  7601. }),
  7602. removeLineWidget: function(widget) { widget.clear(); },
  7603. markText: function(from, to, options) {
  7604. return markText(this, clipPos(this, from), clipPos(this, to), options, options && options.type || "range")
  7605. },
  7606. setBookmark: function(pos, options) {
  7607. var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options),
  7608. insertLeft: options && options.insertLeft,
  7609. clearWhenEmpty: false, shared: options && options.shared,
  7610. handleMouseEvents: options && options.handleMouseEvents};
  7611. pos = clipPos(this, pos);
  7612. return markText(this, pos, pos, realOpts, "bookmark")
  7613. },
  7614. findMarksAt: function(pos) {
  7615. pos = clipPos(this, pos);
  7616. var markers = [], spans = getLine(this, pos.line).markedSpans;
  7617. if (spans) { for (var i = 0; i < spans.length; ++i) {
  7618. var span = spans[i];
  7619. if ((span.from == null || span.from <= pos.ch) &&
  7620. (span.to == null || span.to >= pos.ch))
  7621. { markers.push(span.marker.parent || span.marker); }
  7622. } }
  7623. return markers
  7624. },
  7625. findMarks: function(from, to, filter) {
  7626. from = clipPos(this, from); to = clipPos(this, to);
  7627. var found = [], lineNo$$1 = from.line;
  7628. this.iter(from.line, to.line + 1, function (line) {
  7629. var spans = line.markedSpans;
  7630. if (spans) { for (var i = 0; i < spans.length; i++) {
  7631. var span = spans[i];
  7632. if (!(span.to != null && lineNo$$1 == from.line && from.ch >= span.to ||
  7633. span.from == null && lineNo$$1 != from.line ||
  7634. span.from != null && lineNo$$1 == to.line && span.from >= to.ch) &&
  7635. (!filter || filter(span.marker)))
  7636. { found.push(span.marker.parent || span.marker); }
  7637. } }
  7638. ++lineNo$$1;
  7639. });
  7640. return found
  7641. },
  7642. getAllMarks: function() {
  7643. var markers = [];
  7644. this.iter(function (line) {
  7645. var sps = line.markedSpans;
  7646. if (sps) { for (var i = 0; i < sps.length; ++i)
  7647. { if (sps[i].from != null) { markers.push(sps[i].marker); } } }
  7648. });
  7649. return markers
  7650. },
  7651. posFromIndex: function(off) {
  7652. var ch, lineNo$$1 = this.first, sepSize = this.lineSeparator().length;
  7653. this.iter(function (line) {
  7654. var sz = line.text.length + sepSize;
  7655. if (sz > off) { ch = off; return true }
  7656. off -= sz;
  7657. ++lineNo$$1;
  7658. });
  7659. return clipPos(this, Pos(lineNo$$1, ch))
  7660. },
  7661. indexFromPos: function (coords) {
  7662. coords = clipPos(this, coords);
  7663. var index = coords.ch;
  7664. if (coords.line < this.first || coords.ch < 0) { return 0 }
  7665. var sepSize = this.lineSeparator().length;
  7666. this.iter(this.first, coords.line, function (line) { // iter aborts when callback returns a truthy value
  7667. index += line.text.length + sepSize;
  7668. });
  7669. return index
  7670. },
  7671. copy: function(copyHistory) {
  7672. var doc = new Doc(getLines(this, this.first, this.first + this.size),
  7673. this.modeOption, this.first, this.lineSep, this.direction);
  7674. doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft;
  7675. doc.sel = this.sel;
  7676. doc.extend = false;
  7677. if (copyHistory) {
  7678. doc.history.undoDepth = this.history.undoDepth;
  7679. doc.setHistory(this.getHistory());
  7680. }
  7681. return doc
  7682. },
  7683. linkedDoc: function(options) {
  7684. if (!options) { options = {}; }
  7685. var from = this.first, to = this.first + this.size;
  7686. if (options.from != null && options.from > from) { from = options.from; }
  7687. if (options.to != null && options.to < to) { to = options.to; }
  7688. var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from, this.lineSep, this.direction);
  7689. if (options.sharedHist) { copy.history = this.history
  7690. ; }(this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist});
  7691. copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}];
  7692. copySharedMarkers(copy, findSharedMarkers(this));
  7693. return copy
  7694. },
  7695. unlinkDoc: function(other) {
  7696. var this$1 = this;
  7697. if (other instanceof CodeMirror$1) { other = other.doc; }
  7698. if (this.linked) { for (var i = 0; i < this.linked.length; ++i) {
  7699. var link = this$1.linked[i];
  7700. if (link.doc != other) { continue }
  7701. this$1.linked.splice(i, 1);
  7702. other.unlinkDoc(this$1);
  7703. detachSharedMarkers(findSharedMarkers(this$1));
  7704. break
  7705. } }
  7706. // If the histories were shared, split them again
  7707. if (other.history == this.history) {
  7708. var splitIds = [other.id];
  7709. linkedDocs(other, function (doc) { return splitIds.push(doc.id); }, true);
  7710. other.history = new History(null);
  7711. other.history.done = copyHistoryArray(this.history.done, splitIds);
  7712. other.history.undone = copyHistoryArray(this.history.undone, splitIds);
  7713. }
  7714. },
  7715. iterLinkedDocs: function(f) {linkedDocs(this, f);},
  7716. getMode: function() {return this.mode},
  7717. getEditor: function() {return this.cm},
  7718. splitLines: function(str) {
  7719. if (this.lineSep) { return str.split(this.lineSep) }
  7720. return splitLinesAuto(str)
  7721. },
  7722. lineSeparator: function() { return this.lineSep || "\n" },
  7723. setDirection: docMethodOp(function (dir) {
  7724. if (dir != "rtl") { dir = "ltr"; }
  7725. if (dir == this.direction) { return }
  7726. this.direction = dir;
  7727. this.iter(function (line) { return line.order = null; });
  7728. if (this.cm) { directionChanged(this.cm); }
  7729. })
  7730. });
  7731. // Public alias.
  7732. Doc.prototype.eachLine = Doc.prototype.iter;
  7733. // Kludge to work around strange IE behavior where it'll sometimes
  7734. // re-fire a series of drag-related events right after the drop (#1551)
  7735. var lastDrop = 0;
  7736. function onDrop(e) {
  7737. var cm = this;
  7738. clearDragCursor(cm);
  7739. if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e))
  7740. { return }
  7741. e_preventDefault(e);
  7742. if (ie) { lastDrop = +new Date; }
  7743. var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files;
  7744. if (!pos || cm.isReadOnly()) { return }
  7745. // Might be a file drop, in which case we simply extract the text
  7746. // and insert it.
  7747. if (files && files.length && window.FileReader && window.File) {
  7748. var n = files.length, text = Array(n), read = 0;
  7749. var loadFile = function (file, i) {
  7750. if (cm.options.allowDropFileTypes &&
  7751. indexOf(cm.options.allowDropFileTypes, file.type) == -1)
  7752. { return }
  7753. var reader = new FileReader;
  7754. reader.onload = operation(cm, function () {
  7755. var content = reader.result;
  7756. if (/[\x00-\x08\x0e-\x1f]{2}/.test(content)) { content = ""; }
  7757. text[i] = content;
  7758. if (++read == n) {
  7759. pos = clipPos(cm.doc, pos);
  7760. var change = {from: pos, to: pos,
  7761. text: cm.doc.splitLines(text.join(cm.doc.lineSeparator())),
  7762. origin: "paste"};
  7763. makeChange(cm.doc, change);
  7764. setSelectionReplaceHistory(cm.doc, simpleSelection(pos, changeEnd(change)));
  7765. }
  7766. });
  7767. reader.readAsText(file);
  7768. };
  7769. for (var i = 0; i < n; ++i) { loadFile(files[i], i); }
  7770. } else { // Normal drop
  7771. // Don't do a replace if the drop happened inside of the selected text.
  7772. if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) {
  7773. cm.state.draggingText(e);
  7774. // Ensure the editor is re-focused
  7775. setTimeout(function () { return cm.display.input.focus(); }, 20);
  7776. return
  7777. }
  7778. try {
  7779. var text$1 = e.dataTransfer.getData("Text");
  7780. if (text$1) {
  7781. var selected;
  7782. if (cm.state.draggingText && !cm.state.draggingText.copy)
  7783. { selected = cm.listSelections(); }
  7784. setSelectionNoUndo(cm.doc, simpleSelection(pos, pos));
  7785. if (selected) { for (var i$1 = 0; i$1 < selected.length; ++i$1)
  7786. { replaceRange(cm.doc, "", selected[i$1].anchor, selected[i$1].head, "drag"); } }
  7787. cm.replaceSelection(text$1, "around", "paste");
  7788. cm.display.input.focus();
  7789. }
  7790. }
  7791. catch(e){}
  7792. }
  7793. }
  7794. function onDragStart(cm, e) {
  7795. if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return }
  7796. if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) { return }
  7797. e.dataTransfer.setData("Text", cm.getSelection());
  7798. e.dataTransfer.effectAllowed = "copyMove";
  7799. // Use dummy image instead of default browsers image.
  7800. // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there.
  7801. if (e.dataTransfer.setDragImage && !safari) {
  7802. var img = elt("img", null, null, "position: fixed; left: 0; top: 0;");
  7803. img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";
  7804. if (presto) {
  7805. img.width = img.height = 1;
  7806. cm.display.wrapper.appendChild(img);
  7807. // Force a relayout, or Opera won't use our image for some obscure reason
  7808. img._top = img.offsetTop;
  7809. }
  7810. e.dataTransfer.setDragImage(img, 0, 0);
  7811. if (presto) { img.parentNode.removeChild(img); }
  7812. }
  7813. }
  7814. function onDragOver(cm, e) {
  7815. var pos = posFromMouse(cm, e);
  7816. if (!pos) { return }
  7817. var frag = document.createDocumentFragment();
  7818. drawSelectionCursor(cm, pos, frag);
  7819. if (!cm.display.dragCursor) {
  7820. cm.display.dragCursor = elt("div", null, "CodeMirror-cursors CodeMirror-dragcursors");
  7821. cm.display.lineSpace.insertBefore(cm.display.dragCursor, cm.display.cursorDiv);
  7822. }
  7823. removeChildrenAndAdd(cm.display.dragCursor, frag);
  7824. }
  7825. function clearDragCursor(cm) {
  7826. if (cm.display.dragCursor) {
  7827. cm.display.lineSpace.removeChild(cm.display.dragCursor);
  7828. cm.display.dragCursor = null;
  7829. }
  7830. }
  7831. // These must be handled carefully, because naively registering a
  7832. // handler for each editor will cause the editors to never be
  7833. // garbage collected.
  7834. function forEachCodeMirror(f) {
  7835. if (!document.getElementsByClassName) { return }
  7836. var byClass = document.getElementsByClassName("CodeMirror");
  7837. for (var i = 0; i < byClass.length; i++) {
  7838. var cm = byClass[i].CodeMirror;
  7839. if (cm) { f(cm); }
  7840. }
  7841. }
  7842. var globalsRegistered = false;
  7843. function ensureGlobalHandlers() {
  7844. if (globalsRegistered) { return }
  7845. registerGlobalHandlers();
  7846. globalsRegistered = true;
  7847. }
  7848. function registerGlobalHandlers() {
  7849. // When the window resizes, we need to refresh active editors.
  7850. var resizeTimer;
  7851. on(window, "resize", function () {
  7852. if (resizeTimer == null) { resizeTimer = setTimeout(function () {
  7853. resizeTimer = null;
  7854. forEachCodeMirror(onResize);
  7855. }, 100); }
  7856. });
  7857. // When the window loses focus, we want to show the editor as blurred
  7858. on(window, "blur", function () { return forEachCodeMirror(onBlur); });
  7859. }
  7860. // Called when the window resizes
  7861. function onResize(cm) {
  7862. var d = cm.display;
  7863. if (d.lastWrapHeight == d.wrapper.clientHeight && d.lastWrapWidth == d.wrapper.clientWidth)
  7864. { return }
  7865. // Might be a text scaling operation, clear size caches.
  7866. d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
  7867. d.scrollbarsClipped = false;
  7868. cm.setSize();
  7869. }
  7870. var keyNames = {
  7871. 3: "Enter", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt",
  7872. 19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End",
  7873. 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert",
  7874. 46: "Delete", 59: ";", 61: "=", 91: "Mod", 92: "Mod", 93: "Mod",
  7875. 106: "*", 107: "=", 109: "-", 110: ".", 111: "/", 127: "Delete",
  7876. 173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\",
  7877. 221: "]", 222: "'", 63232: "Up", 63233: "Down", 63234: "Left", 63235: "Right", 63272: "Delete",
  7878. 63273: "Home", 63275: "End", 63276: "PageUp", 63277: "PageDown", 63302: "Insert"
  7879. };
  7880. // Number keys
  7881. for (var i = 0; i < 10; i++) { keyNames[i + 48] = keyNames[i + 96] = String(i); }
  7882. // Alphabetic keys
  7883. for (var i$1 = 65; i$1 <= 90; i$1++) { keyNames[i$1] = String.fromCharCode(i$1); }
  7884. // Function keys
  7885. for (var i$2 = 1; i$2 <= 12; i$2++) { keyNames[i$2 + 111] = keyNames[i$2 + 63235] = "F" + i$2; }
  7886. var keyMap = {};
  7887. keyMap.basic = {
  7888. "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown",
  7889. "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown",
  7890. "Delete": "delCharAfter", "Backspace": "delCharBefore", "Shift-Backspace": "delCharBefore",
  7891. "Tab": "defaultTab", "Shift-Tab": "indentAuto",
  7892. "Enter": "newlineAndIndent", "Insert": "toggleOverwrite",
  7893. "Esc": "singleSelection"
  7894. };
  7895. // Note that the save and find-related commands aren't defined by
  7896. // default. User code or addons can define them. Unknown commands
  7897. // are simply ignored.
  7898. keyMap.pcDefault = {
  7899. "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo",
  7900. "Ctrl-Home": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Up": "goLineUp", "Ctrl-Down": "goLineDown",
  7901. "Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd",
  7902. "Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find",
  7903. "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll",
  7904. "Ctrl-[": "indentLess", "Ctrl-]": "indentMore",
  7905. "Ctrl-U": "undoSelection", "Shift-Ctrl-U": "redoSelection", "Alt-U": "redoSelection",
  7906. fallthrough: "basic"
  7907. };
  7908. // Very basic readline/emacs-style bindings, which are standard on Mac.
  7909. keyMap.emacsy = {
  7910. "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown",
  7911. "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd",
  7912. "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp", "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore",
  7913. "Alt-D": "delWordAfter", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars",
  7914. "Ctrl-O": "openLine"
  7915. };
  7916. keyMap.macDefault = {
  7917. "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo",
  7918. "Cmd-Home": "goDocStart", "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft",
  7919. "Alt-Right": "goGroupRight", "Cmd-Left": "goLineLeft", "Cmd-Right": "goLineRight", "Alt-Backspace": "delGroupBefore",
  7920. "Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find",
  7921. "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll",
  7922. "Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delWrappedLineLeft", "Cmd-Delete": "delWrappedLineRight",
  7923. "Cmd-U": "undoSelection", "Shift-Cmd-U": "redoSelection", "Ctrl-Up": "goDocStart", "Ctrl-Down": "goDocEnd",
  7924. fallthrough: ["basic", "emacsy"]
  7925. };
  7926. keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault;
  7927. // KEYMAP DISPATCH
  7928. function normalizeKeyName(name) {
  7929. var parts = name.split(/-(?!$)/);
  7930. name = parts[parts.length - 1];
  7931. var alt, ctrl, shift, cmd;
  7932. for (var i = 0; i < parts.length - 1; i++) {
  7933. var mod = parts[i];
  7934. if (/^(cmd|meta|m)$/i.test(mod)) { cmd = true; }
  7935. else if (/^a(lt)?$/i.test(mod)) { alt = true; }
  7936. else if (/^(c|ctrl|control)$/i.test(mod)) { ctrl = true; }
  7937. else if (/^s(hift)?$/i.test(mod)) { shift = true; }
  7938. else { throw new Error("Unrecognized modifier name: " + mod) }
  7939. }
  7940. if (alt) { name = "Alt-" + name; }
  7941. if (ctrl) { name = "Ctrl-" + name; }
  7942. if (cmd) { name = "Cmd-" + name; }
  7943. if (shift) { name = "Shift-" + name; }
  7944. return name
  7945. }
  7946. // This is a kludge to keep keymaps mostly working as raw objects
  7947. // (backwards compatibility) while at the same time support features
  7948. // like normalization and multi-stroke key bindings. It compiles a
  7949. // new normalized keymap, and then updates the old object to reflect
  7950. // this.
  7951. function normalizeKeyMap(keymap) {
  7952. var copy = {};
  7953. for (var keyname in keymap) { if (keymap.hasOwnProperty(keyname)) {
  7954. var value = keymap[keyname];
  7955. if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) { continue }
  7956. if (value == "...") { delete keymap[keyname]; continue }
  7957. var keys = map(keyname.split(" "), normalizeKeyName);
  7958. for (var i = 0; i < keys.length; i++) {
  7959. var val = (void 0), name = (void 0);
  7960. if (i == keys.length - 1) {
  7961. name = keys.join(" ");
  7962. val = value;
  7963. } else {
  7964. name = keys.slice(0, i + 1).join(" ");
  7965. val = "...";
  7966. }
  7967. var prev = copy[name];
  7968. if (!prev) { copy[name] = val; }
  7969. else if (prev != val) { throw new Error("Inconsistent bindings for " + name) }
  7970. }
  7971. delete keymap[keyname];
  7972. } }
  7973. for (var prop in copy) { keymap[prop] = copy[prop]; }
  7974. return keymap
  7975. }
  7976. function lookupKey(key, map$$1, handle, context) {
  7977. map$$1 = getKeyMap(map$$1);
  7978. var found = map$$1.call ? map$$1.call(key, context) : map$$1[key];
  7979. if (found === false) { return "nothing" }
  7980. if (found === "...") { return "multi" }
  7981. if (found != null && handle(found)) { return "handled" }
  7982. if (map$$1.fallthrough) {
  7983. if (Object.prototype.toString.call(map$$1.fallthrough) != "[object Array]")
  7984. { return lookupKey(key, map$$1.fallthrough, handle, context) }
  7985. for (var i = 0; i < map$$1.fallthrough.length; i++) {
  7986. var result = lookupKey(key, map$$1.fallthrough[i], handle, context);
  7987. if (result) { return result }
  7988. }
  7989. }
  7990. }
  7991. // Modifier key presses don't count as 'real' key presses for the
  7992. // purpose of keymap fallthrough.
  7993. function isModifierKey(value) {
  7994. var name = typeof value == "string" ? value : keyNames[value.keyCode];
  7995. return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod"
  7996. }
  7997. function addModifierNames(name, event, noShift) {
  7998. var base = name;
  7999. if (event.altKey && base != "Alt") { name = "Alt-" + name; }
  8000. if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != "Ctrl") { name = "Ctrl-" + name; }
  8001. if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != "Cmd") { name = "Cmd-" + name; }
  8002. if (!noShift && event.shiftKey && base != "Shift") { name = "Shift-" + name; }
  8003. return name
  8004. }
  8005. // Look up the name of a key as indicated by an event object.
  8006. function keyName(event, noShift) {
  8007. if (presto && event.keyCode == 34 && event["char"]) { return false }
  8008. var name = keyNames[event.keyCode];
  8009. if (name == null || event.altGraphKey) { return false }
  8010. return addModifierNames(name, event, noShift)
  8011. }
  8012. function getKeyMap(val) {
  8013. return typeof val == "string" ? keyMap[val] : val
  8014. }
  8015. // Helper for deleting text near the selection(s), used to implement
  8016. // backspace, delete, and similar functionality.
  8017. function deleteNearSelection(cm, compute) {
  8018. var ranges = cm.doc.sel.ranges, kill = [];
  8019. // Build up a set of ranges to kill first, merging overlapping
  8020. // ranges.
  8021. for (var i = 0; i < ranges.length; i++) {
  8022. var toKill = compute(ranges[i]);
  8023. while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) {
  8024. var replaced = kill.pop();
  8025. if (cmp(replaced.from, toKill.from) < 0) {
  8026. toKill.from = replaced.from;
  8027. break
  8028. }
  8029. }
  8030. kill.push(toKill);
  8031. }
  8032. // Next, remove those actual ranges.
  8033. runInOp(cm, function () {
  8034. for (var i = kill.length - 1; i >= 0; i--)
  8035. { replaceRange(cm.doc, "", kill[i].from, kill[i].to, "+delete"); }
  8036. ensureCursorVisible(cm);
  8037. });
  8038. }
  8039. function moveCharLogically(line, ch, dir) {
  8040. var target = skipExtendingChars(line.text, ch + dir, dir);
  8041. return target < 0 || target > line.text.length ? null : target
  8042. }
  8043. function moveLogically(line, start, dir) {
  8044. var ch = moveCharLogically(line, start.ch, dir);
  8045. return ch == null ? null : new Pos(start.line, ch, dir < 0 ? "after" : "before")
  8046. }
  8047. function endOfLine(visually, cm, lineObj, lineNo, dir) {
  8048. if (visually) {
  8049. var order = getOrder(lineObj, cm.doc.direction);
  8050. if (order) {
  8051. var part = dir < 0 ? lst(order) : order[0];
  8052. var moveInStorageOrder = (dir < 0) == (part.level == 1);
  8053. var sticky = moveInStorageOrder ? "after" : "before";
  8054. var ch;
  8055. // With a wrapped rtl chunk (possibly spanning multiple bidi parts),
  8056. // it could be that the last bidi part is not on the last visual line,
  8057. // since visual lines contain content order-consecutive chunks.
  8058. // Thus, in rtl, we are looking for the first (content-order) character
  8059. // in the rtl chunk that is on the last line (that is, the same line
  8060. // as the last (content-order) character).
  8061. if (part.level > 0 || cm.doc.direction == "rtl") {
  8062. var prep = prepareMeasureForLine(cm, lineObj);
  8063. ch = dir < 0 ? lineObj.text.length - 1 : 0;
  8064. var targetTop = measureCharPrepared(cm, prep, ch).top;
  8065. ch = findFirst(function (ch) { return measureCharPrepared(cm, prep, ch).top == targetTop; }, (dir < 0) == (part.level == 1) ? part.from : part.to - 1, ch);
  8066. if (sticky == "before") { ch = moveCharLogically(lineObj, ch, 1); }
  8067. } else { ch = dir < 0 ? part.to : part.from; }
  8068. return new Pos(lineNo, ch, sticky)
  8069. }
  8070. }
  8071. return new Pos(lineNo, dir < 0 ? lineObj.text.length : 0, dir < 0 ? "before" : "after")
  8072. }
  8073. function moveVisually(cm, line, start, dir) {
  8074. var bidi = getOrder(line, cm.doc.direction);
  8075. if (!bidi) { return moveLogically(line, start, dir) }
  8076. if (start.ch >= line.text.length) {
  8077. start.ch = line.text.length;
  8078. start.sticky = "before";
  8079. } else if (start.ch <= 0) {
  8080. start.ch = 0;
  8081. start.sticky = "after";
  8082. }
  8083. var partPos = getBidiPartAt(bidi, start.ch, start.sticky), part = bidi[partPos];
  8084. if (cm.doc.direction == "ltr" && part.level % 2 == 0 && (dir > 0 ? part.to > start.ch : part.from < start.ch)) {
  8085. // Case 1: We move within an ltr part in an ltr editor. Even with wrapped lines,
  8086. // nothing interesting happens.
  8087. return moveLogically(line, start, dir)
  8088. }
  8089. var mv = function (pos, dir) { return moveCharLogically(line, pos instanceof Pos ? pos.ch : pos, dir); };
  8090. var prep;
  8091. var getWrappedLineExtent = function (ch) {
  8092. if (!cm.options.lineWrapping) { return {begin: 0, end: line.text.length} }
  8093. prep = prep || prepareMeasureForLine(cm, line);
  8094. return wrappedLineExtentChar(cm, line, prep, ch)
  8095. };
  8096. var wrappedLineExtent = getWrappedLineExtent(start.sticky == "before" ? mv(start, -1) : start.ch);
  8097. if (cm.doc.direction == "rtl" || part.level == 1) {
  8098. var moveInStorageOrder = (part.level == 1) == (dir < 0);
  8099. var ch = mv(start, moveInStorageOrder ? 1 : -1);
  8100. if (ch != null && (!moveInStorageOrder ? ch >= part.from && ch >= wrappedLineExtent.begin : ch <= part.to && ch <= wrappedLineExtent.end)) {
  8101. // Case 2: We move within an rtl part or in an rtl editor on the same visual line
  8102. var sticky = moveInStorageOrder ? "before" : "after";
  8103. return new Pos(start.line, ch, sticky)
  8104. }
  8105. }
  8106. // Case 3: Could not move within this bidi part in this visual line, so leave
  8107. // the current bidi part
  8108. var searchInVisualLine = function (partPos, dir, wrappedLineExtent) {
  8109. var getRes = function (ch, moveInStorageOrder) { return moveInStorageOrder
  8110. ? new Pos(start.line, mv(ch, 1), "before")
  8111. : new Pos(start.line, ch, "after"); };
  8112. for (; partPos >= 0 && partPos < bidi.length; partPos += dir) {
  8113. var part = bidi[partPos];
  8114. var moveInStorageOrder = (dir > 0) == (part.level != 1);
  8115. var ch = moveInStorageOrder ? wrappedLineExtent.begin : mv(wrappedLineExtent.end, -1);
  8116. if (part.from <= ch && ch < part.to) { return getRes(ch, moveInStorageOrder) }
  8117. ch = moveInStorageOrder ? part.from : mv(part.to, -1);
  8118. if (wrappedLineExtent.begin <= ch && ch < wrappedLineExtent.end) { return getRes(ch, moveInStorageOrder) }
  8119. }
  8120. };
  8121. // Case 3a: Look for other bidi parts on the same visual line
  8122. var res = searchInVisualLine(partPos + dir, dir, wrappedLineExtent);
  8123. if (res) { return res }
  8124. // Case 3b: Look for other bidi parts on the next visual line
  8125. var nextCh = dir > 0 ? wrappedLineExtent.end : mv(wrappedLineExtent.begin, -1);
  8126. if (nextCh != null && !(dir > 0 && nextCh == line.text.length)) {
  8127. res = searchInVisualLine(dir > 0 ? 0 : bidi.length - 1, dir, getWrappedLineExtent(nextCh));
  8128. if (res) { return res }
  8129. }
  8130. // Case 4: Nowhere to move
  8131. return null
  8132. }
  8133. // Commands are parameter-less actions that can be performed on an
  8134. // editor, mostly used for keybindings.
  8135. var commands = {
  8136. selectAll: selectAll,
  8137. singleSelection: function (cm) { return cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll); },
  8138. killLine: function (cm) { return deleteNearSelection(cm, function (range) {
  8139. if (range.empty()) {
  8140. var len = getLine(cm.doc, range.head.line).text.length;
  8141. if (range.head.ch == len && range.head.line < cm.lastLine())
  8142. { return {from: range.head, to: Pos(range.head.line + 1, 0)} }
  8143. else
  8144. { return {from: range.head, to: Pos(range.head.line, len)} }
  8145. } else {
  8146. return {from: range.from(), to: range.to()}
  8147. }
  8148. }); },
  8149. deleteLine: function (cm) { return deleteNearSelection(cm, function (range) { return ({
  8150. from: Pos(range.from().line, 0),
  8151. to: clipPos(cm.doc, Pos(range.to().line + 1, 0))
  8152. }); }); },
  8153. delLineLeft: function (cm) { return deleteNearSelection(cm, function (range) { return ({
  8154. from: Pos(range.from().line, 0), to: range.from()
  8155. }); }); },
  8156. delWrappedLineLeft: function (cm) { return deleteNearSelection(cm, function (range) {
  8157. var top = cm.charCoords(range.head, "div").top + 5;
  8158. var leftPos = cm.coordsChar({left: 0, top: top}, "div");
  8159. return {from: leftPos, to: range.from()}
  8160. }); },
  8161. delWrappedLineRight: function (cm) { return deleteNearSelection(cm, function (range) {
  8162. var top = cm.charCoords(range.head, "div").top + 5;
  8163. var rightPos = cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div");
  8164. return {from: range.from(), to: rightPos }
  8165. }); },
  8166. undo: function (cm) { return cm.undo(); },
  8167. redo: function (cm) { return cm.redo(); },
  8168. undoSelection: function (cm) { return cm.undoSelection(); },
  8169. redoSelection: function (cm) { return cm.redoSelection(); },
  8170. goDocStart: function (cm) { return cm.extendSelection(Pos(cm.firstLine(), 0)); },
  8171. goDocEnd: function (cm) { return cm.extendSelection(Pos(cm.lastLine())); },
  8172. goLineStart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStart(cm, range.head.line); },
  8173. {origin: "+move", bias: 1}
  8174. ); },
  8175. goLineStartSmart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStartSmart(cm, range.head); },
  8176. {origin: "+move", bias: 1}
  8177. ); },
  8178. goLineEnd: function (cm) { return cm.extendSelectionsBy(function (range) { return lineEnd(cm, range.head.line); },
  8179. {origin: "+move", bias: -1}
  8180. ); },
  8181. goLineRight: function (cm) { return cm.extendSelectionsBy(function (range) {
  8182. var top = cm.cursorCoords(range.head, "div").top + 5;
  8183. return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div")
  8184. }, sel_move); },
  8185. goLineLeft: function (cm) { return cm.extendSelectionsBy(function (range) {
  8186. var top = cm.cursorCoords(range.head, "div").top + 5;
  8187. return cm.coordsChar({left: 0, top: top}, "div")
  8188. }, sel_move); },
  8189. goLineLeftSmart: function (cm) { return cm.extendSelectionsBy(function (range) {
  8190. var top = cm.cursorCoords(range.head, "div").top + 5;
  8191. var pos = cm.coordsChar({left: 0, top: top}, "div");
  8192. if (pos.ch < cm.getLine(pos.line).search(/\S/)) { return lineStartSmart(cm, range.head) }
  8193. return pos
  8194. }, sel_move); },
  8195. goLineUp: function (cm) { return cm.moveV(-1, "line"); },
  8196. goLineDown: function (cm) { return cm.moveV(1, "line"); },
  8197. goPageUp: function (cm) { return cm.moveV(-1, "page"); },
  8198. goPageDown: function (cm) { return cm.moveV(1, "page"); },
  8199. goCharLeft: function (cm) { return cm.moveH(-1, "char"); },
  8200. goCharRight: function (cm) { return cm.moveH(1, "char"); },
  8201. goColumnLeft: function (cm) { return cm.moveH(-1, "column"); },
  8202. goColumnRight: function (cm) { return cm.moveH(1, "column"); },
  8203. goWordLeft: function (cm) { return cm.moveH(-1, "word"); },
  8204. goGroupRight: function (cm) { return cm.moveH(1, "group"); },
  8205. goGroupLeft: function (cm) { return cm.moveH(-1, "group"); },
  8206. goWordRight: function (cm) { return cm.moveH(1, "word"); },
  8207. delCharBefore: function (cm) { return cm.deleteH(-1, "char"); },
  8208. delCharAfter: function (cm) { return cm.deleteH(1, "char"); },
  8209. delWordBefore: function (cm) { return cm.deleteH(-1, "word"); },
  8210. delWordAfter: function (cm) { return cm.deleteH(1, "word"); },
  8211. delGroupBefore: function (cm) { return cm.deleteH(-1, "group"); },
  8212. delGroupAfter: function (cm) { return cm.deleteH(1, "group"); },
  8213. indentAuto: function (cm) { return cm.indentSelection("smart"); },
  8214. indentMore: function (cm) { return cm.indentSelection("add"); },
  8215. indentLess: function (cm) { return cm.indentSelection("subtract"); },
  8216. insertTab: function (cm) { return cm.replaceSelection("\t"); },
  8217. insertSoftTab: function (cm) {
  8218. var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize;
  8219. for (var i = 0; i < ranges.length; i++) {
  8220. var pos = ranges[i].from();
  8221. var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize);
  8222. spaces.push(spaceStr(tabSize - col % tabSize));
  8223. }
  8224. cm.replaceSelections(spaces);
  8225. },
  8226. defaultTab: function (cm) {
  8227. if (cm.somethingSelected()) { cm.indentSelection("add"); }
  8228. else { cm.execCommand("insertTab"); }
  8229. },
  8230. // Swap the two chars left and right of each selection's head.
  8231. // Move cursor behind the two swapped characters afterwards.
  8232. //
  8233. // Doesn't consider line feeds a character.
  8234. // Doesn't scan more than one line above to find a character.
  8235. // Doesn't do anything on an empty line.
  8236. // Doesn't do anything with non-empty selections.
  8237. transposeChars: function (cm) { return runInOp(cm, function () {
  8238. var ranges = cm.listSelections(), newSel = [];
  8239. for (var i = 0; i < ranges.length; i++) {
  8240. if (!ranges[i].empty()) { continue }
  8241. var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text;
  8242. if (line) {
  8243. if (cur.ch == line.length) { cur = new Pos(cur.line, cur.ch - 1); }
  8244. if (cur.ch > 0) {
  8245. cur = new Pos(cur.line, cur.ch + 1);
  8246. cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2),
  8247. Pos(cur.line, cur.ch - 2), cur, "+transpose");
  8248. } else if (cur.line > cm.doc.first) {
  8249. var prev = getLine(cm.doc, cur.line - 1).text;
  8250. if (prev) {
  8251. cur = new Pos(cur.line, 1);
  8252. cm.replaceRange(line.charAt(0) + cm.doc.lineSeparator() +
  8253. prev.charAt(prev.length - 1),
  8254. Pos(cur.line - 1, prev.length - 1), cur, "+transpose");
  8255. }
  8256. }
  8257. }
  8258. newSel.push(new Range(cur, cur));
  8259. }
  8260. cm.setSelections(newSel);
  8261. }); },
  8262. newlineAndIndent: function (cm) { return runInOp(cm, function () {
  8263. var sels = cm.listSelections();
  8264. for (var i = sels.length - 1; i >= 0; i--)
  8265. { cm.replaceRange(cm.doc.lineSeparator(), sels[i].anchor, sels[i].head, "+input"); }
  8266. sels = cm.listSelections();
  8267. for (var i$1 = 0; i$1 < sels.length; i$1++)
  8268. { cm.indentLine(sels[i$1].from().line, null, true); }
  8269. ensureCursorVisible(cm);
  8270. }); },
  8271. openLine: function (cm) { return cm.replaceSelection("\n", "start"); },
  8272. toggleOverwrite: function (cm) { return cm.toggleOverwrite(); }
  8273. };
  8274. function lineStart(cm, lineN) {
  8275. var line = getLine(cm.doc, lineN);
  8276. var visual = visualLine(line);
  8277. if (visual != line) { lineN = lineNo(visual); }
  8278. return endOfLine(true, cm, visual, lineN, 1)
  8279. }
  8280. function lineEnd(cm, lineN) {
  8281. var line = getLine(cm.doc, lineN);
  8282. var visual = visualLineEnd(line);
  8283. if (visual != line) { lineN = lineNo(visual); }
  8284. return endOfLine(true, cm, line, lineN, -1)
  8285. }
  8286. function lineStartSmart(cm, pos) {
  8287. var start = lineStart(cm, pos.line);
  8288. var line = getLine(cm.doc, start.line);
  8289. var order = getOrder(line, cm.doc.direction);
  8290. if (!order || order[0].level == 0) {
  8291. var firstNonWS = Math.max(0, line.text.search(/\S/));
  8292. var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch;
  8293. return Pos(start.line, inWS ? 0 : firstNonWS, start.sticky)
  8294. }
  8295. return start
  8296. }
  8297. // Run a handler that was bound to a key.
  8298. function doHandleBinding(cm, bound, dropShift) {
  8299. if (typeof bound == "string") {
  8300. bound = commands[bound];
  8301. if (!bound) { return false }
  8302. }
  8303. // Ensure previous input has been read, so that the handler sees a
  8304. // consistent view of the document
  8305. cm.display.input.ensurePolled();
  8306. var prevShift = cm.display.shift, done = false;
  8307. try {
  8308. if (cm.isReadOnly()) { cm.state.suppressEdits = true; }
  8309. if (dropShift) { cm.display.shift = false; }
  8310. done = bound(cm) != Pass;
  8311. } finally {
  8312. cm.display.shift = prevShift;
  8313. cm.state.suppressEdits = false;
  8314. }
  8315. return done
  8316. }
  8317. function lookupKeyForEditor(cm, name, handle) {
  8318. for (var i = 0; i < cm.state.keyMaps.length; i++) {
  8319. var result = lookupKey(name, cm.state.keyMaps[i], handle, cm);
  8320. if (result) { return result }
  8321. }
  8322. return (cm.options.extraKeys && lookupKey(name, cm.options.extraKeys, handle, cm))
  8323. || lookupKey(name, cm.options.keyMap, handle, cm)
  8324. }
  8325. // Note that, despite the name, this function is also used to check
  8326. // for bound mouse clicks.
  8327. var stopSeq = new Delayed;
  8328. function dispatchKey(cm, name, e, handle) {
  8329. var seq = cm.state.keySeq;
  8330. if (seq) {
  8331. if (isModifierKey(name)) { return "handled" }
  8332. if (/\'$/.test(name))
  8333. { cm.state.keySeq = null; }
  8334. else
  8335. { stopSeq.set(50, function () {
  8336. if (cm.state.keySeq == seq) {
  8337. cm.state.keySeq = null;
  8338. cm.display.input.reset();
  8339. }
  8340. }); }
  8341. if (dispatchKeyInner(cm, seq + " " + name, e, handle)) { return true }
  8342. }
  8343. return dispatchKeyInner(cm, name, e, handle)
  8344. }
  8345. function dispatchKeyInner(cm, name, e, handle) {
  8346. var result = lookupKeyForEditor(cm, name, handle);
  8347. if (result == "multi")
  8348. { cm.state.keySeq = name; }
  8349. if (result == "handled")
  8350. { signalLater(cm, "keyHandled", cm, name, e); }
  8351. if (result == "handled" || result == "multi") {
  8352. e_preventDefault(e);
  8353. restartBlink(cm);
  8354. }
  8355. return !!result
  8356. }
  8357. // Handle a key from the keydown event.
  8358. function handleKeyBinding(cm, e) {
  8359. var name = keyName(e, true);
  8360. if (!name) { return false }
  8361. if (e.shiftKey && !cm.state.keySeq) {
  8362. // First try to resolve full name (including 'Shift-'). Failing
  8363. // that, see if there is a cursor-motion command (starting with
  8364. // 'go') bound to the keyname without 'Shift-'.
  8365. return dispatchKey(cm, "Shift-" + name, e, function (b) { return doHandleBinding(cm, b, true); })
  8366. || dispatchKey(cm, name, e, function (b) {
  8367. if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion)
  8368. { return doHandleBinding(cm, b) }
  8369. })
  8370. } else {
  8371. return dispatchKey(cm, name, e, function (b) { return doHandleBinding(cm, b); })
  8372. }
  8373. }
  8374. // Handle a key from the keypress event
  8375. function handleCharBinding(cm, e, ch) {
  8376. return dispatchKey(cm, "'" + ch + "'", e, function (b) { return doHandleBinding(cm, b, true); })
  8377. }
  8378. var lastStoppedKey = null;
  8379. function onKeyDown(e) {
  8380. var cm = this;
  8381. cm.curOp.focus = activeElt();
  8382. if (signalDOMEvent(cm, e)) { return }
  8383. // IE does strange things with escape.
  8384. if (ie && ie_version < 11 && e.keyCode == 27) { e.returnValue = false; }
  8385. var code = e.keyCode;
  8386. cm.display.shift = code == 16 || e.shiftKey;
  8387. var handled = handleKeyBinding(cm, e);
  8388. if (presto) {
  8389. lastStoppedKey = handled ? code : null;
  8390. // Opera has no cut event... we try to at least catch the key combo
  8391. if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey))
  8392. { cm.replaceSelection("", null, "cut"); }
  8393. }
  8394. // Turn mouse into crosshair when Alt is held on Mac.
  8395. if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className))
  8396. { showCrossHair(cm); }
  8397. }
  8398. function showCrossHair(cm) {
  8399. var lineDiv = cm.display.lineDiv;
  8400. addClass(lineDiv, "CodeMirror-crosshair");
  8401. function up(e) {
  8402. if (e.keyCode == 18 || !e.altKey) {
  8403. rmClass(lineDiv, "CodeMirror-crosshair");
  8404. off(document, "keyup", up);
  8405. off(document, "mouseover", up);
  8406. }
  8407. }
  8408. on(document, "keyup", up);
  8409. on(document, "mouseover", up);
  8410. }
  8411. function onKeyUp(e) {
  8412. if (e.keyCode == 16) { this.doc.sel.shift = false; }
  8413. signalDOMEvent(this, e);
  8414. }
  8415. function onKeyPress(e) {
  8416. var cm = this;
  8417. if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) { return }
  8418. var keyCode = e.keyCode, charCode = e.charCode;
  8419. if (presto && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return}
  8420. if ((presto && (!e.which || e.which < 10)) && handleKeyBinding(cm, e)) { return }
  8421. var ch = String.fromCharCode(charCode == null ? keyCode : charCode);
  8422. // Some browsers fire keypress events for backspace
  8423. if (ch == "\x08") { return }
  8424. if (handleCharBinding(cm, e, ch)) { return }
  8425. cm.display.input.onKeyPress(e);
  8426. }
  8427. var DOUBLECLICK_DELAY = 400;
  8428. var PastClick = function(time, pos, button) {
  8429. this.time = time;
  8430. this.pos = pos;
  8431. this.button = button;
  8432. };
  8433. PastClick.prototype.compare = function (time, pos, button) {
  8434. return this.time + DOUBLECLICK_DELAY > time &&
  8435. cmp(pos, this.pos) == 0 && button == this.button
  8436. };
  8437. var lastClick;
  8438. var lastDoubleClick;
  8439. function clickRepeat(pos, button) {
  8440. var now = +new Date;
  8441. if (lastDoubleClick && lastDoubleClick.compare(now, pos, button)) {
  8442. lastClick = lastDoubleClick = null;
  8443. return "triple"
  8444. } else if (lastClick && lastClick.compare(now, pos, button)) {
  8445. lastDoubleClick = new PastClick(now, pos, button);
  8446. lastClick = null;
  8447. return "double"
  8448. } else {
  8449. lastClick = new PastClick(now, pos, button);
  8450. lastDoubleClick = null;
  8451. return "single"
  8452. }
  8453. }
  8454. // A mouse down can be a single click, double click, triple click,
  8455. // start of selection drag, start of text drag, new cursor
  8456. // (ctrl-click), rectangle drag (alt-drag), or xwin
  8457. // middle-click-paste. Or it might be a click on something we should
  8458. // not interfere with, such as a scrollbar or widget.
  8459. function onMouseDown(e) {
  8460. var cm = this, display = cm.display;
  8461. if (signalDOMEvent(cm, e) || display.activeTouch && display.input.supportsTouch()) { return }
  8462. display.input.ensurePolled();
  8463. display.shift = e.shiftKey;
  8464. if (eventInWidget(display, e)) {
  8465. if (!webkit) {
  8466. // Briefly turn off draggability, to allow widgets to do
  8467. // normal dragging things.
  8468. display.scroller.draggable = false;
  8469. setTimeout(function () { return display.scroller.draggable = true; }, 100);
  8470. }
  8471. return
  8472. }
  8473. if (clickInGutter(cm, e)) { return }
  8474. var pos = posFromMouse(cm, e), button = e_button(e), repeat = pos ? clickRepeat(pos, button) : "single";
  8475. window.focus();
  8476. // #3261: make sure, that we're not starting a second selection
  8477. if (button == 1 && cm.state.selectingText)
  8478. { cm.state.selectingText(e); }
  8479. if (pos && handleMappedButton(cm, button, pos, repeat, e)) { return }
  8480. if (button == 1) {
  8481. if (pos) { leftButtonDown(cm, pos, repeat, e); }
  8482. else if (e_target(e) == display.scroller) { e_preventDefault(e); }
  8483. } else if (button == 2) {
  8484. if (pos) { extendSelection(cm.doc, pos); }
  8485. setTimeout(function () { return display.input.focus(); }, 20);
  8486. } else if (button == 3) {
  8487. if (captureRightClick) { onContextMenu(cm, e); }
  8488. else { delayBlurEvent(cm); }
  8489. }
  8490. }
  8491. function handleMappedButton(cm, button, pos, repeat, event) {
  8492. var name = "Click";
  8493. if (repeat == "double") { name = "Double" + name; }
  8494. else if (repeat == "triple") { name = "Triple" + name; }
  8495. name = (button == 1 ? "Left" : button == 2 ? "Middle" : "Right") + name;
  8496. return dispatchKey(cm, addModifierNames(name, event), event, function (bound) {
  8497. if (typeof bound == "string") { bound = commands[bound]; }
  8498. if (!bound) { return false }
  8499. var done = false;
  8500. try {
  8501. if (cm.isReadOnly()) { cm.state.suppressEdits = true; }
  8502. done = bound(cm, pos) != Pass;
  8503. } finally {
  8504. cm.state.suppressEdits = false;
  8505. }
  8506. return done
  8507. })
  8508. }
  8509. function configureMouse(cm, repeat, event) {
  8510. var option = cm.getOption("configureMouse");
  8511. var value = option ? option(cm, repeat, event) : {};
  8512. if (value.unit == null) {
  8513. var rect = chromeOS ? event.shiftKey && event.metaKey : event.altKey;
  8514. value.unit = rect ? "rectangle" : repeat == "single" ? "char" : repeat == "double" ? "word" : "line";
  8515. }
  8516. if (value.extend == null || cm.doc.extend) { value.extend = cm.doc.extend || event.shiftKey; }
  8517. if (value.addNew == null) { value.addNew = mac ? event.metaKey : event.ctrlKey; }
  8518. if (value.moveOnDrag == null) { value.moveOnDrag = !(mac ? event.altKey : event.ctrlKey); }
  8519. return value
  8520. }
  8521. function leftButtonDown(cm, pos, repeat, event) {
  8522. if (ie) { setTimeout(bind(ensureFocus, cm), 0); }
  8523. else { cm.curOp.focus = activeElt(); }
  8524. var behavior = configureMouse(cm, repeat, event);
  8525. var sel = cm.doc.sel, contained;
  8526. if (cm.options.dragDrop && dragAndDrop && !cm.isReadOnly() &&
  8527. repeat == "single" && (contained = sel.contains(pos)) > -1 &&
  8528. (cmp((contained = sel.ranges[contained]).from(), pos) < 0 || pos.xRel > 0) &&
  8529. (cmp(contained.to(), pos) > 0 || pos.xRel < 0))
  8530. { leftButtonStartDrag(cm, event, pos, behavior); }
  8531. else
  8532. { leftButtonSelect(cm, event, pos, behavior); }
  8533. }
  8534. // Start a text drag. When it ends, see if any dragging actually
  8535. // happen, and treat as a click if it didn't.
  8536. function leftButtonStartDrag(cm, event, pos, behavior) {
  8537. var display = cm.display, moved = false;
  8538. var dragEnd = operation(cm, function (e) {
  8539. if (webkit) { display.scroller.draggable = false; }
  8540. cm.state.draggingText = false;
  8541. off(document, "mouseup", dragEnd);
  8542. off(document, "mousemove", mouseMove);
  8543. off(display.scroller, "dragstart", dragStart);
  8544. off(display.scroller, "drop", dragEnd);
  8545. if (!moved) {
  8546. e_preventDefault(e);
  8547. if (!behavior.addNew)
  8548. { extendSelection(cm.doc, pos, null, null, behavior.extend); }
  8549. // Work around unexplainable focus problem in IE9 (#2127) and Chrome (#3081)
  8550. if (webkit || ie && ie_version == 9)
  8551. { setTimeout(function () {document.body.focus(); display.input.focus();}, 20); }
  8552. else
  8553. { display.input.focus(); }
  8554. }
  8555. });
  8556. var mouseMove = function(e2) {
  8557. moved = moved || Math.abs(event.clientX - e2.clientX) + Math.abs(event.clientY - e2.clientY) >= 10;
  8558. };
  8559. var dragStart = function () { return moved = true; };
  8560. // Let the drag handler handle this.
  8561. if (webkit) { display.scroller.draggable = true; }
  8562. cm.state.draggingText = dragEnd;
  8563. dragEnd.copy = !behavior.moveOnDrag;
  8564. // IE's approach to draggable
  8565. if (display.scroller.dragDrop) { display.scroller.dragDrop(); }
  8566. on(document, "mouseup", dragEnd);
  8567. on(document, "mousemove", mouseMove);
  8568. on(display.scroller, "dragstart", dragStart);
  8569. on(display.scroller, "drop", dragEnd);
  8570. delayBlurEvent(cm);
  8571. setTimeout(function () { return display.input.focus(); }, 20);
  8572. }
  8573. function rangeForUnit(cm, pos, unit) {
  8574. if (unit == "char") { return new Range(pos, pos) }
  8575. if (unit == "word") { return cm.findWordAt(pos) }
  8576. if (unit == "line") { return new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))) }
  8577. var result = unit(cm, pos);
  8578. return new Range(result.from, result.to)
  8579. }
  8580. // Normal selection, as opposed to text dragging.
  8581. function leftButtonSelect(cm, event, start, behavior) {
  8582. var display = cm.display, doc = cm.doc;
  8583. e_preventDefault(event);
  8584. var ourRange, ourIndex, startSel = doc.sel, ranges = startSel.ranges;
  8585. if (behavior.addNew && !behavior.extend) {
  8586. ourIndex = doc.sel.contains(start);
  8587. if (ourIndex > -1)
  8588. { ourRange = ranges[ourIndex]; }
  8589. else
  8590. { ourRange = new Range(start, start); }
  8591. } else {
  8592. ourRange = doc.sel.primary();
  8593. ourIndex = doc.sel.primIndex;
  8594. }
  8595. if (behavior.unit == "rectangle") {
  8596. if (!behavior.addNew) { ourRange = new Range(start, start); }
  8597. start = posFromMouse(cm, event, true, true);
  8598. ourIndex = -1;
  8599. } else {
  8600. var range$$1 = rangeForUnit(cm, start, behavior.unit);
  8601. if (behavior.extend)
  8602. { ourRange = extendRange(ourRange, range$$1.anchor, range$$1.head, behavior.extend); }
  8603. else
  8604. { ourRange = range$$1; }
  8605. }
  8606. if (!behavior.addNew) {
  8607. ourIndex = 0;
  8608. setSelection(doc, new Selection([ourRange], 0), sel_mouse);
  8609. startSel = doc.sel;
  8610. } else if (ourIndex == -1) {
  8611. ourIndex = ranges.length;
  8612. setSelection(doc, normalizeSelection(ranges.concat([ourRange]), ourIndex),
  8613. {scroll: false, origin: "*mouse"});
  8614. } else if (ranges.length > 1 && ranges[ourIndex].empty() && behavior.unit == "char" && !behavior.extend) {
  8615. setSelection(doc, normalizeSelection(ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0),
  8616. {scroll: false, origin: "*mouse"});
  8617. startSel = doc.sel;
  8618. } else {
  8619. replaceOneSelection(doc, ourIndex, ourRange, sel_mouse);
  8620. }
  8621. var lastPos = start;
  8622. function extendTo(pos) {
  8623. if (cmp(lastPos, pos) == 0) { return }
  8624. lastPos = pos;
  8625. if (behavior.unit == "rectangle") {
  8626. var ranges = [], tabSize = cm.options.tabSize;
  8627. var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize);
  8628. var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize);
  8629. var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol);
  8630. for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line));
  8631. line <= end; line++) {
  8632. var text = getLine(doc, line).text, leftPos = findColumn(text, left, tabSize);
  8633. if (left == right)
  8634. { ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos))); }
  8635. else if (text.length > leftPos)
  8636. { ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize)))); }
  8637. }
  8638. if (!ranges.length) { ranges.push(new Range(start, start)); }
  8639. setSelection(doc, normalizeSelection(startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex),
  8640. {origin: "*mouse", scroll: false});
  8641. cm.scrollIntoView(pos);
  8642. } else {
  8643. var oldRange = ourRange;
  8644. var range$$1 = rangeForUnit(cm, pos, behavior.unit);
  8645. var anchor = oldRange.anchor, head;
  8646. if (cmp(range$$1.anchor, anchor) > 0) {
  8647. head = range$$1.head;
  8648. anchor = minPos(oldRange.from(), range$$1.anchor);
  8649. } else {
  8650. head = range$$1.anchor;
  8651. anchor = maxPos(oldRange.to(), range$$1.head);
  8652. }
  8653. var ranges$1 = startSel.ranges.slice(0);
  8654. ranges$1[ourIndex] = bidiSimplify(cm, new Range(clipPos(doc, anchor), head));
  8655. setSelection(doc, normalizeSelection(ranges$1, ourIndex), sel_mouse);
  8656. }
  8657. }
  8658. var editorSize = display.wrapper.getBoundingClientRect();
  8659. // Used to ensure timeout re-tries don't fire when another extend
  8660. // happened in the meantime (clearTimeout isn't reliable -- at
  8661. // least on Chrome, the timeouts still happen even when cleared,
  8662. // if the clear happens after their scheduled firing time).
  8663. var counter = 0;
  8664. function extend(e) {
  8665. var curCount = ++counter;
  8666. var cur = posFromMouse(cm, e, true, behavior.unit == "rectangle");
  8667. if (!cur) { return }
  8668. if (cmp(cur, lastPos) != 0) {
  8669. cm.curOp.focus = activeElt();
  8670. extendTo(cur);
  8671. var visible = visibleLines(display, doc);
  8672. if (cur.line >= visible.to || cur.line < visible.from)
  8673. { setTimeout(operation(cm, function () {if (counter == curCount) { extend(e); }}), 150); }
  8674. } else {
  8675. var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0;
  8676. if (outside) { setTimeout(operation(cm, function () {
  8677. if (counter != curCount) { return }
  8678. display.scroller.scrollTop += outside;
  8679. extend(e);
  8680. }), 50); }
  8681. }
  8682. }
  8683. function done(e) {
  8684. cm.state.selectingText = false;
  8685. counter = Infinity;
  8686. e_preventDefault(e);
  8687. display.input.focus();
  8688. off(document, "mousemove", move);
  8689. off(document, "mouseup", up);
  8690. doc.history.lastSelOrigin = null;
  8691. }
  8692. var move = operation(cm, function (e) {
  8693. if (!e_button(e)) { done(e); }
  8694. else { extend(e); }
  8695. });
  8696. var up = operation(cm, done);
  8697. cm.state.selectingText = up;
  8698. on(document, "mousemove", move);
  8699. on(document, "mouseup", up);
  8700. }
  8701. // Used when mouse-selecting to adjust the anchor to the proper side
  8702. // of a bidi jump depending on the visual position of the head.
  8703. function bidiSimplify(cm, range$$1) {
  8704. var anchor = range$$1.anchor;
  8705. var head = range$$1.head;
  8706. var anchorLine = getLine(cm.doc, anchor.line);
  8707. if (cmp(anchor, head) == 0 && anchor.sticky == head.sticky) { return range$$1 }
  8708. var order = getOrder(anchorLine);
  8709. if (!order) { return range$$1 }
  8710. var index = getBidiPartAt(order, anchor.ch, anchor.sticky), part = order[index];
  8711. if (part.from != anchor.ch && part.to != anchor.ch) { return range$$1 }
  8712. var boundary = index + ((part.from == anchor.ch) == (part.level != 1) ? 0 : 1);
  8713. if (boundary == 0 || boundary == order.length) { return range$$1 }
  8714. // Compute the relative visual position of the head compared to the
  8715. // anchor (<0 is to the left, >0 to the right)
  8716. var leftSide;
  8717. if (head.line != anchor.line) {
  8718. leftSide = (head.line - anchor.line) * (cm.doc.direction == "ltr" ? 1 : -1) > 0;
  8719. } else {
  8720. var headIndex = getBidiPartAt(order, head.ch, head.sticky);
  8721. var dir = headIndex - index || (head.ch - anchor.ch) * (part.level == 1 ? -1 : 1);
  8722. if (headIndex == boundary - 1 || headIndex == boundary)
  8723. { leftSide = dir < 0; }
  8724. else
  8725. { leftSide = dir > 0; }
  8726. }
  8727. var usePart = order[boundary + (leftSide ? -1 : 0)];
  8728. var from = leftSide == (usePart.level == 1);
  8729. var ch = from ? usePart.from : usePart.to, sticky = from ? "after" : "before";
  8730. return anchor.ch == ch && anchor.sticky == sticky ? range$$1 : new Range(new Pos(anchor.line, ch, sticky), head)
  8731. }
  8732. // Determines whether an event happened in the gutter, and fires the
  8733. // handlers for the corresponding event.
  8734. function gutterEvent(cm, e, type, prevent) {
  8735. var mX, mY;
  8736. if (e.touches) {
  8737. mX = e.touches[0].clientX;
  8738. mY = e.touches[0].clientY;
  8739. } else {
  8740. try { mX = e.clientX; mY = e.clientY; }
  8741. catch(e) { return false }
  8742. }
  8743. if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) { return false }
  8744. if (prevent) { e_preventDefault(e); }
  8745. var display = cm.display;
  8746. var lineBox = display.lineDiv.getBoundingClientRect();
  8747. if (mY > lineBox.bottom || !hasHandler(cm, type)) { return e_defaultPrevented(e) }
  8748. mY -= lineBox.top - display.viewOffset;
  8749. for (var i = 0; i < cm.options.gutters.length; ++i) {
  8750. var g = display.gutters.childNodes[i];
  8751. if (g && g.getBoundingClientRect().right >= mX) {
  8752. var line = lineAtHeight(cm.doc, mY);
  8753. var gutter = cm.options.gutters[i];
  8754. signal(cm, type, cm, line, gutter, e);
  8755. return e_defaultPrevented(e)
  8756. }
  8757. }
  8758. }
  8759. function clickInGutter(cm, e) {
  8760. return gutterEvent(cm, e, "gutterClick", true)
  8761. }
  8762. // CONTEXT MENU HANDLING
  8763. // To make the context menu work, we need to briefly unhide the
  8764. // textarea (making it as unobtrusive as possible) to let the
  8765. // right-click take effect on it.
  8766. function onContextMenu(cm, e) {
  8767. if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) { return }
  8768. if (signalDOMEvent(cm, e, "contextmenu")) { return }
  8769. cm.display.input.onContextMenu(e);
  8770. }
  8771. function contextMenuInGutter(cm, e) {
  8772. if (!hasHandler(cm, "gutterContextMenu")) { return false }
  8773. return gutterEvent(cm, e, "gutterContextMenu", false)
  8774. }
  8775. function themeChanged(cm) {
  8776. cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") +
  8777. cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-");
  8778. clearCaches(cm);
  8779. }
  8780. var Init = {toString: function(){return "CodeMirror.Init"}};
  8781. var defaults = {};
  8782. var optionHandlers = {};
  8783. function defineOptions(CodeMirror) {
  8784. var optionHandlers = CodeMirror.optionHandlers;
  8785. function option(name, deflt, handle, notOnInit) {
  8786. CodeMirror.defaults[name] = deflt;
  8787. if (handle) { optionHandlers[name] =
  8788. notOnInit ? function (cm, val, old) {if (old != Init) { handle(cm, val, old); }} : handle; }
  8789. }
  8790. CodeMirror.defineOption = option;
  8791. // Passed to option handlers when there is no old value.
  8792. CodeMirror.Init = Init;
  8793. // These two are, on init, called from the constructor because they
  8794. // have to be initialized before the editor can start at all.
  8795. option("value", "", function (cm, val) { return cm.setValue(val); }, true);
  8796. option("mode", null, function (cm, val) {
  8797. cm.doc.modeOption = val;
  8798. loadMode(cm);
  8799. }, true);
  8800. option("indentUnit", 2, loadMode, true);
  8801. option("indentWithTabs", false);
  8802. option("smartIndent", true);
  8803. option("tabSize", 4, function (cm) {
  8804. resetModeState(cm);
  8805. clearCaches(cm);
  8806. regChange(cm);
  8807. }, true);
  8808. option("lineSeparator", null, function (cm, val) {
  8809. cm.doc.lineSep = val;
  8810. if (!val) { return }
  8811. var newBreaks = [], lineNo = cm.doc.first;
  8812. cm.doc.iter(function (line) {
  8813. for (var pos = 0;;) {
  8814. var found = line.text.indexOf(val, pos);
  8815. if (found == -1) { break }
  8816. pos = found + val.length;
  8817. newBreaks.push(Pos(lineNo, found));
  8818. }
  8819. lineNo++;
  8820. });
  8821. for (var i = newBreaks.length - 1; i >= 0; i--)
  8822. { replaceRange(cm.doc, val, newBreaks[i], Pos(newBreaks[i].line, newBreaks[i].ch + val.length)); }
  8823. });
  8824. option("specialChars", /[\u0000-\u001f\u007f-\u009f\u00ad\u061c\u200b-\u200f\u2028\u2029\ufeff]/g, function (cm, val, old) {
  8825. cm.state.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g");
  8826. if (old != Init) { cm.refresh(); }
  8827. });
  8828. option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function (cm) { return cm.refresh(); }, true);
  8829. option("electricChars", true);
  8830. option("inputStyle", mobile ? "contenteditable" : "textarea", function () {
  8831. throw new Error("inputStyle can not (yet) be changed in a running editor") // FIXME
  8832. }, true);
  8833. option("spellcheck", false, function (cm, val) { return cm.getInputField().spellcheck = val; }, true);
  8834. option("rtlMoveVisually", !windows);
  8835. option("wholeLineUpdateBefore", true);
  8836. option("theme", "default", function (cm) {
  8837. themeChanged(cm);
  8838. guttersChanged(cm);
  8839. }, true);
  8840. option("keyMap", "default", function (cm, val, old) {
  8841. var next = getKeyMap(val);
  8842. var prev = old != Init && getKeyMap(old);
  8843. if (prev && prev.detach) { prev.detach(cm, next); }
  8844. if (next.attach) { next.attach(cm, prev || null); }
  8845. });
  8846. option("extraKeys", null);
  8847. option("configureMouse", null);
  8848. option("lineWrapping", false, wrappingChanged, true);
  8849. option("gutters", [], function (cm) {
  8850. setGuttersForLineNumbers(cm.options);
  8851. guttersChanged(cm);
  8852. }, true);
  8853. option("fixedGutter", true, function (cm, val) {
  8854. cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0";
  8855. cm.refresh();
  8856. }, true);
  8857. option("coverGutterNextToScrollbar", false, function (cm) { return updateScrollbars(cm); }, true);
  8858. option("scrollbarStyle", "native", function (cm) {
  8859. initScrollbars(cm);
  8860. updateScrollbars(cm);
  8861. cm.display.scrollbars.setScrollTop(cm.doc.scrollTop);
  8862. cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft);
  8863. }, true);
  8864. option("lineNumbers", false, function (cm) {
  8865. setGuttersForLineNumbers(cm.options);
  8866. guttersChanged(cm);
  8867. }, true);
  8868. option("firstLineNumber", 1, guttersChanged, true);
  8869. option("lineNumberFormatter", function (integer) { return integer; }, guttersChanged, true);
  8870. option("showCursorWhenSelecting", false, updateSelection, true);
  8871. option("resetSelectionOnContextMenu", true);
  8872. option("lineWiseCopyCut", true);
  8873. option("pasteLinesPerSelection", true);
  8874. option("readOnly", false, function (cm, val) {
  8875. if (val == "nocursor") {
  8876. onBlur(cm);
  8877. cm.display.input.blur();
  8878. }
  8879. cm.display.input.readOnlyChanged(val);
  8880. });
  8881. option("disableInput", false, function (cm, val) {if (!val) { cm.display.input.reset(); }}, true);
  8882. option("dragDrop", true, dragDropChanged);
  8883. option("allowDropFileTypes", null);
  8884. option("cursorBlinkRate", 530);
  8885. option("cursorScrollMargin", 0);
  8886. option("cursorHeight", 1, updateSelection, true);
  8887. option("singleCursorHeightPerLine", true, updateSelection, true);
  8888. option("workTime", 100);
  8889. option("workDelay", 100);
  8890. option("flattenSpans", true, resetModeState, true);
  8891. option("addModeClass", false, resetModeState, true);
  8892. option("pollInterval", 100);
  8893. option("undoDepth", 200, function (cm, val) { return cm.doc.history.undoDepth = val; });
  8894. option("historyEventDelay", 1250);
  8895. option("viewportMargin", 10, function (cm) { return cm.refresh(); }, true);
  8896. option("maxHighlightLength", 10000, resetModeState, true);
  8897. option("moveInputWithCursor", true, function (cm, val) {
  8898. if (!val) { cm.display.input.resetPosition(); }
  8899. });
  8900. option("tabindex", null, function (cm, val) { return cm.display.input.getField().tabIndex = val || ""; });
  8901. option("autofocus", null);
  8902. option("direction", "ltr", function (cm, val) { return cm.doc.setDirection(val); }, true);
  8903. }
  8904. function guttersChanged(cm) {
  8905. updateGutters(cm);
  8906. regChange(cm);
  8907. alignHorizontally(cm);
  8908. }
  8909. function dragDropChanged(cm, value, old) {
  8910. var wasOn = old && old != Init;
  8911. if (!value != !wasOn) {
  8912. var funcs = cm.display.dragFunctions;
  8913. var toggle = value ? on : off;
  8914. toggle(cm.display.scroller, "dragstart", funcs.start);
  8915. toggle(cm.display.scroller, "dragenter", funcs.enter);
  8916. toggle(cm.display.scroller, "dragover", funcs.over);
  8917. toggle(cm.display.scroller, "dragleave", funcs.leave);
  8918. toggle(cm.display.scroller, "drop", funcs.drop);
  8919. }
  8920. }
  8921. function wrappingChanged(cm) {
  8922. if (cm.options.lineWrapping) {
  8923. addClass(cm.display.wrapper, "CodeMirror-wrap");
  8924. cm.display.sizer.style.minWidth = "";
  8925. cm.display.sizerWidth = null;
  8926. } else {
  8927. rmClass(cm.display.wrapper, "CodeMirror-wrap");
  8928. findMaxLine(cm);
  8929. }
  8930. estimateLineHeights(cm);
  8931. regChange(cm);
  8932. clearCaches(cm);
  8933. setTimeout(function () { return updateScrollbars(cm); }, 100);
  8934. }
  8935. // A CodeMirror instance represents an editor. This is the object
  8936. // that user code is usually dealing with.
  8937. function CodeMirror$1(place, options) {
  8938. var this$1 = this;
  8939. if (!(this instanceof CodeMirror$1)) { return new CodeMirror$1(place, options) }
  8940. this.options = options = options ? copyObj(options) : {};
  8941. // Determine effective options based on given values and defaults.
  8942. copyObj(defaults, options, false);
  8943. setGuttersForLineNumbers(options);
  8944. var doc = options.value;
  8945. if (typeof doc == "string") { doc = new Doc(doc, options.mode, null, options.lineSeparator, options.direction); }
  8946. this.doc = doc;
  8947. var input = new CodeMirror$1.inputStyles[options.inputStyle](this);
  8948. var display = this.display = new Display(place, doc, input);
  8949. display.wrapper.CodeMirror = this;
  8950. updateGutters(this);
  8951. themeChanged(this);
  8952. if (options.lineWrapping)
  8953. { this.display.wrapper.className += " CodeMirror-wrap"; }
  8954. initScrollbars(this);
  8955. this.state = {
  8956. keyMaps: [], // stores maps added by addKeyMap
  8957. overlays: [], // highlighting overlays, as added by addOverlay
  8958. modeGen: 0, // bumped when mode/overlay changes, used to invalidate highlighting info
  8959. overwrite: false,
  8960. delayingBlurEvent: false,
  8961. focused: false,
  8962. suppressEdits: false, // used to disable editing during key handlers when in readOnly mode
  8963. pasteIncoming: false, cutIncoming: false, // help recognize paste/cut edits in input.poll
  8964. selectingText: false,
  8965. draggingText: false,
  8966. highlight: new Delayed(), // stores highlight worker timeout
  8967. keySeq: null, // Unfinished key sequence
  8968. specialChars: null
  8969. };
  8970. if (options.autofocus && !mobile) { display.input.focus(); }
  8971. // Override magic textarea content restore that IE sometimes does
  8972. // on our hidden textarea on reload
  8973. if (ie && ie_version < 11) { setTimeout(function () { return this$1.display.input.reset(true); }, 20); }
  8974. registerEventHandlers(this);
  8975. ensureGlobalHandlers();
  8976. startOperation(this);
  8977. this.curOp.forceUpdate = true;
  8978. attachDoc(this, doc);
  8979. if ((options.autofocus && !mobile) || this.hasFocus())
  8980. { setTimeout(bind(onFocus, this), 20); }
  8981. else
  8982. { onBlur(this); }
  8983. for (var opt in optionHandlers) { if (optionHandlers.hasOwnProperty(opt))
  8984. { optionHandlers[opt](this$1, options[opt], Init); } }
  8985. maybeUpdateLineNumberWidth(this);
  8986. if (options.finishInit) { options.finishInit(this); }
  8987. for (var i = 0; i < initHooks.length; ++i) { initHooks[i](this$1); }
  8988. endOperation(this);
  8989. // Suppress optimizelegibility in Webkit, since it breaks text
  8990. // measuring on line wrapping boundaries.
  8991. if (webkit && options.lineWrapping &&
  8992. getComputedStyle(display.lineDiv).textRendering == "optimizelegibility")
  8993. { display.lineDiv.style.textRendering = "auto"; }
  8994. }
  8995. // The default configuration options.
  8996. CodeMirror$1.defaults = defaults;
  8997. // Functions to run when options are changed.
  8998. CodeMirror$1.optionHandlers = optionHandlers;
  8999. // Attach the necessary event handlers when initializing the editor
  9000. function registerEventHandlers(cm) {
  9001. var d = cm.display;
  9002. on(d.scroller, "mousedown", operation(cm, onMouseDown));
  9003. // Older IE's will not fire a second mousedown for a double click
  9004. if (ie && ie_version < 11)
  9005. { on(d.scroller, "dblclick", operation(cm, function (e) {
  9006. if (signalDOMEvent(cm, e)) { return }
  9007. var pos = posFromMouse(cm, e);
  9008. if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) { return }
  9009. e_preventDefault(e);
  9010. var word = cm.findWordAt(pos);
  9011. extendSelection(cm.doc, word.anchor, word.head);
  9012. })); }
  9013. else
  9014. { on(d.scroller, "dblclick", function (e) { return signalDOMEvent(cm, e) || e_preventDefault(e); }); }
  9015. // Some browsers fire contextmenu *after* opening the menu, at
  9016. // which point we can't mess with it anymore. Context menu is
  9017. // handled in onMouseDown for these browsers.
  9018. if (!captureRightClick) { on(d.scroller, "contextmenu", function (e) { return onContextMenu(cm, e); }); }
  9019. // Used to suppress mouse event handling when a touch happens
  9020. var touchFinished, prevTouch = {end: 0};
  9021. function finishTouch() {
  9022. if (d.activeTouch) {
  9023. touchFinished = setTimeout(function () { return d.activeTouch = null; }, 1000);
  9024. prevTouch = d.activeTouch;
  9025. prevTouch.end = +new Date;
  9026. }
  9027. }
  9028. function isMouseLikeTouchEvent(e) {
  9029. if (e.touches.length != 1) { return false }
  9030. var touch = e.touches[0];
  9031. return touch.radiusX <= 1 && touch.radiusY <= 1
  9032. }
  9033. function farAway(touch, other) {
  9034. if (other.left == null) { return true }
  9035. var dx = other.left - touch.left, dy = other.top - touch.top;
  9036. return dx * dx + dy * dy > 20 * 20
  9037. }
  9038. on(d.scroller, "touchstart", function (e) {
  9039. if (!signalDOMEvent(cm, e) && !isMouseLikeTouchEvent(e) && !clickInGutter(cm, e)) {
  9040. d.input.ensurePolled();
  9041. clearTimeout(touchFinished);
  9042. var now = +new Date;
  9043. d.activeTouch = {start: now, moved: false,
  9044. prev: now - prevTouch.end <= 300 ? prevTouch : null};
  9045. if (e.touches.length == 1) {
  9046. d.activeTouch.left = e.touches[0].pageX;
  9047. d.activeTouch.top = e.touches[0].pageY;
  9048. }
  9049. }
  9050. });
  9051. on(d.scroller, "touchmove", function () {
  9052. if (d.activeTouch) { d.activeTouch.moved = true; }
  9053. });
  9054. on(d.scroller, "touchend", function (e) {
  9055. var touch = d.activeTouch;
  9056. if (touch && !eventInWidget(d, e) && touch.left != null &&
  9057. !touch.moved && new Date - touch.start < 300) {
  9058. var pos = cm.coordsChar(d.activeTouch, "page"), range;
  9059. if (!touch.prev || farAway(touch, touch.prev)) // Single tap
  9060. { range = new Range(pos, pos); }
  9061. else if (!touch.prev.prev || farAway(touch, touch.prev.prev)) // Double tap
  9062. { range = cm.findWordAt(pos); }
  9063. else // Triple tap
  9064. { range = new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))); }
  9065. cm.setSelection(range.anchor, range.head);
  9066. cm.focus();
  9067. e_preventDefault(e);
  9068. }
  9069. finishTouch();
  9070. });
  9071. on(d.scroller, "touchcancel", finishTouch);
  9072. // Sync scrolling between fake scrollbars and real scrollable
  9073. // area, ensure viewport is updated when scrolling.
  9074. on(d.scroller, "scroll", function () {
  9075. if (d.scroller.clientHeight) {
  9076. updateScrollTop(cm, d.scroller.scrollTop);
  9077. setScrollLeft(cm, d.scroller.scrollLeft, true);
  9078. signal(cm, "scroll", cm);
  9079. }
  9080. });
  9081. // Listen to wheel events in order to try and update the viewport on time.
  9082. on(d.scroller, "mousewheel", function (e) { return onScrollWheel(cm, e); });
  9083. on(d.scroller, "DOMMouseScroll", function (e) { return onScrollWheel(cm, e); });
  9084. // Prevent wrapper from ever scrolling
  9085. on(d.wrapper, "scroll", function () { return d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; });
  9086. d.dragFunctions = {
  9087. enter: function (e) {if (!signalDOMEvent(cm, e)) { e_stop(e); }},
  9088. over: function (e) {if (!signalDOMEvent(cm, e)) { onDragOver(cm, e); e_stop(e); }},
  9089. start: function (e) { return onDragStart(cm, e); },
  9090. drop: operation(cm, onDrop),
  9091. leave: function (e) {if (!signalDOMEvent(cm, e)) { clearDragCursor(cm); }}
  9092. };
  9093. var inp = d.input.getField();
  9094. on(inp, "keyup", function (e) { return onKeyUp.call(cm, e); });
  9095. on(inp, "keydown", operation(cm, onKeyDown));
  9096. on(inp, "keypress", operation(cm, onKeyPress));
  9097. on(inp, "focus", function (e) { return onFocus(cm, e); });
  9098. on(inp, "blur", function (e) { return onBlur(cm, e); });
  9099. }
  9100. var initHooks = [];
  9101. CodeMirror$1.defineInitHook = function (f) { return initHooks.push(f); };
  9102. // Indent the given line. The how parameter can be "smart",
  9103. // "add"/null, "subtract", or "prev". When aggressive is false
  9104. // (typically set to true for forced single-line indents), empty
  9105. // lines are not indented, and places where the mode returns Pass
  9106. // are left alone.
  9107. function indentLine(cm, n, how, aggressive) {
  9108. var doc = cm.doc, state;
  9109. if (how == null) { how = "add"; }
  9110. if (how == "smart") {
  9111. // Fall back to "prev" when the mode doesn't have an indentation
  9112. // method.
  9113. if (!doc.mode.indent) { how = "prev"; }
  9114. else { state = getContextBefore(cm, n).state; }
  9115. }
  9116. var tabSize = cm.options.tabSize;
  9117. var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize);
  9118. if (line.stateAfter) { line.stateAfter = null; }
  9119. var curSpaceString = line.text.match(/^\s*/)[0], indentation;
  9120. if (!aggressive && !/\S/.test(line.text)) {
  9121. indentation = 0;
  9122. how = "not";
  9123. } else if (how == "smart") {
  9124. indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text);
  9125. if (indentation == Pass || indentation > 150) {
  9126. if (!aggressive) { return }
  9127. how = "prev";
  9128. }
  9129. }
  9130. if (how == "prev") {
  9131. if (n > doc.first) { indentation = countColumn(getLine(doc, n-1).text, null, tabSize); }
  9132. else { indentation = 0; }
  9133. } else if (how == "add") {
  9134. indentation = curSpace + cm.options.indentUnit;
  9135. } else if (how == "subtract") {
  9136. indentation = curSpace - cm.options.indentUnit;
  9137. } else if (typeof how == "number") {
  9138. indentation = curSpace + how;
  9139. }
  9140. indentation = Math.max(0, indentation);
  9141. var indentString = "", pos = 0;
  9142. if (cm.options.indentWithTabs)
  9143. { for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";} }
  9144. if (pos < indentation) { indentString += spaceStr(indentation - pos); }
  9145. if (indentString != curSpaceString) {
  9146. replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input");
  9147. line.stateAfter = null;
  9148. return true
  9149. } else {
  9150. // Ensure that, if the cursor was in the whitespace at the start
  9151. // of the line, it is moved to the end of that space.
  9152. for (var i$1 = 0; i$1 < doc.sel.ranges.length; i$1++) {
  9153. var range = doc.sel.ranges[i$1];
  9154. if (range.head.line == n && range.head.ch < curSpaceString.length) {
  9155. var pos$1 = Pos(n, curSpaceString.length);
  9156. replaceOneSelection(doc, i$1, new Range(pos$1, pos$1));
  9157. break
  9158. }
  9159. }
  9160. }
  9161. }
  9162. // This will be set to a {lineWise: bool, text: [string]} object, so
  9163. // that, when pasting, we know what kind of selections the copied
  9164. // text was made out of.
  9165. var lastCopied = null;
  9166. function setLastCopied(newLastCopied) {
  9167. lastCopied = newLastCopied;
  9168. }
  9169. function applyTextInput(cm, inserted, deleted, sel, origin) {
  9170. var doc = cm.doc;
  9171. cm.display.shift = false;
  9172. if (!sel) { sel = doc.sel; }
  9173. var paste = cm.state.pasteIncoming || origin == "paste";
  9174. var textLines = splitLinesAuto(inserted), multiPaste = null;
  9175. // When pasing N lines into N selections, insert one line per selection
  9176. if (paste && sel.ranges.length > 1) {
  9177. if (lastCopied && lastCopied.text.join("\n") == inserted) {
  9178. if (sel.ranges.length % lastCopied.text.length == 0) {
  9179. multiPaste = [];
  9180. for (var i = 0; i < lastCopied.text.length; i++)
  9181. { multiPaste.push(doc.splitLines(lastCopied.text[i])); }
  9182. }
  9183. } else if (textLines.length == sel.ranges.length && cm.options.pasteLinesPerSelection) {
  9184. multiPaste = map(textLines, function (l) { return [l]; });
  9185. }
  9186. }
  9187. var updateInput;
  9188. // Normal behavior is to insert the new text into every selection
  9189. for (var i$1 = sel.ranges.length - 1; i$1 >= 0; i$1--) {
  9190. var range$$1 = sel.ranges[i$1];
  9191. var from = range$$1.from(), to = range$$1.to();
  9192. if (range$$1.empty()) {
  9193. if (deleted && deleted > 0) // Handle deletion
  9194. { from = Pos(from.line, from.ch - deleted); }
  9195. else if (cm.state.overwrite && !paste) // Handle overwrite
  9196. { to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length)); }
  9197. else if (lastCopied && lastCopied.lineWise && lastCopied.text.join("\n") == inserted)
  9198. { from = to = Pos(from.line, 0); }
  9199. }
  9200. updateInput = cm.curOp.updateInput;
  9201. var changeEvent = {from: from, to: to, text: multiPaste ? multiPaste[i$1 % multiPaste.length] : textLines,
  9202. origin: origin || (paste ? "paste" : cm.state.cutIncoming ? "cut" : "+input")};
  9203. makeChange(cm.doc, changeEvent);
  9204. signalLater(cm, "inputRead", cm, changeEvent);
  9205. }
  9206. if (inserted && !paste)
  9207. { triggerElectric(cm, inserted); }
  9208. ensureCursorVisible(cm);
  9209. cm.curOp.updateInput = updateInput;
  9210. cm.curOp.typing = true;
  9211. cm.state.pasteIncoming = cm.state.cutIncoming = false;
  9212. }
  9213. function handlePaste(e, cm) {
  9214. var pasted = e.clipboardData && e.clipboardData.getData("Text");
  9215. if (pasted) {
  9216. e.preventDefault();
  9217. if (!cm.isReadOnly() && !cm.options.disableInput)
  9218. { runInOp(cm, function () { return applyTextInput(cm, pasted, 0, null, "paste"); }); }
  9219. return true
  9220. }
  9221. }
  9222. function triggerElectric(cm, inserted) {
  9223. // When an 'electric' character is inserted, immediately trigger a reindent
  9224. if (!cm.options.electricChars || !cm.options.smartIndent) { return }
  9225. var sel = cm.doc.sel;
  9226. for (var i = sel.ranges.length - 1; i >= 0; i--) {
  9227. var range$$1 = sel.ranges[i];
  9228. if (range$$1.head.ch > 100 || (i && sel.ranges[i - 1].head.line == range$$1.head.line)) { continue }
  9229. var mode = cm.getModeAt(range$$1.head);
  9230. var indented = false;
  9231. if (mode.electricChars) {
  9232. for (var j = 0; j < mode.electricChars.length; j++)
  9233. { if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) {
  9234. indented = indentLine(cm, range$$1.head.line, "smart");
  9235. break
  9236. } }
  9237. } else if (mode.electricInput) {
  9238. if (mode.electricInput.test(getLine(cm.doc, range$$1.head.line).text.slice(0, range$$1.head.ch)))
  9239. { indented = indentLine(cm, range$$1.head.line, "smart"); }
  9240. }
  9241. if (indented) { signalLater(cm, "electricInput", cm, range$$1.head.line); }
  9242. }
  9243. }
  9244. function copyableRanges(cm) {
  9245. var text = [], ranges = [];
  9246. for (var i = 0; i < cm.doc.sel.ranges.length; i++) {
  9247. var line = cm.doc.sel.ranges[i].head.line;
  9248. var lineRange = {anchor: Pos(line, 0), head: Pos(line + 1, 0)};
  9249. ranges.push(lineRange);
  9250. text.push(cm.getRange(lineRange.anchor, lineRange.head));
  9251. }
  9252. return {text: text, ranges: ranges}
  9253. }
  9254. function disableBrowserMagic(field, spellcheck) {
  9255. field.setAttribute("autocorrect", "off");
  9256. field.setAttribute("autocapitalize", "off");
  9257. field.setAttribute("spellcheck", !!spellcheck);
  9258. }
  9259. function hiddenTextarea() {
  9260. var te = elt("textarea", null, null, "position: absolute; bottom: -1em; padding: 0; width: 1px; height: 1em; outline: none");
  9261. var div = elt("div", [te], null, "overflow: hidden; position: relative; width: 3px; height: 0px;");
  9262. // The textarea is kept positioned near the cursor to prevent the
  9263. // fact that it'll be scrolled into view on input from scrolling
  9264. // our fake cursor out of view. On webkit, when wrap=off, paste is
  9265. // very slow. So make the area wide instead.
  9266. if (webkit) { te.style.width = "1000px"; }
  9267. else { te.setAttribute("wrap", "off"); }
  9268. // If border: 0; -- iOS fails to open keyboard (issue #1287)
  9269. if (ios) { te.style.border = "1px solid black"; }
  9270. disableBrowserMagic(te);
  9271. return div
  9272. }
  9273. // The publicly visible API. Note that methodOp(f) means
  9274. // 'wrap f in an operation, performed on its `this` parameter'.
  9275. // This is not the complete set of editor methods. Most of the
  9276. // methods defined on the Doc type are also injected into
  9277. // CodeMirror.prototype, for backwards compatibility and
  9278. // convenience.
  9279. var addEditorMethods = function(CodeMirror) {
  9280. var optionHandlers = CodeMirror.optionHandlers;
  9281. var helpers = CodeMirror.helpers = {};
  9282. CodeMirror.prototype = {
  9283. constructor: CodeMirror,
  9284. focus: function(){window.focus(); this.display.input.focus();},
  9285. setOption: function(option, value) {
  9286. var options = this.options, old = options[option];
  9287. if (options[option] == value && option != "mode") { return }
  9288. options[option] = value;
  9289. if (optionHandlers.hasOwnProperty(option))
  9290. { operation(this, optionHandlers[option])(this, value, old); }
  9291. signal(this, "optionChange", this, option);
  9292. },
  9293. getOption: function(option) {return this.options[option]},
  9294. getDoc: function() {return this.doc},
  9295. addKeyMap: function(map$$1, bottom) {
  9296. this.state.keyMaps[bottom ? "push" : "unshift"](getKeyMap(map$$1));
  9297. },
  9298. removeKeyMap: function(map$$1) {
  9299. var maps = this.state.keyMaps;
  9300. for (var i = 0; i < maps.length; ++i)
  9301. { if (maps[i] == map$$1 || maps[i].name == map$$1) {
  9302. maps.splice(i, 1);
  9303. return true
  9304. } }
  9305. },
  9306. addOverlay: methodOp(function(spec, options) {
  9307. var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec);
  9308. if (mode.startState) { throw new Error("Overlays may not be stateful.") }
  9309. insertSorted(this.state.overlays,
  9310. {mode: mode, modeSpec: spec, opaque: options && options.opaque,
  9311. priority: (options && options.priority) || 0},
  9312. function (overlay) { return overlay.priority; });
  9313. this.state.modeGen++;
  9314. regChange(this);
  9315. }),
  9316. removeOverlay: methodOp(function(spec) {
  9317. var this$1 = this;
  9318. var overlays = this.state.overlays;
  9319. for (var i = 0; i < overlays.length; ++i) {
  9320. var cur = overlays[i].modeSpec;
  9321. if (cur == spec || typeof spec == "string" && cur.name == spec) {
  9322. overlays.splice(i, 1);
  9323. this$1.state.modeGen++;
  9324. regChange(this$1);
  9325. return
  9326. }
  9327. }
  9328. }),
  9329. indentLine: methodOp(function(n, dir, aggressive) {
  9330. if (typeof dir != "string" && typeof dir != "number") {
  9331. if (dir == null) { dir = this.options.smartIndent ? "smart" : "prev"; }
  9332. else { dir = dir ? "add" : "subtract"; }
  9333. }
  9334. if (isLine(this.doc, n)) { indentLine(this, n, dir, aggressive); }
  9335. }),
  9336. indentSelection: methodOp(function(how) {
  9337. var this$1 = this;
  9338. var ranges = this.doc.sel.ranges, end = -1;
  9339. for (var i = 0; i < ranges.length; i++) {
  9340. var range$$1 = ranges[i];
  9341. if (!range$$1.empty()) {
  9342. var from = range$$1.from(), to = range$$1.to();
  9343. var start = Math.max(end, from.line);
  9344. end = Math.min(this$1.lastLine(), to.line - (to.ch ? 0 : 1)) + 1;
  9345. for (var j = start; j < end; ++j)
  9346. { indentLine(this$1, j, how); }
  9347. var newRanges = this$1.doc.sel.ranges;
  9348. if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i].from().ch > 0)
  9349. { replaceOneSelection(this$1.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll); }
  9350. } else if (range$$1.head.line > end) {
  9351. indentLine(this$1, range$$1.head.line, how, true);
  9352. end = range$$1.head.line;
  9353. if (i == this$1.doc.sel.primIndex) { ensureCursorVisible(this$1); }
  9354. }
  9355. }
  9356. }),
  9357. // Fetch the parser token for a given character. Useful for hacks
  9358. // that want to inspect the mode state (say, for completion).
  9359. getTokenAt: function(pos, precise) {
  9360. return takeToken(this, pos, precise)
  9361. },
  9362. getLineTokens: function(line, precise) {
  9363. return takeToken(this, Pos(line), precise, true)
  9364. },
  9365. getTokenTypeAt: function(pos) {
  9366. pos = clipPos(this.doc, pos);
  9367. var styles = getLineStyles(this, getLine(this.doc, pos.line));
  9368. var before = 0, after = (styles.length - 1) / 2, ch = pos.ch;
  9369. var type;
  9370. if (ch == 0) { type = styles[2]; }
  9371. else { for (;;) {
  9372. var mid = (before + after) >> 1;
  9373. if ((mid ? styles[mid * 2 - 1] : 0) >= ch) { after = mid; }
  9374. else if (styles[mid * 2 + 1] < ch) { before = mid + 1; }
  9375. else { type = styles[mid * 2 + 2]; break }
  9376. } }
  9377. var cut = type ? type.indexOf("overlay ") : -1;
  9378. return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1)
  9379. },
  9380. getModeAt: function(pos) {
  9381. var mode = this.doc.mode;
  9382. if (!mode.innerMode) { return mode }
  9383. return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode
  9384. },
  9385. getHelper: function(pos, type) {
  9386. return this.getHelpers(pos, type)[0]
  9387. },
  9388. getHelpers: function(pos, type) {
  9389. var this$1 = this;
  9390. var found = [];
  9391. if (!helpers.hasOwnProperty(type)) { return found }
  9392. var help = helpers[type], mode = this.getModeAt(pos);
  9393. if (typeof mode[type] == "string") {
  9394. if (help[mode[type]]) { found.push(help[mode[type]]); }
  9395. } else if (mode[type]) {
  9396. for (var i = 0; i < mode[type].length; i++) {
  9397. var val = help[mode[type][i]];
  9398. if (val) { found.push(val); }
  9399. }
  9400. } else if (mode.helperType && help[mode.helperType]) {
  9401. found.push(help[mode.helperType]);
  9402. } else if (help[mode.name]) {
  9403. found.push(help[mode.name]);
  9404. }
  9405. for (var i$1 = 0; i$1 < help._global.length; i$1++) {
  9406. var cur = help._global[i$1];
  9407. if (cur.pred(mode, this$1) && indexOf(found, cur.val) == -1)
  9408. { found.push(cur.val); }
  9409. }
  9410. return found
  9411. },
  9412. getStateAfter: function(line, precise) {
  9413. var doc = this.doc;
  9414. line = clipLine(doc, line == null ? doc.first + doc.size - 1: line);
  9415. return getContextBefore(this, line + 1, precise).state
  9416. },
  9417. cursorCoords: function(start, mode) {
  9418. var pos, range$$1 = this.doc.sel.primary();
  9419. if (start == null) { pos = range$$1.head; }
  9420. else if (typeof start == "object") { pos = clipPos(this.doc, start); }
  9421. else { pos = start ? range$$1.from() : range$$1.to(); }
  9422. return cursorCoords(this, pos, mode || "page")
  9423. },
  9424. charCoords: function(pos, mode) {
  9425. return charCoords(this, clipPos(this.doc, pos), mode || "page")
  9426. },
  9427. coordsChar: function(coords, mode) {
  9428. coords = fromCoordSystem(this, coords, mode || "page");
  9429. return coordsChar(this, coords.left, coords.top)
  9430. },
  9431. lineAtHeight: function(height, mode) {
  9432. height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top;
  9433. return lineAtHeight(this.doc, height + this.display.viewOffset)
  9434. },
  9435. heightAtLine: function(line, mode, includeWidgets) {
  9436. var end = false, lineObj;
  9437. if (typeof line == "number") {
  9438. var last = this.doc.first + this.doc.size - 1;
  9439. if (line < this.doc.first) { line = this.doc.first; }
  9440. else if (line > last) { line = last; end = true; }
  9441. lineObj = getLine(this.doc, line);
  9442. } else {
  9443. lineObj = line;
  9444. }
  9445. return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || "page", includeWidgets || end).top +
  9446. (end ? this.doc.height - heightAtLine(lineObj) : 0)
  9447. },
  9448. defaultTextHeight: function() { return textHeight(this.display) },
  9449. defaultCharWidth: function() { return charWidth(this.display) },
  9450. getViewport: function() { return {from: this.display.viewFrom, to: this.display.viewTo}},
  9451. addWidget: function(pos, node, scroll, vert, horiz) {
  9452. var display = this.display;
  9453. pos = cursorCoords(this, clipPos(this.doc, pos));
  9454. var top = pos.bottom, left = pos.left;
  9455. node.style.position = "absolute";
  9456. node.setAttribute("cm-ignore-events", "true");
  9457. this.display.input.setUneditable(node);
  9458. display.sizer.appendChild(node);
  9459. if (vert == "over") {
  9460. top = pos.top;
  9461. } else if (vert == "above" || vert == "near") {
  9462. var vspace = Math.max(display.wrapper.clientHeight, this.doc.height),
  9463. hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth);
  9464. // Default to positioning above (if specified and possible); otherwise default to positioning below
  9465. if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight)
  9466. { top = pos.top - node.offsetHeight; }
  9467. else if (pos.bottom + node.offsetHeight <= vspace)
  9468. { top = pos.bottom; }
  9469. if (left + node.offsetWidth > hspace)
  9470. { left = hspace - node.offsetWidth; }
  9471. }
  9472. node.style.top = top + "px";
  9473. node.style.left = node.style.right = "";
  9474. if (horiz == "right") {
  9475. left = display.sizer.clientWidth - node.offsetWidth;
  9476. node.style.right = "0px";
  9477. } else {
  9478. if (horiz == "left") { left = 0; }
  9479. else if (horiz == "middle") { left = (display.sizer.clientWidth - node.offsetWidth) / 2; }
  9480. node.style.left = left + "px";
  9481. }
  9482. if (scroll)
  9483. { scrollIntoView(this, {left: left, top: top, right: left + node.offsetWidth, bottom: top + node.offsetHeight}); }
  9484. },
  9485. triggerOnKeyDown: methodOp(onKeyDown),
  9486. triggerOnKeyPress: methodOp(onKeyPress),
  9487. triggerOnKeyUp: onKeyUp,
  9488. triggerOnMouseDown: methodOp(onMouseDown),
  9489. execCommand: function(cmd) {
  9490. if (commands.hasOwnProperty(cmd))
  9491. { return commands[cmd].call(null, this) }
  9492. },
  9493. triggerElectric: methodOp(function(text) { triggerElectric(this, text); }),
  9494. findPosH: function(from, amount, unit, visually) {
  9495. var this$1 = this;
  9496. var dir = 1;
  9497. if (amount < 0) { dir = -1; amount = -amount; }
  9498. var cur = clipPos(this.doc, from);
  9499. for (var i = 0; i < amount; ++i) {
  9500. cur = findPosH(this$1.doc, cur, dir, unit, visually);
  9501. if (cur.hitSide) { break }
  9502. }
  9503. return cur
  9504. },
  9505. moveH: methodOp(function(dir, unit) {
  9506. var this$1 = this;
  9507. this.extendSelectionsBy(function (range$$1) {
  9508. if (this$1.display.shift || this$1.doc.extend || range$$1.empty())
  9509. { return findPosH(this$1.doc, range$$1.head, dir, unit, this$1.options.rtlMoveVisually) }
  9510. else
  9511. { return dir < 0 ? range$$1.from() : range$$1.to() }
  9512. }, sel_move);
  9513. }),
  9514. deleteH: methodOp(function(dir, unit) {
  9515. var sel = this.doc.sel, doc = this.doc;
  9516. if (sel.somethingSelected())
  9517. { doc.replaceSelection("", null, "+delete"); }
  9518. else
  9519. { deleteNearSelection(this, function (range$$1) {
  9520. var other = findPosH(doc, range$$1.head, dir, unit, false);
  9521. return dir < 0 ? {from: other, to: range$$1.head} : {from: range$$1.head, to: other}
  9522. }); }
  9523. }),
  9524. findPosV: function(from, amount, unit, goalColumn) {
  9525. var this$1 = this;
  9526. var dir = 1, x = goalColumn;
  9527. if (amount < 0) { dir = -1; amount = -amount; }
  9528. var cur = clipPos(this.doc, from);
  9529. for (var i = 0; i < amount; ++i) {
  9530. var coords = cursorCoords(this$1, cur, "div");
  9531. if (x == null) { x = coords.left; }
  9532. else { coords.left = x; }
  9533. cur = findPosV(this$1, coords, dir, unit);
  9534. if (cur.hitSide) { break }
  9535. }
  9536. return cur
  9537. },
  9538. moveV: methodOp(function(dir, unit) {
  9539. var this$1 = this;
  9540. var doc = this.doc, goals = [];
  9541. var collapse = !this.display.shift && !doc.extend && doc.sel.somethingSelected();
  9542. doc.extendSelectionsBy(function (range$$1) {
  9543. if (collapse)
  9544. { return dir < 0 ? range$$1.from() : range$$1.to() }
  9545. var headPos = cursorCoords(this$1, range$$1.head, "div");
  9546. if (range$$1.goalColumn != null) { headPos.left = range$$1.goalColumn; }
  9547. goals.push(headPos.left);
  9548. var pos = findPosV(this$1, headPos, dir, unit);
  9549. if (unit == "page" && range$$1 == doc.sel.primary())
  9550. { addToScrollTop(this$1, charCoords(this$1, pos, "div").top - headPos.top); }
  9551. return pos
  9552. }, sel_move);
  9553. if (goals.length) { for (var i = 0; i < doc.sel.ranges.length; i++)
  9554. { doc.sel.ranges[i].goalColumn = goals[i]; } }
  9555. }),
  9556. // Find the word at the given position (as returned by coordsChar).
  9557. findWordAt: function(pos) {
  9558. var doc = this.doc, line = getLine(doc, pos.line).text;
  9559. var start = pos.ch, end = pos.ch;
  9560. if (line) {
  9561. var helper = this.getHelper(pos, "wordChars");
  9562. if ((pos.sticky == "before" || end == line.length) && start) { --start; } else { ++end; }
  9563. var startChar = line.charAt(start);
  9564. var check = isWordChar(startChar, helper)
  9565. ? function (ch) { return isWordChar(ch, helper); }
  9566. : /\s/.test(startChar) ? function (ch) { return /\s/.test(ch); }
  9567. : function (ch) { return (!/\s/.test(ch) && !isWordChar(ch)); };
  9568. while (start > 0 && check(line.charAt(start - 1))) { --start; }
  9569. while (end < line.length && check(line.charAt(end))) { ++end; }
  9570. }
  9571. return new Range(Pos(pos.line, start), Pos(pos.line, end))
  9572. },
  9573. toggleOverwrite: function(value) {
  9574. if (value != null && value == this.state.overwrite) { return }
  9575. if (this.state.overwrite = !this.state.overwrite)
  9576. { addClass(this.display.cursorDiv, "CodeMirror-overwrite"); }
  9577. else
  9578. { rmClass(this.display.cursorDiv, "CodeMirror-overwrite"); }
  9579. signal(this, "overwriteToggle", this, this.state.overwrite);
  9580. },
  9581. hasFocus: function() { return this.display.input.getField() == activeElt() },
  9582. isReadOnly: function() { return !!(this.options.readOnly || this.doc.cantEdit) },
  9583. scrollTo: methodOp(function (x, y) { scrollToCoords(this, x, y); }),
  9584. getScrollInfo: function() {
  9585. var scroller = this.display.scroller;
  9586. return {left: scroller.scrollLeft, top: scroller.scrollTop,
  9587. height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight,
  9588. width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth,
  9589. clientHeight: displayHeight(this), clientWidth: displayWidth(this)}
  9590. },
  9591. scrollIntoView: methodOp(function(range$$1, margin) {
  9592. if (range$$1 == null) {
  9593. range$$1 = {from: this.doc.sel.primary().head, to: null};
  9594. if (margin == null) { margin = this.options.cursorScrollMargin; }
  9595. } else if (typeof range$$1 == "number") {
  9596. range$$1 = {from: Pos(range$$1, 0), to: null};
  9597. } else if (range$$1.from == null) {
  9598. range$$1 = {from: range$$1, to: null};
  9599. }
  9600. if (!range$$1.to) { range$$1.to = range$$1.from; }
  9601. range$$1.margin = margin || 0;
  9602. if (range$$1.from.line != null) {
  9603. scrollToRange(this, range$$1);
  9604. } else {
  9605. scrollToCoordsRange(this, range$$1.from, range$$1.to, range$$1.margin);
  9606. }
  9607. }),
  9608. setSize: methodOp(function(width, height) {
  9609. var this$1 = this;
  9610. var interpret = function (val) { return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val; };
  9611. if (width != null) { this.display.wrapper.style.width = interpret(width); }
  9612. if (height != null) { this.display.wrapper.style.height = interpret(height); }
  9613. if (this.options.lineWrapping) { clearLineMeasurementCache(this); }
  9614. var lineNo$$1 = this.display.viewFrom;
  9615. this.doc.iter(lineNo$$1, this.display.viewTo, function (line) {
  9616. if (line.widgets) { for (var i = 0; i < line.widgets.length; i++)
  9617. { if (line.widgets[i].noHScroll) { regLineChange(this$1, lineNo$$1, "widget"); break } } }
  9618. ++lineNo$$1;
  9619. });
  9620. this.curOp.forceUpdate = true;
  9621. signal(this, "refresh", this);
  9622. }),
  9623. operation: function(f){return runInOp(this, f)},
  9624. startOperation: function(){return startOperation(this)},
  9625. endOperation: function(){return endOperation(this)},
  9626. refresh: methodOp(function() {
  9627. var oldHeight = this.display.cachedTextHeight;
  9628. regChange(this);
  9629. this.curOp.forceUpdate = true;
  9630. clearCaches(this);
  9631. scrollToCoords(this, this.doc.scrollLeft, this.doc.scrollTop);
  9632. updateGutterSpace(this);
  9633. if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5)
  9634. { estimateLineHeights(this); }
  9635. signal(this, "refresh", this);
  9636. }),
  9637. swapDoc: methodOp(function(doc) {
  9638. var old = this.doc;
  9639. old.cm = null;
  9640. attachDoc(this, doc);
  9641. clearCaches(this);
  9642. this.display.input.reset();
  9643. scrollToCoords(this, doc.scrollLeft, doc.scrollTop);
  9644. this.curOp.forceScroll = true;
  9645. signalLater(this, "swapDoc", this, old);
  9646. return old
  9647. }),
  9648. getInputField: function(){return this.display.input.getField()},
  9649. getWrapperElement: function(){return this.display.wrapper},
  9650. getScrollerElement: function(){return this.display.scroller},
  9651. getGutterElement: function(){return this.display.gutters}
  9652. };
  9653. eventMixin(CodeMirror);
  9654. CodeMirror.registerHelper = function(type, name, value) {
  9655. if (!helpers.hasOwnProperty(type)) { helpers[type] = CodeMirror[type] = {_global: []}; }
  9656. helpers[type][name] = value;
  9657. };
  9658. CodeMirror.registerGlobalHelper = function(type, name, predicate, value) {
  9659. CodeMirror.registerHelper(type, name, value);
  9660. helpers[type]._global.push({pred: predicate, val: value});
  9661. };
  9662. };
  9663. // Used for horizontal relative motion. Dir is -1 or 1 (left or
  9664. // right), unit can be "char", "column" (like char, but doesn't
  9665. // cross line boundaries), "word" (across next word), or "group" (to
  9666. // the start of next group of word or non-word-non-whitespace
  9667. // chars). The visually param controls whether, in right-to-left
  9668. // text, direction 1 means to move towards the next index in the
  9669. // string, or towards the character to the right of the current
  9670. // position. The resulting position will have a hitSide=true
  9671. // property if it reached the end of the document.
  9672. function findPosH(doc, pos, dir, unit, visually) {
  9673. var oldPos = pos;
  9674. var origDir = dir;
  9675. var lineObj = getLine(doc, pos.line);
  9676. function findNextLine() {
  9677. var l = pos.line + dir;
  9678. if (l < doc.first || l >= doc.first + doc.size) { return false }
  9679. pos = new Pos(l, pos.ch, pos.sticky);
  9680. return lineObj = getLine(doc, l)
  9681. }
  9682. function moveOnce(boundToLine) {
  9683. var next;
  9684. if (visually) {
  9685. next = moveVisually(doc.cm, lineObj, pos, dir);
  9686. } else {
  9687. next = moveLogically(lineObj, pos, dir);
  9688. }
  9689. if (next == null) {
  9690. if (!boundToLine && findNextLine())
  9691. { pos = endOfLine(visually, doc.cm, lineObj, pos.line, dir); }
  9692. else
  9693. { return false }
  9694. } else {
  9695. pos = next;
  9696. }
  9697. return true
  9698. }
  9699. if (unit == "char") {
  9700. moveOnce();
  9701. } else if (unit == "column") {
  9702. moveOnce(true);
  9703. } else if (unit == "word" || unit == "group") {
  9704. var sawType = null, group = unit == "group";
  9705. var helper = doc.cm && doc.cm.getHelper(pos, "wordChars");
  9706. for (var first = true;; first = false) {
  9707. if (dir < 0 && !moveOnce(!first)) { break }
  9708. var cur = lineObj.text.charAt(pos.ch) || "\n";
  9709. var type = isWordChar(cur, helper) ? "w"
  9710. : group && cur == "\n" ? "n"
  9711. : !group || /\s/.test(cur) ? null
  9712. : "p";
  9713. if (group && !first && !type) { type = "s"; }
  9714. if (sawType && sawType != type) {
  9715. if (dir < 0) {dir = 1; moveOnce(); pos.sticky = "after";}
  9716. break
  9717. }
  9718. if (type) { sawType = type; }
  9719. if (dir > 0 && !moveOnce(!first)) { break }
  9720. }
  9721. }
  9722. var result = skipAtomic(doc, pos, oldPos, origDir, true);
  9723. if (equalCursorPos(oldPos, result)) { result.hitSide = true; }
  9724. return result
  9725. }
  9726. // For relative vertical movement. Dir may be -1 or 1. Unit can be
  9727. // "page" or "line". The resulting position will have a hitSide=true
  9728. // property if it reached the end of the document.
  9729. function findPosV(cm, pos, dir, unit) {
  9730. var doc = cm.doc, x = pos.left, y;
  9731. if (unit == "page") {
  9732. var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight);
  9733. var moveAmount = Math.max(pageSize - .5 * textHeight(cm.display), 3);
  9734. y = (dir > 0 ? pos.bottom : pos.top) + dir * moveAmount;
  9735. } else if (unit == "line") {
  9736. y = dir > 0 ? pos.bottom + 3 : pos.top - 3;
  9737. }
  9738. var target;
  9739. for (;;) {
  9740. target = coordsChar(cm, x, y);
  9741. if (!target.outside) { break }
  9742. if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break }
  9743. y += dir * 5;
  9744. }
  9745. return target
  9746. }
  9747. // CONTENTEDITABLE INPUT STYLE
  9748. var ContentEditableInput = function(cm) {
  9749. this.cm = cm;
  9750. this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null;
  9751. this.polling = new Delayed();
  9752. this.composing = null;
  9753. this.gracePeriod = false;
  9754. this.readDOMTimeout = null;
  9755. };
  9756. ContentEditableInput.prototype.init = function (display) {
  9757. var this$1 = this;
  9758. var input = this, cm = input.cm;
  9759. var div = input.div = display.lineDiv;
  9760. disableBrowserMagic(div, cm.options.spellcheck);
  9761. on(div, "paste", function (e) {
  9762. if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { return }
  9763. // IE doesn't fire input events, so we schedule a read for the pasted content in this way
  9764. if (ie_version <= 11) { setTimeout(operation(cm, function () { return this$1.updateFromDOM(); }), 20); }
  9765. });
  9766. on(div, "compositionstart", function (e) {
  9767. this$1.composing = {data: e.data, done: false};
  9768. });
  9769. on(div, "compositionupdate", function (e) {
  9770. if (!this$1.composing) { this$1.composing = {data: e.data, done: false}; }
  9771. });
  9772. on(div, "compositionend", function (e) {
  9773. if (this$1.composing) {
  9774. if (e.data != this$1.composing.data) { this$1.readFromDOMSoon(); }
  9775. this$1.composing.done = true;
  9776. }
  9777. });
  9778. on(div, "touchstart", function () { return input.forceCompositionEnd(); });
  9779. on(div, "input", function () {
  9780. if (!this$1.composing) { this$1.readFromDOMSoon(); }
  9781. });
  9782. function onCopyCut(e) {
  9783. if (signalDOMEvent(cm, e)) { return }
  9784. if (cm.somethingSelected()) {
  9785. setLastCopied({lineWise: false, text: cm.getSelections()});
  9786. if (e.type == "cut") { cm.replaceSelection("", null, "cut"); }
  9787. } else if (!cm.options.lineWiseCopyCut) {
  9788. return
  9789. } else {
  9790. var ranges = copyableRanges(cm);
  9791. setLastCopied({lineWise: true, text: ranges.text});
  9792. if (e.type == "cut") {
  9793. cm.operation(function () {
  9794. cm.setSelections(ranges.ranges, 0, sel_dontScroll);
  9795. cm.replaceSelection("", null, "cut");
  9796. });
  9797. }
  9798. }
  9799. if (e.clipboardData) {
  9800. e.clipboardData.clearData();
  9801. var content = lastCopied.text.join("\n");
  9802. // iOS exposes the clipboard API, but seems to discard content inserted into it
  9803. e.clipboardData.setData("Text", content);
  9804. if (e.clipboardData.getData("Text") == content) {
  9805. e.preventDefault();
  9806. return
  9807. }
  9808. }
  9809. // Old-fashioned briefly-focus-a-textarea hack
  9810. var kludge = hiddenTextarea(), te = kludge.firstChild;
  9811. cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild);
  9812. te.value = lastCopied.text.join("\n");
  9813. var hadFocus = document.activeElement;
  9814. selectInput(te);
  9815. setTimeout(function () {
  9816. cm.display.lineSpace.removeChild(kludge);
  9817. hadFocus.focus();
  9818. if (hadFocus == div) { input.showPrimarySelection(); }
  9819. }, 50);
  9820. }
  9821. on(div, "copy", onCopyCut);
  9822. on(div, "cut", onCopyCut);
  9823. };
  9824. ContentEditableInput.prototype.prepareSelection = function () {
  9825. var result = prepareSelection(this.cm, false);
  9826. result.focus = this.cm.state.focused;
  9827. return result
  9828. };
  9829. ContentEditableInput.prototype.showSelection = function (info, takeFocus) {
  9830. if (!info || !this.cm.display.view.length) { return }
  9831. if (info.focus || takeFocus) { this.showPrimarySelection(); }
  9832. this.showMultipleSelections(info);
  9833. };
  9834. ContentEditableInput.prototype.showPrimarySelection = function () {
  9835. var sel = window.getSelection(), cm = this.cm, prim = cm.doc.sel.primary();
  9836. var from = prim.from(), to = prim.to();
  9837. if (cm.display.viewTo == cm.display.viewFrom || from.line >= cm.display.viewTo || to.line < cm.display.viewFrom) {
  9838. sel.removeAllRanges();
  9839. return
  9840. }
  9841. var curAnchor = domToPos(cm, sel.anchorNode, sel.anchorOffset);
  9842. var curFocus = domToPos(cm, sel.focusNode, sel.focusOffset);
  9843. if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad &&
  9844. cmp(minPos(curAnchor, curFocus), from) == 0 &&
  9845. cmp(maxPos(curAnchor, curFocus), to) == 0)
  9846. { return }
  9847. var view = cm.display.view;
  9848. var start = (from.line >= cm.display.viewFrom && posToDOM(cm, from)) ||
  9849. {node: view[0].measure.map[2], offset: 0};
  9850. var end = to.line < cm.display.viewTo && posToDOM(cm, to);
  9851. if (!end) {
  9852. var measure = view[view.length - 1].measure;
  9853. var map$$1 = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map;
  9854. end = {node: map$$1[map$$1.length - 1], offset: map$$1[map$$1.length - 2] - map$$1[map$$1.length - 3]};
  9855. }
  9856. if (!start || !end) {
  9857. sel.removeAllRanges();
  9858. return
  9859. }
  9860. var old = sel.rangeCount && sel.getRangeAt(0), rng;
  9861. try { rng = range(start.node, start.offset, end.offset, end.node); }
  9862. catch(e) {} // Our model of the DOM might be outdated, in which case the range we try to set can be impossible
  9863. if (rng) {
  9864. if (!gecko && cm.state.focused) {
  9865. sel.collapse(start.node, start.offset);
  9866. if (!rng.collapsed) {
  9867. sel.removeAllRanges();
  9868. sel.addRange(rng);
  9869. }
  9870. } else {
  9871. sel.removeAllRanges();
  9872. sel.addRange(rng);
  9873. }
  9874. if (old && sel.anchorNode == null) { sel.addRange(old); }
  9875. else if (gecko) { this.startGracePeriod(); }
  9876. }
  9877. this.rememberSelection();
  9878. };
  9879. ContentEditableInput.prototype.startGracePeriod = function () {
  9880. var this$1 = this;
  9881. clearTimeout(this.gracePeriod);
  9882. this.gracePeriod = setTimeout(function () {
  9883. this$1.gracePeriod = false;
  9884. if (this$1.selectionChanged())
  9885. { this$1.cm.operation(function () { return this$1.cm.curOp.selectionChanged = true; }); }
  9886. }, 20);
  9887. };
  9888. ContentEditableInput.prototype.showMultipleSelections = function (info) {
  9889. removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors);
  9890. removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection);
  9891. };
  9892. ContentEditableInput.prototype.rememberSelection = function () {
  9893. var sel = window.getSelection();
  9894. this.lastAnchorNode = sel.anchorNode; this.lastAnchorOffset = sel.anchorOffset;
  9895. this.lastFocusNode = sel.focusNode; this.lastFocusOffset = sel.focusOffset;
  9896. };
  9897. ContentEditableInput.prototype.selectionInEditor = function () {
  9898. var sel = window.getSelection();
  9899. if (!sel.rangeCount) { return false }
  9900. var node = sel.getRangeAt(0).commonAncestorContainer;
  9901. return contains(this.div, node)
  9902. };
  9903. ContentEditableInput.prototype.focus = function () {
  9904. if (this.cm.options.readOnly != "nocursor") {
  9905. if (!this.selectionInEditor())
  9906. { this.showSelection(this.prepareSelection(), true); }
  9907. this.div.focus();
  9908. }
  9909. };
  9910. ContentEditableInput.prototype.blur = function () { this.div.blur(); };
  9911. ContentEditableInput.prototype.getField = function () { return this.div };
  9912. ContentEditableInput.prototype.supportsTouch = function () { return true };
  9913. ContentEditableInput.prototype.receivedFocus = function () {
  9914. var input = this;
  9915. if (this.selectionInEditor())
  9916. { this.pollSelection(); }
  9917. else
  9918. { runInOp(this.cm, function () { return input.cm.curOp.selectionChanged = true; }); }
  9919. function poll() {
  9920. if (input.cm.state.focused) {
  9921. input.pollSelection();
  9922. input.polling.set(input.cm.options.pollInterval, poll);
  9923. }
  9924. }
  9925. this.polling.set(this.cm.options.pollInterval, poll);
  9926. };
  9927. ContentEditableInput.prototype.selectionChanged = function () {
  9928. var sel = window.getSelection();
  9929. return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset ||
  9930. sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset
  9931. };
  9932. ContentEditableInput.prototype.pollSelection = function () {
  9933. if (this.readDOMTimeout != null || this.gracePeriod || !this.selectionChanged()) { return }
  9934. var sel = window.getSelection(), cm = this.cm;
  9935. // On Android Chrome (version 56, at least), backspacing into an
  9936. // uneditable block element will put the cursor in that element,
  9937. // and then, because it's not editable, hide the virtual keyboard.
  9938. // Because Android doesn't allow us to actually detect backspace
  9939. // presses in a sane way, this code checks for when that happens
  9940. // and simulates a backspace press in this case.
  9941. if (android && chrome && this.cm.options.gutters.length && isInGutter(sel.anchorNode)) {
  9942. this.cm.triggerOnKeyDown({type: "keydown", keyCode: 8, preventDefault: Math.abs});
  9943. this.blur();
  9944. this.focus();
  9945. return
  9946. }
  9947. if (this.composing) { return }
  9948. this.rememberSelection();
  9949. var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset);
  9950. var head = domToPos(cm, sel.focusNode, sel.focusOffset);
  9951. if (anchor && head) { runInOp(cm, function () {
  9952. setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll);
  9953. if (anchor.bad || head.bad) { cm.curOp.selectionChanged = true; }
  9954. }); }
  9955. };
  9956. ContentEditableInput.prototype.pollContent = function () {
  9957. if (this.readDOMTimeout != null) {
  9958. clearTimeout(this.readDOMTimeout);
  9959. this.readDOMTimeout = null;
  9960. }
  9961. var cm = this.cm, display = cm.display, sel = cm.doc.sel.primary();
  9962. var from = sel.from(), to = sel.to();
  9963. if (from.ch == 0 && from.line > cm.firstLine())
  9964. { from = Pos(from.line - 1, getLine(cm.doc, from.line - 1).length); }
  9965. if (to.ch == getLine(cm.doc, to.line).text.length && to.line < cm.lastLine())
  9966. { to = Pos(to.line + 1, 0); }
  9967. if (from.line < display.viewFrom || to.line > display.viewTo - 1) { return false }
  9968. var fromIndex, fromLine, fromNode;
  9969. if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) {
  9970. fromLine = lineNo(display.view[0].line);
  9971. fromNode = display.view[0].node;
  9972. } else {
  9973. fromLine = lineNo(display.view[fromIndex].line);
  9974. fromNode = display.view[fromIndex - 1].node.nextSibling;
  9975. }
  9976. var toIndex = findViewIndex(cm, to.line);
  9977. var toLine, toNode;
  9978. if (toIndex == display.view.length - 1) {
  9979. toLine = display.viewTo - 1;
  9980. toNode = display.lineDiv.lastChild;
  9981. } else {
  9982. toLine = lineNo(display.view[toIndex + 1].line) - 1;
  9983. toNode = display.view[toIndex + 1].node.previousSibling;
  9984. }
  9985. if (!fromNode) { return false }
  9986. var newText = cm.doc.splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine));
  9987. var oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length));
  9988. while (newText.length > 1 && oldText.length > 1) {
  9989. if (lst(newText) == lst(oldText)) { newText.pop(); oldText.pop(); toLine--; }
  9990. else if (newText[0] == oldText[0]) { newText.shift(); oldText.shift(); fromLine++; }
  9991. else { break }
  9992. }
  9993. var cutFront = 0, cutEnd = 0;
  9994. var newTop = newText[0], oldTop = oldText[0], maxCutFront = Math.min(newTop.length, oldTop.length);
  9995. while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront))
  9996. { ++cutFront; }
  9997. var newBot = lst(newText), oldBot = lst(oldText);
  9998. var maxCutEnd = Math.min(newBot.length - (newText.length == 1 ? cutFront : 0),
  9999. oldBot.length - (oldText.length == 1 ? cutFront : 0));
  10000. while (cutEnd < maxCutEnd &&
  10001. newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1))
  10002. { ++cutEnd; }
  10003. // Try to move start of change to start of selection if ambiguous
  10004. if (newText.length == 1 && oldText.length == 1 && fromLine == from.line) {
  10005. while (cutFront && cutFront > from.ch &&
  10006. newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) {
  10007. cutFront--;
  10008. cutEnd++;
  10009. }
  10010. }
  10011. newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd).replace(/^\u200b+/, "");
  10012. newText[0] = newText[0].slice(cutFront).replace(/\u200b+$/, "");
  10013. var chFrom = Pos(fromLine, cutFront);
  10014. var chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0);
  10015. if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) {
  10016. replaceRange(cm.doc, newText, chFrom, chTo, "+input");
  10017. return true
  10018. }
  10019. };
  10020. ContentEditableInput.prototype.ensurePolled = function () {
  10021. this.forceCompositionEnd();
  10022. };
  10023. ContentEditableInput.prototype.reset = function () {
  10024. this.forceCompositionEnd();
  10025. };
  10026. ContentEditableInput.prototype.forceCompositionEnd = function () {
  10027. if (!this.composing) { return }
  10028. clearTimeout(this.readDOMTimeout);
  10029. this.composing = null;
  10030. this.updateFromDOM();
  10031. this.div.blur();
  10032. this.div.focus();
  10033. };
  10034. ContentEditableInput.prototype.readFromDOMSoon = function () {
  10035. var this$1 = this;
  10036. if (this.readDOMTimeout != null) { return }
  10037. this.readDOMTimeout = setTimeout(function () {
  10038. this$1.readDOMTimeout = null;
  10039. if (this$1.composing) {
  10040. if (this$1.composing.done) { this$1.composing = null; }
  10041. else { return }
  10042. }
  10043. this$1.updateFromDOM();
  10044. }, 80);
  10045. };
  10046. ContentEditableInput.prototype.updateFromDOM = function () {
  10047. var this$1 = this;
  10048. if (this.cm.isReadOnly() || !this.pollContent())
  10049. { runInOp(this.cm, function () { return regChange(this$1.cm); }); }
  10050. };
  10051. ContentEditableInput.prototype.setUneditable = function (node) {
  10052. node.contentEditable = "false";
  10053. };
  10054. ContentEditableInput.prototype.onKeyPress = function (e) {
  10055. if (e.charCode == 0) { return }
  10056. e.preventDefault();
  10057. if (!this.cm.isReadOnly())
  10058. { operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0); }
  10059. };
  10060. ContentEditableInput.prototype.readOnlyChanged = function (val) {
  10061. this.div.contentEditable = String(val != "nocursor");
  10062. };
  10063. ContentEditableInput.prototype.onContextMenu = function () {};
  10064. ContentEditableInput.prototype.resetPosition = function () {};
  10065. ContentEditableInput.prototype.needsContentAttribute = true;
  10066. function posToDOM(cm, pos) {
  10067. var view = findViewForLine(cm, pos.line);
  10068. if (!view || view.hidden) { return null }
  10069. var line = getLine(cm.doc, pos.line);
  10070. var info = mapFromLineView(view, line, pos.line);
  10071. var order = getOrder(line, cm.doc.direction), side = "left";
  10072. if (order) {
  10073. var partPos = getBidiPartAt(order, pos.ch);
  10074. side = partPos % 2 ? "right" : "left";
  10075. }
  10076. var result = nodeAndOffsetInLineMap(info.map, pos.ch, side);
  10077. result.offset = result.collapse == "right" ? result.end : result.start;
  10078. return result
  10079. }
  10080. function isInGutter(node) {
  10081. for (var scan = node; scan; scan = scan.parentNode)
  10082. { if (/CodeMirror-gutter-wrapper/.test(scan.className)) { return true } }
  10083. return false
  10084. }
  10085. function badPos(pos, bad) { if (bad) { pos.bad = true; } return pos }
  10086. function domTextBetween(cm, from, to, fromLine, toLine) {
  10087. var text = "", closing = false, lineSep = cm.doc.lineSeparator();
  10088. function recognizeMarker(id) { return function (marker) { return marker.id == id; } }
  10089. function close() {
  10090. if (closing) {
  10091. text += lineSep;
  10092. closing = false;
  10093. }
  10094. }
  10095. function addText(str) {
  10096. if (str) {
  10097. close();
  10098. text += str;
  10099. }
  10100. }
  10101. function walk(node) {
  10102. if (node.nodeType == 1) {
  10103. var cmText = node.getAttribute("cm-text");
  10104. if (cmText != null) {
  10105. addText(cmText || node.textContent.replace(/\u200b/g, ""));
  10106. return
  10107. }
  10108. var markerID = node.getAttribute("cm-marker"), range$$1;
  10109. if (markerID) {
  10110. var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID));
  10111. if (found.length && (range$$1 = found[0].find(0)))
  10112. { addText(getBetween(cm.doc, range$$1.from, range$$1.to).join(lineSep)); }
  10113. return
  10114. }
  10115. if (node.getAttribute("contenteditable") == "false") { return }
  10116. var isBlock = /^(pre|div|p)$/i.test(node.nodeName);
  10117. if (isBlock) { close(); }
  10118. for (var i = 0; i < node.childNodes.length; i++)
  10119. { walk(node.childNodes[i]); }
  10120. if (isBlock) { closing = true; }
  10121. } else if (node.nodeType == 3) {
  10122. addText(node.nodeValue);
  10123. }
  10124. }
  10125. for (;;) {
  10126. walk(from);
  10127. if (from == to) { break }
  10128. from = from.nextSibling;
  10129. }
  10130. return text
  10131. }
  10132. function domToPos(cm, node, offset) {
  10133. var lineNode;
  10134. if (node == cm.display.lineDiv) {
  10135. lineNode = cm.display.lineDiv.childNodes[offset];
  10136. if (!lineNode) { return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true) }
  10137. node = null; offset = 0;
  10138. } else {
  10139. for (lineNode = node;; lineNode = lineNode.parentNode) {
  10140. if (!lineNode || lineNode == cm.display.lineDiv) { return null }
  10141. if (lineNode.parentNode && lineNode.parentNode == cm.display.lineDiv) { break }
  10142. }
  10143. }
  10144. for (var i = 0; i < cm.display.view.length; i++) {
  10145. var lineView = cm.display.view[i];
  10146. if (lineView.node == lineNode)
  10147. { return locateNodeInLineView(lineView, node, offset) }
  10148. }
  10149. }
  10150. function locateNodeInLineView(lineView, node, offset) {
  10151. var wrapper = lineView.text.firstChild, bad = false;
  10152. if (!node || !contains(wrapper, node)) { return badPos(Pos(lineNo(lineView.line), 0), true) }
  10153. if (node == wrapper) {
  10154. bad = true;
  10155. node = wrapper.childNodes[offset];
  10156. offset = 0;
  10157. if (!node) {
  10158. var line = lineView.rest ? lst(lineView.rest) : lineView.line;
  10159. return badPos(Pos(lineNo(line), line.text.length), bad)
  10160. }
  10161. }
  10162. var textNode = node.nodeType == 3 ? node : null, topNode = node;
  10163. if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) {
  10164. textNode = node.firstChild;
  10165. if (offset) { offset = textNode.nodeValue.length; }
  10166. }
  10167. while (topNode.parentNode != wrapper) { topNode = topNode.parentNode; }
  10168. var measure = lineView.measure, maps = measure.maps;
  10169. function find(textNode, topNode, offset) {
  10170. for (var i = -1; i < (maps ? maps.length : 0); i++) {
  10171. var map$$1 = i < 0 ? measure.map : maps[i];
  10172. for (var j = 0; j < map$$1.length; j += 3) {
  10173. var curNode = map$$1[j + 2];
  10174. if (curNode == textNode || curNode == topNode) {
  10175. var line = lineNo(i < 0 ? lineView.line : lineView.rest[i]);
  10176. var ch = map$$1[j] + offset;
  10177. if (offset < 0 || curNode != textNode) { ch = map$$1[j + (offset ? 1 : 0)]; }
  10178. return Pos(line, ch)
  10179. }
  10180. }
  10181. }
  10182. }
  10183. var found = find(textNode, topNode, offset);
  10184. if (found) { return badPos(found, bad) }
  10185. // FIXME this is all really shaky. might handle the few cases it needs to handle, but likely to cause problems
  10186. for (var after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) {
  10187. found = find(after, after.firstChild, 0);
  10188. if (found)
  10189. { return badPos(Pos(found.line, found.ch - dist), bad) }
  10190. else
  10191. { dist += after.textContent.length; }
  10192. }
  10193. for (var before = topNode.previousSibling, dist$1 = offset; before; before = before.previousSibling) {
  10194. found = find(before, before.firstChild, -1);
  10195. if (found)
  10196. { return badPos(Pos(found.line, found.ch + dist$1), bad) }
  10197. else
  10198. { dist$1 += before.textContent.length; }
  10199. }
  10200. }
  10201. // TEXTAREA INPUT STYLE
  10202. var TextareaInput = function(cm) {
  10203. this.cm = cm;
  10204. // See input.poll and input.reset
  10205. this.prevInput = "";
  10206. // Flag that indicates whether we expect input to appear real soon
  10207. // now (after some event like 'keypress' or 'input') and are
  10208. // polling intensively.
  10209. this.pollingFast = false;
  10210. // Self-resetting timeout for the poller
  10211. this.polling = new Delayed();
  10212. // Used to work around IE issue with selection being forgotten when focus moves away from textarea
  10213. this.hasSelection = false;
  10214. this.composing = null;
  10215. };
  10216. TextareaInput.prototype.init = function (display) {
  10217. var this$1 = this;
  10218. var input = this, cm = this.cm;
  10219. // Wraps and hides input textarea
  10220. var div = this.wrapper = hiddenTextarea();
  10221. // The semihidden textarea that is focused when the editor is
  10222. // focused, and receives input.
  10223. var te = this.textarea = div.firstChild;
  10224. display.wrapper.insertBefore(div, display.wrapper.firstChild);
  10225. // Needed to hide big blue blinking cursor on Mobile Safari (doesn't seem to work in iOS 8 anymore)
  10226. if (ios) { te.style.width = "0px"; }
  10227. on(te, "input", function () {
  10228. if (ie && ie_version >= 9 && this$1.hasSelection) { this$1.hasSelection = null; }
  10229. input.poll();
  10230. });
  10231. on(te, "paste", function (e) {
  10232. if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { return }
  10233. cm.state.pasteIncoming = true;
  10234. input.fastPoll();
  10235. });
  10236. function prepareCopyCut(e) {
  10237. if (signalDOMEvent(cm, e)) { return }
  10238. if (cm.somethingSelected()) {
  10239. setLastCopied({lineWise: false, text: cm.getSelections()});
  10240. } else if (!cm.options.lineWiseCopyCut) {
  10241. return
  10242. } else {
  10243. var ranges = copyableRanges(cm);
  10244. setLastCopied({lineWise: true, text: ranges.text});
  10245. if (e.type == "cut") {
  10246. cm.setSelections(ranges.ranges, null, sel_dontScroll);
  10247. } else {
  10248. input.prevInput = "";
  10249. te.value = ranges.text.join("\n");
  10250. selectInput(te);
  10251. }
  10252. }
  10253. if (e.type == "cut") { cm.state.cutIncoming = true; }
  10254. }
  10255. on(te, "cut", prepareCopyCut);
  10256. on(te, "copy", prepareCopyCut);
  10257. on(display.scroller, "paste", function (e) {
  10258. if (eventInWidget(display, e) || signalDOMEvent(cm, e)) { return }
  10259. cm.state.pasteIncoming = true;
  10260. input.focus();
  10261. });
  10262. // Prevent normal selection in the editor (we handle our own)
  10263. on(display.lineSpace, "selectstart", function (e) {
  10264. if (!eventInWidget(display, e)) { e_preventDefault(e); }
  10265. });
  10266. on(te, "compositionstart", function () {
  10267. var start = cm.getCursor("from");
  10268. if (input.composing) { input.composing.range.clear(); }
  10269. input.composing = {
  10270. start: start,
  10271. range: cm.markText(start, cm.getCursor("to"), {className: "CodeMirror-composing"})
  10272. };
  10273. });
  10274. on(te, "compositionend", function () {
  10275. if (input.composing) {
  10276. input.poll();
  10277. input.composing.range.clear();
  10278. input.composing = null;
  10279. }
  10280. });
  10281. };
  10282. TextareaInput.prototype.prepareSelection = function () {
  10283. // Redraw the selection and/or cursor
  10284. var cm = this.cm, display = cm.display, doc = cm.doc;
  10285. var result = prepareSelection(cm);
  10286. // Move the hidden textarea near the cursor to prevent scrolling artifacts
  10287. if (cm.options.moveInputWithCursor) {
  10288. var headPos = cursorCoords(cm, doc.sel.primary().head, "div");
  10289. var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect();
  10290. result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10,
  10291. headPos.top + lineOff.top - wrapOff.top));
  10292. result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10,
  10293. headPos.left + lineOff.left - wrapOff.left));
  10294. }
  10295. return result
  10296. };
  10297. TextareaInput.prototype.showSelection = function (drawn) {
  10298. var cm = this.cm, display = cm.display;
  10299. removeChildrenAndAdd(display.cursorDiv, drawn.cursors);
  10300. removeChildrenAndAdd(display.selectionDiv, drawn.selection);
  10301. if (drawn.teTop != null) {
  10302. this.wrapper.style.top = drawn.teTop + "px";
  10303. this.wrapper.style.left = drawn.teLeft + "px";
  10304. }
  10305. };
  10306. // Reset the input to correspond to the selection (or to be empty,
  10307. // when not typing and nothing is selected)
  10308. TextareaInput.prototype.reset = function (typing) {
  10309. if (this.contextMenuPending || this.composing) { return }
  10310. var cm = this.cm;
  10311. if (cm.somethingSelected()) {
  10312. this.prevInput = "";
  10313. var content = cm.getSelection();
  10314. this.textarea.value = content;
  10315. if (cm.state.focused) { selectInput(this.textarea); }
  10316. if (ie && ie_version >= 9) { this.hasSelection = content; }
  10317. } else if (!typing) {
  10318. this.prevInput = this.textarea.value = "";
  10319. if (ie && ie_version >= 9) { this.hasSelection = null; }
  10320. }
  10321. };
  10322. TextareaInput.prototype.getField = function () { return this.textarea };
  10323. TextareaInput.prototype.supportsTouch = function () { return false };
  10324. TextareaInput.prototype.focus = function () {
  10325. if (this.cm.options.readOnly != "nocursor" && (!mobile || activeElt() != this.textarea)) {
  10326. try { this.textarea.focus(); }
  10327. catch (e) {} // IE8 will throw if the textarea is display: none or not in DOM
  10328. }
  10329. };
  10330. TextareaInput.prototype.blur = function () { this.textarea.blur(); };
  10331. TextareaInput.prototype.resetPosition = function () {
  10332. this.wrapper.style.top = this.wrapper.style.left = 0;
  10333. };
  10334. TextareaInput.prototype.receivedFocus = function () { this.slowPoll(); };
  10335. // Poll for input changes, using the normal rate of polling. This
  10336. // runs as long as the editor is focused.
  10337. TextareaInput.prototype.slowPoll = function () {
  10338. var this$1 = this;
  10339. if (this.pollingFast) { return }
  10340. this.polling.set(this.cm.options.pollInterval, function () {
  10341. this$1.poll();
  10342. if (this$1.cm.state.focused) { this$1.slowPoll(); }
  10343. });
  10344. };
  10345. // When an event has just come in that is likely to add or change
  10346. // something in the input textarea, we poll faster, to ensure that
  10347. // the change appears on the screen quickly.
  10348. TextareaInput.prototype.fastPoll = function () {
  10349. var missed = false, input = this;
  10350. input.pollingFast = true;
  10351. function p() {
  10352. var changed = input.poll();
  10353. if (!changed && !missed) {missed = true; input.polling.set(60, p);}
  10354. else {input.pollingFast = false; input.slowPoll();}
  10355. }
  10356. input.polling.set(20, p);
  10357. };
  10358. // Read input from the textarea, and update the document to match.
  10359. // When something is selected, it is present in the textarea, and
  10360. // selected (unless it is huge, in which case a placeholder is
  10361. // used). When nothing is selected, the cursor sits after previously
  10362. // seen text (can be empty), which is stored in prevInput (we must
  10363. // not reset the textarea when typing, because that breaks IME).
  10364. TextareaInput.prototype.poll = function () {
  10365. var this$1 = this;
  10366. var cm = this.cm, input = this.textarea, prevInput = this.prevInput;
  10367. // Since this is called a *lot*, try to bail out as cheaply as
  10368. // possible when it is clear that nothing happened. hasSelection
  10369. // will be the case when there is a lot of text in the textarea,
  10370. // in which case reading its value would be expensive.
  10371. if (this.contextMenuPending || !cm.state.focused ||
  10372. (hasSelection(input) && !prevInput && !this.composing) ||
  10373. cm.isReadOnly() || cm.options.disableInput || cm.state.keySeq)
  10374. { return false }
  10375. var text = input.value;
  10376. // If nothing changed, bail.
  10377. if (text == prevInput && !cm.somethingSelected()) { return false }
  10378. // Work around nonsensical selection resetting in IE9/10, and
  10379. // inexplicable appearance of private area unicode characters on
  10380. // some key combos in Mac (#2689).
  10381. if (ie && ie_version >= 9 && this.hasSelection === text ||
  10382. mac && /[\uf700-\uf7ff]/.test(text)) {
  10383. cm.display.input.reset();
  10384. return false
  10385. }
  10386. if (cm.doc.sel == cm.display.selForContextMenu) {
  10387. var first = text.charCodeAt(0);
  10388. if (first == 0x200b && !prevInput) { prevInput = "\u200b"; }
  10389. if (first == 0x21da) { this.reset(); return this.cm.execCommand("undo") }
  10390. }
  10391. // Find the part of the input that is actually new
  10392. var same = 0, l = Math.min(prevInput.length, text.length);
  10393. while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) { ++same; }
  10394. runInOp(cm, function () {
  10395. applyTextInput(cm, text.slice(same), prevInput.length - same,
  10396. null, this$1.composing ? "*compose" : null);
  10397. // Don't leave long text in the textarea, since it makes further polling slow
  10398. if (text.length > 1000 || text.indexOf("\n") > -1) { input.value = this$1.prevInput = ""; }
  10399. else { this$1.prevInput = text; }
  10400. if (this$1.composing) {
  10401. this$1.composing.range.clear();
  10402. this$1.composing.range = cm.markText(this$1.composing.start, cm.getCursor("to"),
  10403. {className: "CodeMirror-composing"});
  10404. }
  10405. });
  10406. return true
  10407. };
  10408. TextareaInput.prototype.ensurePolled = function () {
  10409. if (this.pollingFast && this.poll()) { this.pollingFast = false; }
  10410. };
  10411. TextareaInput.prototype.onKeyPress = function () {
  10412. if (ie && ie_version >= 9) { this.hasSelection = null; }
  10413. this.fastPoll();
  10414. };
  10415. TextareaInput.prototype.onContextMenu = function (e) {
  10416. var input = this, cm = input.cm, display = cm.display, te = input.textarea;
  10417. var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop;
  10418. if (!pos || presto) { return } // Opera is difficult.
  10419. // Reset the current text selection only if the click is done outside of the selection
  10420. // and 'resetSelectionOnContextMenu' option is true.
  10421. var reset = cm.options.resetSelectionOnContextMenu;
  10422. if (reset && cm.doc.sel.contains(pos) == -1)
  10423. { operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll); }
  10424. var oldCSS = te.style.cssText, oldWrapperCSS = input.wrapper.style.cssText;
  10425. input.wrapper.style.cssText = "position: absolute";
  10426. var wrapperBox = input.wrapper.getBoundingClientRect();
  10427. 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);";
  10428. var oldScrollY;
  10429. if (webkit) { oldScrollY = window.scrollY; } // Work around Chrome issue (#2712)
  10430. display.input.focus();
  10431. if (webkit) { window.scrollTo(null, oldScrollY); }
  10432. display.input.reset();
  10433. // Adds "Select all" to context menu in FF
  10434. if (!cm.somethingSelected()) { te.value = input.prevInput = " "; }
  10435. input.contextMenuPending = true;
  10436. display.selForContextMenu = cm.doc.sel;
  10437. clearTimeout(display.detectingSelectAll);
  10438. // Select-all will be greyed out if there's nothing to select, so
  10439. // this adds a zero-width space so that we can later check whether
  10440. // it got selected.
  10441. function prepareSelectAllHack() {
  10442. if (te.selectionStart != null) {
  10443. var selected = cm.somethingSelected();
  10444. var extval = "\u200b" + (selected ? te.value : "");
  10445. te.value = "\u21da"; // Used to catch context-menu undo
  10446. te.value = extval;
  10447. input.prevInput = selected ? "" : "\u200b";
  10448. te.selectionStart = 1; te.selectionEnd = extval.length;
  10449. // Re-set this, in case some other handler touched the
  10450. // selection in the meantime.
  10451. display.selForContextMenu = cm.doc.sel;
  10452. }
  10453. }
  10454. function rehide() {
  10455. input.contextMenuPending = false;
  10456. input.wrapper.style.cssText = oldWrapperCSS;
  10457. te.style.cssText = oldCSS;
  10458. if (ie && ie_version < 9) { display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos); }
  10459. // Try to detect the user choosing select-all
  10460. if (te.selectionStart != null) {
  10461. if (!ie || (ie && ie_version < 9)) { prepareSelectAllHack(); }
  10462. var i = 0, poll = function () {
  10463. if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0 &&
  10464. te.selectionEnd > 0 && input.prevInput == "\u200b") {
  10465. operation(cm, selectAll)(cm);
  10466. } else if (i++ < 10) {
  10467. display.detectingSelectAll = setTimeout(poll, 500);
  10468. } else {
  10469. display.selForContextMenu = null;
  10470. display.input.reset();
  10471. }
  10472. };
  10473. display.detectingSelectAll = setTimeout(poll, 200);
  10474. }
  10475. }
  10476. if (ie && ie_version >= 9) { prepareSelectAllHack(); }
  10477. if (captureRightClick) {
  10478. e_stop(e);
  10479. var mouseup = function () {
  10480. off(window, "mouseup", mouseup);
  10481. setTimeout(rehide, 20);
  10482. };
  10483. on(window, "mouseup", mouseup);
  10484. } else {
  10485. setTimeout(rehide, 50);
  10486. }
  10487. };
  10488. TextareaInput.prototype.readOnlyChanged = function (val) {
  10489. if (!val) { this.reset(); }
  10490. this.textarea.disabled = val == "nocursor";
  10491. };
  10492. TextareaInput.prototype.setUneditable = function () {};
  10493. TextareaInput.prototype.needsContentAttribute = false;
  10494. function fromTextArea(textarea, options) {
  10495. options = options ? copyObj(options) : {};
  10496. options.value = textarea.value;
  10497. if (!options.tabindex && textarea.tabIndex)
  10498. { options.tabindex = textarea.tabIndex; }
  10499. if (!options.placeholder && textarea.placeholder)
  10500. { options.placeholder = textarea.placeholder; }
  10501. // Set autofocus to true if this textarea is focused, or if it has
  10502. // autofocus and no other element is focused.
  10503. if (options.autofocus == null) {
  10504. var hasFocus = activeElt();
  10505. options.autofocus = hasFocus == textarea ||
  10506. textarea.getAttribute("autofocus") != null && hasFocus == document.body;
  10507. }
  10508. function save() {textarea.value = cm.getValue();}
  10509. var realSubmit;
  10510. if (textarea.form) {
  10511. on(textarea.form, "submit", save);
  10512. // Deplorable hack to make the submit method do the right thing.
  10513. if (!options.leaveSubmitMethodAlone) {
  10514. var form = textarea.form;
  10515. realSubmit = form.submit;
  10516. try {
  10517. var wrappedSubmit = form.submit = function () {
  10518. save();
  10519. form.submit = realSubmit;
  10520. form.submit();
  10521. form.submit = wrappedSubmit;
  10522. };
  10523. } catch(e) {}
  10524. }
  10525. }
  10526. options.finishInit = function (cm) {
  10527. cm.save = save;
  10528. cm.getTextArea = function () { return textarea; };
  10529. cm.toTextArea = function () {
  10530. cm.toTextArea = isNaN; // Prevent this from being ran twice
  10531. save();
  10532. textarea.parentNode.removeChild(cm.getWrapperElement());
  10533. textarea.style.display = "";
  10534. if (textarea.form) {
  10535. off(textarea.form, "submit", save);
  10536. if (typeof textarea.form.submit == "function")
  10537. { textarea.form.submit = realSubmit; }
  10538. }
  10539. };
  10540. };
  10541. textarea.style.display = "none";
  10542. var cm = CodeMirror$1(function (node) { return textarea.parentNode.insertBefore(node, textarea.nextSibling); },
  10543. options);
  10544. return cm
  10545. }
  10546. function addLegacyProps(CodeMirror) {
  10547. CodeMirror.off = off;
  10548. CodeMirror.on = on;
  10549. CodeMirror.wheelEventPixels = wheelEventPixels;
  10550. CodeMirror.Doc = Doc;
  10551. CodeMirror.splitLines = splitLinesAuto;
  10552. CodeMirror.countColumn = countColumn;
  10553. CodeMirror.findColumn = findColumn;
  10554. CodeMirror.isWordChar = isWordCharBasic;
  10555. CodeMirror.Pass = Pass;
  10556. CodeMirror.signal = signal;
  10557. CodeMirror.Line = Line;
  10558. CodeMirror.changeEnd = changeEnd;
  10559. CodeMirror.scrollbarModel = scrollbarModel;
  10560. CodeMirror.Pos = Pos;
  10561. CodeMirror.cmpPos = cmp;
  10562. CodeMirror.modes = modes;
  10563. CodeMirror.mimeModes = mimeModes;
  10564. CodeMirror.resolveMode = resolveMode;
  10565. CodeMirror.getMode = getMode;
  10566. CodeMirror.modeExtensions = modeExtensions;
  10567. CodeMirror.extendMode = extendMode;
  10568. CodeMirror.copyState = copyState;
  10569. CodeMirror.startState = startState;
  10570. CodeMirror.innerMode = innerMode;
  10571. CodeMirror.commands = commands;
  10572. CodeMirror.keyMap = keyMap;
  10573. CodeMirror.keyName = keyName;
  10574. CodeMirror.isModifierKey = isModifierKey;
  10575. CodeMirror.lookupKey = lookupKey;
  10576. CodeMirror.normalizeKeyMap = normalizeKeyMap;
  10577. CodeMirror.StringStream = StringStream;
  10578. CodeMirror.SharedTextMarker = SharedTextMarker;
  10579. CodeMirror.TextMarker = TextMarker;
  10580. CodeMirror.LineWidget = LineWidget;
  10581. CodeMirror.e_preventDefault = e_preventDefault;
  10582. CodeMirror.e_stopPropagation = e_stopPropagation;
  10583. CodeMirror.e_stop = e_stop;
  10584. CodeMirror.addClass = addClass;
  10585. CodeMirror.contains = contains;
  10586. CodeMirror.rmClass = rmClass;
  10587. CodeMirror.keyNames = keyNames;
  10588. }
  10589. // EDITOR CONSTRUCTOR
  10590. defineOptions(CodeMirror$1);
  10591. addEditorMethods(CodeMirror$1);
  10592. // Set up methods on CodeMirror's prototype to redirect to the editor's document.
  10593. var dontDelegate = "iter insert remove copy getEditor constructor".split(" ");
  10594. for (var prop in Doc.prototype) { if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0)
  10595. { CodeMirror$1.prototype[prop] = (function(method) {
  10596. return function() {return method.apply(this.doc, arguments)}
  10597. })(Doc.prototype[prop]); } }
  10598. eventMixin(Doc);
  10599. // INPUT HANDLING
  10600. CodeMirror$1.inputStyles = {"textarea": TextareaInput, "contenteditable": ContentEditableInput};
  10601. // MODE DEFINITION AND QUERYING
  10602. // Extra arguments are stored as the mode's dependencies, which is
  10603. // used by (legacy) mechanisms like loadmode.js to automatically
  10604. // load a mode. (Preferred mechanism is the require/define calls.)
  10605. CodeMirror$1.defineMode = function(name/*, mode, …*/) {
  10606. if (!CodeMirror$1.defaults.mode && name != "null") { CodeMirror$1.defaults.mode = name; }
  10607. defineMode.apply(this, arguments);
  10608. };
  10609. CodeMirror$1.defineMIME = defineMIME;
  10610. // Minimal default mode.
  10611. CodeMirror$1.defineMode("null", function () { return ({token: function (stream) { return stream.skipToEnd(); }}); });
  10612. CodeMirror$1.defineMIME("text/plain", "null");
  10613. // EXTENSIONS
  10614. CodeMirror$1.defineExtension = function (name, func) {
  10615. CodeMirror$1.prototype[name] = func;
  10616. };
  10617. CodeMirror$1.defineDocExtension = function (name, func) {
  10618. Doc.prototype[name] = func;
  10619. };
  10620. CodeMirror$1.fromTextArea = fromTextArea;
  10621. addLegacyProps(CodeMirror$1);
  10622. CodeMirror$1.version = "5.32.0";
  10623. return CodeMirror$1;
  10624. })));
  10625. /***/ }),
  10626. /* 6 */
  10627. /***/ (function(module, exports, __webpack_require__) {
  10628. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  10629. // Distributed under an MIT license: http://codemirror.net/LICENSE
  10630. (function(mod) {
  10631. if (true) // CommonJS
  10632. mod(__webpack_require__(5));
  10633. else if (typeof define == "function" && define.amd) // AMD
  10634. define(["../../lib/codemirror"], mod);
  10635. else // Plain browser env
  10636. mod(CodeMirror);
  10637. })(function(CodeMirror) {
  10638. "use strict";
  10639. var listRE = /^(\s*)(>[> ]*|[*+-] \[[x ]\]\s|[*+-]\s|(\d+)([.)]))(\s*)/,
  10640. emptyListRE = /^(\s*)(>[> ]*|[*+-] \[[x ]\]|[*+-]|(\d+)[.)])(\s*)$/,
  10641. unorderedListRE = /[*+-]\s/;
  10642. CodeMirror.commands.newlineAndIndentContinueMarkdownList = function(cm) {
  10643. if (cm.getOption("disableInput")) return CodeMirror.Pass;
  10644. var ranges = cm.listSelections(), replacements = [];
  10645. for (var i = 0; i < ranges.length; i++) {
  10646. var pos = ranges[i].head;
  10647. var eolState = cm.getStateAfter(pos.line);
  10648. var inList = eolState.list !== false;
  10649. var inQuote = eolState.quote !== 0;
  10650. var line = cm.getLine(pos.line), match = listRE.exec(line);
  10651. var cursorBeforeBullet = /^\s*$/.test(line.slice(0, pos.ch));
  10652. if (!ranges[i].empty() || (!inList && !inQuote) || !match || cursorBeforeBullet) {
  10653. cm.execCommand("newlineAndIndent");
  10654. return;
  10655. }
  10656. if (emptyListRE.test(line)) {
  10657. if (!/>\s*$/.test(line)) cm.replaceRange("", {
  10658. line: pos.line, ch: 0
  10659. }, {
  10660. line: pos.line, ch: pos.ch + 1
  10661. });
  10662. replacements[i] = "\n";
  10663. } else {
  10664. var indent = match[1], after = match[5];
  10665. var bullet = unorderedListRE.test(match[2]) || match[2].indexOf(">") >= 0
  10666. ? match[2].replace("x", " ")
  10667. : (parseInt(match[3], 10) + 1) + match[4];
  10668. replacements[i] = "\n" + indent + bullet + after;
  10669. incrementRemainingMarkdownListNumbers(cm, pos);
  10670. }
  10671. }
  10672. cm.replaceSelections(replacements);
  10673. };
  10674. // Auto-updating Markdown list numbers when a new item is added to the
  10675. // middle of a list
  10676. function incrementRemainingMarkdownListNumbers(cm, pos) {
  10677. var startLine = pos.line, lookAhead = 0, skipCount = 0;
  10678. var startItem = listRE.exec(cm.getLine(startLine)), startIndent = startItem[1];
  10679. do {
  10680. lookAhead += 1;
  10681. var nextLineNumber = startLine + lookAhead;
  10682. var nextLine = cm.getLine(nextLineNumber), nextItem = listRE.exec(nextLine);
  10683. if (nextItem) {
  10684. var nextIndent = nextItem[1];
  10685. var newNumber = (parseInt(startItem[3], 10) + lookAhead - skipCount);
  10686. var nextNumber = (parseInt(nextItem[3], 10)), itemNumber = nextNumber;
  10687. if (startIndent === nextIndent) {
  10688. if (newNumber === nextNumber) itemNumber = nextNumber + 1;
  10689. if (newNumber > nextNumber) itemNumber = newNumber + 1;
  10690. cm.replaceRange(
  10691. nextLine.replace(listRE, nextIndent + itemNumber + nextItem[4] + nextItem[5]),
  10692. {
  10693. line: nextLineNumber, ch: 0
  10694. }, {
  10695. line: nextLineNumber, ch: nextLine.length
  10696. });
  10697. } else {
  10698. if (startIndent.length > nextIndent.length) return;
  10699. // This doesn't run if the next line immediatley indents, as it is
  10700. // not clear of the users intention (new indented item or same level)
  10701. if ((startIndent.length < nextIndent.length) && (lookAhead === 1)) return;
  10702. skipCount += 1;
  10703. }
  10704. }
  10705. } while (nextItem);
  10706. }
  10707. });
  10708. /***/ }),
  10709. /* 7 */
  10710. /***/ (function(module, exports, __webpack_require__) {
  10711. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  10712. // Distributed under an MIT license: http://codemirror.net/LICENSE
  10713. var CodeMirror = __webpack_require__(5);
  10714. CodeMirror.commands.tabAndIndentMarkdownList = function (cm) {
  10715. var ranges = cm.listSelections();
  10716. var pos = ranges[0].head;
  10717. var eolState = cm.getStateAfter(pos.line);
  10718. var inList = eolState.list !== false;
  10719. if (inList) {
  10720. cm.execCommand("indentMore");
  10721. return;
  10722. }
  10723. if (cm.options.indentWithTabs) {
  10724. cm.execCommand("insertTab");
  10725. }
  10726. else {
  10727. var spaces = Array(cm.options.tabSize + 1).join(" ");
  10728. cm.replaceSelection(spaces);
  10729. }
  10730. };
  10731. CodeMirror.commands.shiftTabAndUnindentMarkdownList = function (cm) {
  10732. var ranges = cm.listSelections();
  10733. var pos = ranges[0].head;
  10734. var eolState = cm.getStateAfter(pos.line);
  10735. var inList = eolState.list !== false;
  10736. if (inList) {
  10737. cm.execCommand("indentLess");
  10738. return;
  10739. }
  10740. if (cm.options.indentWithTabs) {
  10741. cm.execCommand("insertTab");
  10742. }
  10743. else {
  10744. var spaces = Array(cm.options.tabSize + 1).join(" ");
  10745. cm.replaceSelection(spaces);
  10746. }
  10747. };
  10748. /***/ }),
  10749. /* 8 */
  10750. /***/ (function(module, exports, __webpack_require__) {
  10751. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  10752. // Distributed under an MIT license: http://codemirror.net/LICENSE
  10753. (function(mod) {
  10754. if (true) // CommonJS
  10755. mod(__webpack_require__(5));
  10756. else if (typeof define == "function" && define.amd) // AMD
  10757. define(["../../lib/codemirror"], mod);
  10758. else // Plain browser env
  10759. mod(CodeMirror);
  10760. })(function(CodeMirror) {
  10761. "use strict";
  10762. CodeMirror.defineOption("fullScreen", false, function(cm, val, old) {
  10763. if (old == CodeMirror.Init) old = false;
  10764. if (!old == !val) return;
  10765. if (val) setFullscreen(cm);
  10766. else setNormal(cm);
  10767. });
  10768. function setFullscreen(cm) {
  10769. var wrap = cm.getWrapperElement();
  10770. cm.state.fullScreenRestore = {scrollTop: window.pageYOffset, scrollLeft: window.pageXOffset,
  10771. width: wrap.style.width, height: wrap.style.height};
  10772. wrap.style.width = "";
  10773. wrap.style.height = "auto";
  10774. wrap.className += " CodeMirror-fullscreen";
  10775. document.documentElement.style.overflow = "hidden";
  10776. cm.refresh();
  10777. }
  10778. function setNormal(cm) {
  10779. var wrap = cm.getWrapperElement();
  10780. wrap.className = wrap.className.replace(/\s*CodeMirror-fullscreen\b/, "");
  10781. document.documentElement.style.overflow = "";
  10782. var info = cm.state.fullScreenRestore;
  10783. wrap.style.width = info.width; wrap.style.height = info.height;
  10784. window.scrollTo(info.scrollLeft, info.scrollTop);
  10785. cm.refresh();
  10786. }
  10787. });
  10788. /***/ }),
  10789. /* 9 */
  10790. /***/ (function(module, exports, __webpack_require__) {
  10791. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  10792. // Distributed under an MIT license: http://codemirror.net/LICENSE
  10793. (function(mod) {
  10794. if (true) // CommonJS
  10795. mod(__webpack_require__(5), __webpack_require__(10), __webpack_require__(11));
  10796. else if (typeof define == "function" && define.amd) // AMD
  10797. define(["../../lib/codemirror", "../xml/xml", "../meta"], mod);
  10798. else // Plain browser env
  10799. mod(CodeMirror);
  10800. })(function(CodeMirror) {
  10801. "use strict";
  10802. CodeMirror.defineMode("markdown", function(cmCfg, modeCfg) {
  10803. var htmlMode = CodeMirror.getMode(cmCfg, "text/html");
  10804. var htmlModeMissing = htmlMode.name == "null"
  10805. function getMode(name) {
  10806. if (CodeMirror.findModeByName) {
  10807. var found = CodeMirror.findModeByName(name);
  10808. if (found) name = found.mime || found.mimes[0];
  10809. }
  10810. var mode = CodeMirror.getMode(cmCfg, name);
  10811. return mode.name == "null" ? null : mode;
  10812. }
  10813. // Should characters that affect highlighting be highlighted separate?
  10814. // Does not include characters that will be output (such as `1.` and `-` for lists)
  10815. if (modeCfg.highlightFormatting === undefined)
  10816. modeCfg.highlightFormatting = false;
  10817. // Maximum number of nested blockquotes. Set to 0 for infinite nesting.
  10818. // Excess `>` will emit `error` token.
  10819. if (modeCfg.maxBlockquoteDepth === undefined)
  10820. modeCfg.maxBlockquoteDepth = 0;
  10821. // Turn on task lists? ("- [ ] " and "- [x] ")
  10822. if (modeCfg.taskLists === undefined) modeCfg.taskLists = false;
  10823. // Turn on strikethrough syntax
  10824. if (modeCfg.strikethrough === undefined)
  10825. modeCfg.strikethrough = false;
  10826. if (modeCfg.emoji === undefined)
  10827. modeCfg.emoji = false;
  10828. if (modeCfg.fencedCodeBlockHighlighting === undefined)
  10829. modeCfg.fencedCodeBlockHighlighting = true;
  10830. if (modeCfg.xml === undefined)
  10831. modeCfg.xml = true;
  10832. // Allow token types to be overridden by user-provided token types.
  10833. if (modeCfg.tokenTypeOverrides === undefined)
  10834. modeCfg.tokenTypeOverrides = {};
  10835. var tokenTypes = {
  10836. header: "header",
  10837. code: "comment",
  10838. quote: "quote",
  10839. list1: "variable-2",
  10840. list2: "variable-3",
  10841. list3: "keyword",
  10842. hr: "hr",
  10843. image: "image",
  10844. imageAltText: "image-alt-text",
  10845. imageMarker: "image-marker",
  10846. formatting: "formatting",
  10847. linkInline: "link",
  10848. linkEmail: "link",
  10849. linkText: "link",
  10850. linkHref: "string",
  10851. em: "em",
  10852. strong: "strong",
  10853. strikethrough: "strikethrough",
  10854. emoji: "builtin"
  10855. };
  10856. for (var tokenType in tokenTypes) {
  10857. if (tokenTypes.hasOwnProperty(tokenType) && modeCfg.tokenTypeOverrides[tokenType]) {
  10858. tokenTypes[tokenType] = modeCfg.tokenTypeOverrides[tokenType];
  10859. }
  10860. }
  10861. var hrRE = /^([*\-_])(?:\s*\1){2,}\s*$/
  10862. , listRE = /^(?:[*\-+]|^[0-9]+([.)]))\s+/
  10863. , taskListRE = /^\[(x| )\](?=\s)/i // Must follow listRE
  10864. , atxHeaderRE = modeCfg.allowAtxHeaderWithoutSpace ? /^(#+)/ : /^(#+)(?: |$)/
  10865. , setextHeaderRE = /^ *(?:\={1,}|-{1,})\s*$/
  10866. , textRE = /^[^#!\[\]*_\\<>` "'(~:]+/
  10867. , fencedCodeRE = /^(~~~+|```+)[ \t]*([\w+#-]*)[^\n`]*$/
  10868. , linkDefRE = /^\s*\[[^\]]+?\]:\s*\S+(\s*\S*\s*)?$/ // naive link-definition
  10869. , punctuation = /[!\"#$%&\'()*+,\-\.\/:;<=>?@\[\\\]^_`{|}~—]/
  10870. , expandedTab = " " // CommonMark specifies tab as 4 spaces
  10871. function switchInline(stream, state, f) {
  10872. state.f = state.inline = f;
  10873. return f(stream, state);
  10874. }
  10875. function switchBlock(stream, state, f) {
  10876. state.f = state.block = f;
  10877. return f(stream, state);
  10878. }
  10879. function lineIsEmpty(line) {
  10880. return !line || !/\S/.test(line.string)
  10881. }
  10882. // Blocks
  10883. function blankLine(state) {
  10884. // Reset linkTitle state
  10885. state.linkTitle = false;
  10886. // Reset EM state
  10887. state.em = false;
  10888. // Reset STRONG state
  10889. state.strong = false;
  10890. // Reset strikethrough state
  10891. state.strikethrough = false;
  10892. // Reset state.quote
  10893. state.quote = 0;
  10894. // Reset state.indentedCode
  10895. state.indentedCode = false;
  10896. if (state.f == htmlBlock) {
  10897. state.f = inlineNormal;
  10898. state.block = blockNormal;
  10899. }
  10900. // Reset state.trailingSpace
  10901. state.trailingSpace = 0;
  10902. state.trailingSpaceNewLine = false;
  10903. // Mark this line as blank
  10904. state.prevLine = state.thisLine
  10905. state.thisLine = {stream: null}
  10906. return null;
  10907. }
  10908. function blockNormal(stream, state) {
  10909. var firstTokenOnLine = stream.column() === state.indentation;
  10910. var prevLineLineIsEmpty = lineIsEmpty(state.prevLine.stream);
  10911. var prevLineIsIndentedCode = state.indentedCode;
  10912. var prevLineIsHr = state.prevLine.hr;
  10913. var prevLineIsList = state.list !== false;
  10914. var maxNonCodeIndentation = (state.listStack[state.listStack.length - 1] || 0) + 3;
  10915. state.indentedCode = false;
  10916. var lineIndentation = state.indentation;
  10917. // compute once per line (on first token)
  10918. if (state.indentationDiff === null) {
  10919. state.indentationDiff = state.indentation;
  10920. if (prevLineIsList) {
  10921. state.list = null;
  10922. // While this list item's marker's indentation is less than the deepest
  10923. // list item's content's indentation,pop the deepest list item
  10924. // indentation off the stack, and update block indentation state
  10925. while (lineIndentation < state.listStack[state.listStack.length - 1]) {
  10926. state.listStack.pop();
  10927. if (state.listStack.length) {
  10928. state.indentation = state.listStack[state.listStack.length - 1];
  10929. // less than the first list's indent -> the line is no longer a list
  10930. } else {
  10931. state.list = false;
  10932. }
  10933. }
  10934. if (state.list !== false) {
  10935. state.indentationDiff = lineIndentation - state.listStack[state.listStack.length - 1]
  10936. }
  10937. }
  10938. }
  10939. // not comprehensive (currently only for setext detection purposes)
  10940. var allowsInlineContinuation = (
  10941. !prevLineLineIsEmpty && !prevLineIsHr && !state.prevLine.header &&
  10942. (!prevLineIsList || !prevLineIsIndentedCode) &&
  10943. !state.prevLine.fencedCodeEnd
  10944. );
  10945. var isHr = (state.list === false || prevLineIsHr || prevLineLineIsEmpty) &&
  10946. state.indentation <= maxNonCodeIndentation && stream.match(hrRE);
  10947. var match = null;
  10948. if (state.indentationDiff >= 4 && (prevLineIsIndentedCode || state.prevLine.fencedCodeEnd ||
  10949. state.prevLine.header || prevLineLineIsEmpty)) {
  10950. stream.skipToEnd();
  10951. state.indentedCode = true;
  10952. return tokenTypes.code;
  10953. } else if (stream.eatSpace()) {
  10954. return null;
  10955. } else if (firstTokenOnLine && state.indentation <= maxNonCodeIndentation && (match = stream.match(atxHeaderRE)) && match[1].length <= 6) {
  10956. state.quote = 0;
  10957. state.header = match[1].length;
  10958. state.thisLine.header = true;
  10959. if (modeCfg.highlightFormatting) state.formatting = "header";
  10960. state.f = state.inline;
  10961. return getType(state);
  10962. } else if (state.indentation <= maxNonCodeIndentation && stream.eat('>')) {
  10963. state.quote = firstTokenOnLine ? 1 : state.quote + 1;
  10964. if (modeCfg.highlightFormatting) state.formatting = "quote";
  10965. stream.eatSpace();
  10966. return getType(state);
  10967. } else if (!isHr && !state.setext && firstTokenOnLine && state.indentation <= maxNonCodeIndentation && (match = stream.match(listRE))) {
  10968. var listType = match[1] ? "ol" : "ul";
  10969. state.indentation = lineIndentation + stream.current().length;
  10970. state.list = true;
  10971. state.quote = 0;
  10972. // Add this list item's content's indentation to the stack
  10973. state.listStack.push(state.indentation);
  10974. if (modeCfg.taskLists && stream.match(taskListRE, false)) {
  10975. state.taskList = true;
  10976. }
  10977. state.f = state.inline;
  10978. if (modeCfg.highlightFormatting) state.formatting = ["list", "list-" + listType];
  10979. return getType(state);
  10980. } else if (firstTokenOnLine && state.indentation <= maxNonCodeIndentation && (match = stream.match(fencedCodeRE, true))) {
  10981. state.quote = 0;
  10982. state.fencedEndRE = new RegExp(match[1] + "+ *$");
  10983. // try switching mode
  10984. state.localMode = modeCfg.fencedCodeBlockHighlighting && getMode(match[2]);
  10985. if (state.localMode) state.localState = CodeMirror.startState(state.localMode);
  10986. state.f = state.block = local;
  10987. if (modeCfg.highlightFormatting) state.formatting = "code-block";
  10988. state.code = -1
  10989. return getType(state);
  10990. // SETEXT has lowest block-scope precedence after HR, so check it after
  10991. // the others (code, blockquote, list...)
  10992. } else if (
  10993. // if setext set, indicates line after ---/===
  10994. state.setext || (
  10995. // line before ---/===
  10996. (!allowsInlineContinuation || !prevLineIsList) && !state.quote && state.list === false &&
  10997. !state.code && !isHr && !linkDefRE.test(stream.string) &&
  10998. (match = stream.lookAhead(1)) && (match = match.match(setextHeaderRE))
  10999. )
  11000. ) {
  11001. if ( !state.setext ) {
  11002. state.header = match[0].charAt(0) == '=' ? 1 : 2;
  11003. state.setext = state.header;
  11004. } else {
  11005. state.header = state.setext;
  11006. // has no effect on type so we can reset it now
  11007. state.setext = 0;
  11008. stream.skipToEnd();
  11009. if (modeCfg.highlightFormatting) state.formatting = "header";
  11010. }
  11011. state.thisLine.header = true;
  11012. state.f = state.inline;
  11013. return getType(state);
  11014. } else if (isHr) {
  11015. stream.skipToEnd();
  11016. state.hr = true;
  11017. state.thisLine.hr = true;
  11018. return tokenTypes.hr;
  11019. } else if (stream.peek() === '[') {
  11020. return switchInline(stream, state, footnoteLink);
  11021. }
  11022. return switchInline(stream, state, state.inline);
  11023. }
  11024. function htmlBlock(stream, state) {
  11025. var style = htmlMode.token(stream, state.htmlState);
  11026. if (!htmlModeMissing) {
  11027. var inner = CodeMirror.innerMode(htmlMode, state.htmlState)
  11028. if ((inner.mode.name == "xml" && inner.state.tagStart === null &&
  11029. (!inner.state.context && inner.state.tokenize.isInText)) ||
  11030. (state.md_inside && stream.current().indexOf(">") > -1)) {
  11031. state.f = inlineNormal;
  11032. state.block = blockNormal;
  11033. state.htmlState = null;
  11034. }
  11035. }
  11036. return style;
  11037. }
  11038. function local(stream, state) {
  11039. var currListInd = state.listStack[state.listStack.length - 1] || 0;
  11040. var hasExitedList = state.indentation < currListInd;
  11041. var maxFencedEndInd = currListInd + 3;
  11042. if (state.fencedEndRE && state.indentation <= maxFencedEndInd && (hasExitedList || stream.match(state.fencedEndRE))) {
  11043. if (modeCfg.highlightFormatting) state.formatting = "code-block";
  11044. var returnType;
  11045. if (!hasExitedList) returnType = getType(state)
  11046. state.localMode = state.localState = null;
  11047. state.block = blockNormal;
  11048. state.f = inlineNormal;
  11049. state.fencedEndRE = null;
  11050. state.code = 0
  11051. state.thisLine.fencedCodeEnd = true;
  11052. if (hasExitedList) return switchBlock(stream, state, state.block);
  11053. return returnType;
  11054. } else if (state.localMode) {
  11055. return state.localMode.token(stream, state.localState);
  11056. } else {
  11057. stream.skipToEnd();
  11058. return tokenTypes.code;
  11059. }
  11060. }
  11061. // Inline
  11062. function getType(state) {
  11063. var styles = [];
  11064. if (state.formatting) {
  11065. styles.push(tokenTypes.formatting);
  11066. if (typeof state.formatting === "string") state.formatting = [state.formatting];
  11067. for (var i = 0; i < state.formatting.length; i++) {
  11068. styles.push(tokenTypes.formatting + "-" + state.formatting[i]);
  11069. if (state.formatting[i] === "header") {
  11070. styles.push(tokenTypes.formatting + "-" + state.formatting[i] + "-" + state.header);
  11071. }
  11072. // Add `formatting-quote` and `formatting-quote-#` for blockquotes
  11073. // Add `error` instead if the maximum blockquote nesting depth is passed
  11074. if (state.formatting[i] === "quote") {
  11075. if (!modeCfg.maxBlockquoteDepth || modeCfg.maxBlockquoteDepth >= state.quote) {
  11076. styles.push(tokenTypes.formatting + "-" + state.formatting[i] + "-" + state.quote);
  11077. } else {
  11078. styles.push("error");
  11079. }
  11080. }
  11081. }
  11082. }
  11083. if (state.taskOpen) {
  11084. styles.push("meta");
  11085. return styles.length ? styles.join(' ') : null;
  11086. }
  11087. if (state.taskClosed) {
  11088. styles.push("property");
  11089. return styles.length ? styles.join(' ') : null;
  11090. }
  11091. if (state.linkHref) {
  11092. styles.push(tokenTypes.linkHref, "url");
  11093. } else { // Only apply inline styles to non-url text
  11094. if (state.strong) { styles.push(tokenTypes.strong); }
  11095. if (state.em) { styles.push(tokenTypes.em); }
  11096. if (state.strikethrough) { styles.push(tokenTypes.strikethrough); }
  11097. if (state.emoji) { styles.push(tokenTypes.emoji); }
  11098. if (state.linkText) { styles.push(tokenTypes.linkText); }
  11099. if (state.code) { styles.push(tokenTypes.code); }
  11100. if (state.image) { styles.push(tokenTypes.image); }
  11101. if (state.imageAltText) { styles.push(tokenTypes.imageAltText, "link"); }
  11102. if (state.imageMarker) { styles.push(tokenTypes.imageMarker); }
  11103. }
  11104. if (state.header) { styles.push(tokenTypes.header, tokenTypes.header + "-" + state.header); }
  11105. if (state.quote) {
  11106. styles.push(tokenTypes.quote);
  11107. // Add `quote-#` where the maximum for `#` is modeCfg.maxBlockquoteDepth
  11108. if (!modeCfg.maxBlockquoteDepth || modeCfg.maxBlockquoteDepth >= state.quote) {
  11109. styles.push(tokenTypes.quote + "-" + state.quote);
  11110. } else {
  11111. styles.push(tokenTypes.quote + "-" + modeCfg.maxBlockquoteDepth);
  11112. }
  11113. }
  11114. if (state.list !== false) {
  11115. var listMod = (state.listStack.length - 1) % 3;
  11116. if (!listMod) {
  11117. styles.push(tokenTypes.list1);
  11118. } else if (listMod === 1) {
  11119. styles.push(tokenTypes.list2);
  11120. } else {
  11121. styles.push(tokenTypes.list3);
  11122. }
  11123. }
  11124. if (state.trailingSpaceNewLine) {
  11125. styles.push("trailing-space-new-line");
  11126. } else if (state.trailingSpace) {
  11127. styles.push("trailing-space-" + (state.trailingSpace % 2 ? "a" : "b"));
  11128. }
  11129. return styles.length ? styles.join(' ') : null;
  11130. }
  11131. function handleText(stream, state) {
  11132. if (stream.match(textRE, true)) {
  11133. return getType(state);
  11134. }
  11135. return undefined;
  11136. }
  11137. function inlineNormal(stream, state) {
  11138. var style = state.text(stream, state);
  11139. if (typeof style !== 'undefined')
  11140. return style;
  11141. if (state.list) { // List marker (*, +, -, 1., etc)
  11142. state.list = null;
  11143. return getType(state);
  11144. }
  11145. if (state.taskList) {
  11146. var taskOpen = stream.match(taskListRE, true)[1] === " ";
  11147. if (taskOpen) state.taskOpen = true;
  11148. else state.taskClosed = true;
  11149. if (modeCfg.highlightFormatting) state.formatting = "task";
  11150. state.taskList = false;
  11151. return getType(state);
  11152. }
  11153. state.taskOpen = false;
  11154. state.taskClosed = false;
  11155. if (state.header && stream.match(/^#+$/, true)) {
  11156. if (modeCfg.highlightFormatting) state.formatting = "header";
  11157. return getType(state);
  11158. }
  11159. var ch = stream.next();
  11160. // Matches link titles present on next line
  11161. if (state.linkTitle) {
  11162. state.linkTitle = false;
  11163. var matchCh = ch;
  11164. if (ch === '(') {
  11165. matchCh = ')';
  11166. }
  11167. matchCh = (matchCh+'').replace(/([.?*+^\[\]\\(){}|-])/g, "\\$1");
  11168. var regex = '^\\s*(?:[^' + matchCh + '\\\\]+|\\\\\\\\|\\\\.)' + matchCh;
  11169. if (stream.match(new RegExp(regex), true)) {
  11170. return tokenTypes.linkHref;
  11171. }
  11172. }
  11173. // If this block is changed, it may need to be updated in GFM mode
  11174. if (ch === '`') {
  11175. var previousFormatting = state.formatting;
  11176. if (modeCfg.highlightFormatting) state.formatting = "code";
  11177. stream.eatWhile('`');
  11178. var count = stream.current().length
  11179. if (state.code == 0 && (!state.quote || count == 1)) {
  11180. state.code = count
  11181. return getType(state)
  11182. } else if (count == state.code) { // Must be exact
  11183. var t = getType(state)
  11184. state.code = 0
  11185. return t
  11186. } else {
  11187. state.formatting = previousFormatting
  11188. return getType(state)
  11189. }
  11190. } else if (state.code) {
  11191. return getType(state);
  11192. }
  11193. if (ch === '\\') {
  11194. stream.next();
  11195. if (modeCfg.highlightFormatting) {
  11196. var type = getType(state);
  11197. var formattingEscape = tokenTypes.formatting + "-escape";
  11198. return type ? type + " " + formattingEscape : formattingEscape;
  11199. }
  11200. }
  11201. if (ch === '!' && stream.match(/\[[^\]]*\] ?(?:\(|\[)/, false)) {
  11202. state.imageMarker = true;
  11203. state.image = true;
  11204. if (modeCfg.highlightFormatting) state.formatting = "image";
  11205. return getType(state);
  11206. }
  11207. if (ch === '[' && state.imageMarker && stream.match(/[^\]]*\](\(.*?\)| ?\[.*?\])/, false)) {
  11208. state.imageMarker = false;
  11209. state.imageAltText = true
  11210. if (modeCfg.highlightFormatting) state.formatting = "image";
  11211. return getType(state);
  11212. }
  11213. if (ch === ']' && state.imageAltText) {
  11214. if (modeCfg.highlightFormatting) state.formatting = "image";
  11215. var type = getType(state);
  11216. state.imageAltText = false;
  11217. state.image = false;
  11218. state.inline = state.f = linkHref;
  11219. return type;
  11220. }
  11221. if (ch === '[' && !state.image) {
  11222. state.linkText = true;
  11223. if (modeCfg.highlightFormatting) state.formatting = "link";
  11224. return getType(state);
  11225. }
  11226. if (ch === ']' && state.linkText) {
  11227. if (modeCfg.highlightFormatting) state.formatting = "link";
  11228. var type = getType(state);
  11229. state.linkText = false;
  11230. state.inline = state.f = stream.match(/\(.*?\)| ?\[.*?\]/, false) ? linkHref : inlineNormal
  11231. return type;
  11232. }
  11233. if (ch === '<' && stream.match(/^(https?|ftps?):\/\/(?:[^\\>]|\\.)+>/, false)) {
  11234. state.f = state.inline = linkInline;
  11235. if (modeCfg.highlightFormatting) state.formatting = "link";
  11236. var type = getType(state);
  11237. if (type){
  11238. type += " ";
  11239. } else {
  11240. type = "";
  11241. }
  11242. return type + tokenTypes.linkInline;
  11243. }
  11244. if (ch === '<' && stream.match(/^[^> \\]+@(?:[^\\>]|\\.)+>/, false)) {
  11245. state.f = state.inline = linkInline;
  11246. if (modeCfg.highlightFormatting) state.formatting = "link";
  11247. var type = getType(state);
  11248. if (type){
  11249. type += " ";
  11250. } else {
  11251. type = "";
  11252. }
  11253. return type + tokenTypes.linkEmail;
  11254. }
  11255. if (modeCfg.xml && ch === '<' && stream.match(/^(!--|[a-z]+(?:\s+[a-z_:.\-]+(?:\s*=\s*[^ >]+)?)*\s*>)/i, false)) {
  11256. var end = stream.string.indexOf(">", stream.pos);
  11257. if (end != -1) {
  11258. var atts = stream.string.substring(stream.start, end);
  11259. if (/markdown\s*=\s*('|"){0,1}1('|"){0,1}/.test(atts)) state.md_inside = true;
  11260. }
  11261. stream.backUp(1);
  11262. state.htmlState = CodeMirror.startState(htmlMode);
  11263. return switchBlock(stream, state, htmlBlock);
  11264. }
  11265. if (modeCfg.xml && ch === '<' && stream.match(/^\/\w*?>/)) {
  11266. state.md_inside = false;
  11267. return "tag";
  11268. } else if (ch === "*" || ch === "_") {
  11269. var len = 1, before = stream.pos == 1 ? " " : stream.string.charAt(stream.pos - 2)
  11270. while (len < 3 && stream.eat(ch)) len++
  11271. var after = stream.peek() || " "
  11272. // See http://spec.commonmark.org/0.27/#emphasis-and-strong-emphasis
  11273. var leftFlanking = !/\s/.test(after) && (!punctuation.test(after) || /\s/.test(before) || punctuation.test(before))
  11274. var rightFlanking = !/\s/.test(before) && (!punctuation.test(before) || /\s/.test(after) || punctuation.test(after))
  11275. var setEm = null, setStrong = null
  11276. if (len % 2) { // Em
  11277. if (!state.em && leftFlanking && (ch === "*" || !rightFlanking || punctuation.test(before)))
  11278. setEm = true
  11279. else if (state.em == ch && rightFlanking && (ch === "*" || !leftFlanking || punctuation.test(after)))
  11280. setEm = false
  11281. }
  11282. if (len > 1) { // Strong
  11283. if (!state.strong && leftFlanking && (ch === "*" || !rightFlanking || punctuation.test(before)))
  11284. setStrong = true
  11285. else if (state.strong == ch && rightFlanking && (ch === "*" || !leftFlanking || punctuation.test(after)))
  11286. setStrong = false
  11287. }
  11288. if (setStrong != null || setEm != null) {
  11289. if (modeCfg.highlightFormatting) state.formatting = setEm == null ? "strong" : setStrong == null ? "em" : "strong em"
  11290. if (setEm === true) state.em = ch
  11291. if (setStrong === true) state.strong = ch
  11292. var t = getType(state)
  11293. if (setEm === false) state.em = false
  11294. if (setStrong === false) state.strong = false
  11295. return t
  11296. }
  11297. } else if (ch === ' ') {
  11298. if (stream.eat('*') || stream.eat('_')) { // Probably surrounded by spaces
  11299. if (stream.peek() === ' ') { // Surrounded by spaces, ignore
  11300. return getType(state);
  11301. } else { // Not surrounded by spaces, back up pointer
  11302. stream.backUp(1);
  11303. }
  11304. }
  11305. }
  11306. if (modeCfg.strikethrough) {
  11307. if (ch === '~' && stream.eatWhile(ch)) {
  11308. if (state.strikethrough) {// Remove strikethrough
  11309. if (modeCfg.highlightFormatting) state.formatting = "strikethrough";
  11310. var t = getType(state);
  11311. state.strikethrough = false;
  11312. return t;
  11313. } else if (stream.match(/^[^\s]/, false)) {// Add strikethrough
  11314. state.strikethrough = true;
  11315. if (modeCfg.highlightFormatting) state.formatting = "strikethrough";
  11316. return getType(state);
  11317. }
  11318. } else if (ch === ' ') {
  11319. if (stream.match(/^~~/, true)) { // Probably surrounded by space
  11320. if (stream.peek() === ' ') { // Surrounded by spaces, ignore
  11321. return getType(state);
  11322. } else { // Not surrounded by spaces, back up pointer
  11323. stream.backUp(2);
  11324. }
  11325. }
  11326. }
  11327. }
  11328. if (modeCfg.emoji && ch === ":" && stream.match(/^[a-z_\d+-]+:/)) {
  11329. state.emoji = true;
  11330. if (modeCfg.highlightFormatting) state.formatting = "emoji";
  11331. var retType = getType(state);
  11332. state.emoji = false;
  11333. return retType;
  11334. }
  11335. if (ch === ' ') {
  11336. if (stream.match(/ +$/, false)) {
  11337. state.trailingSpace++;
  11338. } else if (state.trailingSpace) {
  11339. state.trailingSpaceNewLine = true;
  11340. }
  11341. }
  11342. return getType(state);
  11343. }
  11344. function linkInline(stream, state) {
  11345. var ch = stream.next();
  11346. if (ch === ">") {
  11347. state.f = state.inline = inlineNormal;
  11348. if (modeCfg.highlightFormatting) state.formatting = "link";
  11349. var type = getType(state);
  11350. if (type){
  11351. type += " ";
  11352. } else {
  11353. type = "";
  11354. }
  11355. return type + tokenTypes.linkInline;
  11356. }
  11357. stream.match(/^[^>]+/, true);
  11358. return tokenTypes.linkInline;
  11359. }
  11360. function linkHref(stream, state) {
  11361. // Check if space, and return NULL if so (to avoid marking the space)
  11362. if(stream.eatSpace()){
  11363. return null;
  11364. }
  11365. var ch = stream.next();
  11366. if (ch === '(' || ch === '[') {
  11367. state.f = state.inline = getLinkHrefInside(ch === "(" ? ")" : "]");
  11368. if (modeCfg.highlightFormatting) state.formatting = "link-string";
  11369. state.linkHref = true;
  11370. return getType(state);
  11371. }
  11372. return 'error';
  11373. }
  11374. var linkRE = {
  11375. ")": /^(?:[^\\\(\)]|\\.|\((?:[^\\\(\)]|\\.)*\))*?(?=\))/,
  11376. "]": /^(?:[^\\\[\]]|\\.|\[(?:[^\\\[\]]|\\.)*\])*?(?=\])/
  11377. }
  11378. function getLinkHrefInside(endChar) {
  11379. return function(stream, state) {
  11380. var ch = stream.next();
  11381. if (ch === endChar) {
  11382. state.f = state.inline = inlineNormal;
  11383. if (modeCfg.highlightFormatting) state.formatting = "link-string";
  11384. var returnState = getType(state);
  11385. state.linkHref = false;
  11386. return returnState;
  11387. }
  11388. stream.match(linkRE[endChar])
  11389. state.linkHref = true;
  11390. return getType(state);
  11391. };
  11392. }
  11393. function footnoteLink(stream, state) {
  11394. if (stream.match(/^([^\]\\]|\\.)*\]:/, false)) {
  11395. state.f = footnoteLinkInside;
  11396. stream.next(); // Consume [
  11397. if (modeCfg.highlightFormatting) state.formatting = "link";
  11398. state.linkText = true;
  11399. return getType(state);
  11400. }
  11401. return switchInline(stream, state, inlineNormal);
  11402. }
  11403. function footnoteLinkInside(stream, state) {
  11404. if (stream.match(/^\]:/, true)) {
  11405. state.f = state.inline = footnoteUrl;
  11406. if (modeCfg.highlightFormatting) state.formatting = "link";
  11407. var returnType = getType(state);
  11408. state.linkText = false;
  11409. return returnType;
  11410. }
  11411. stream.match(/^([^\]\\]|\\.)+/, true);
  11412. return tokenTypes.linkText;
  11413. }
  11414. function footnoteUrl(stream, state) {
  11415. // Check if space, and return NULL if so (to avoid marking the space)
  11416. if(stream.eatSpace()){
  11417. return null;
  11418. }
  11419. // Match URL
  11420. stream.match(/^[^\s]+/, true);
  11421. // Check for link title
  11422. if (stream.peek() === undefined) { // End of line, set flag to check next line
  11423. state.linkTitle = true;
  11424. } else { // More content on line, check if link title
  11425. stream.match(/^(?:\s+(?:"(?:[^"\\]|\\\\|\\.)+"|'(?:[^'\\]|\\\\|\\.)+'|\((?:[^)\\]|\\\\|\\.)+\)))?/, true);
  11426. }
  11427. state.f = state.inline = inlineNormal;
  11428. return tokenTypes.linkHref + " url";
  11429. }
  11430. var mode = {
  11431. startState: function() {
  11432. return {
  11433. f: blockNormal,
  11434. prevLine: {stream: null},
  11435. thisLine: {stream: null},
  11436. block: blockNormal,
  11437. htmlState: null,
  11438. indentation: 0,
  11439. inline: inlineNormal,
  11440. text: handleText,
  11441. formatting: false,
  11442. linkText: false,
  11443. linkHref: false,
  11444. linkTitle: false,
  11445. code: 0,
  11446. em: false,
  11447. strong: false,
  11448. header: 0,
  11449. setext: 0,
  11450. hr: false,
  11451. taskList: false,
  11452. list: false,
  11453. listStack: [],
  11454. quote: 0,
  11455. trailingSpace: 0,
  11456. trailingSpaceNewLine: false,
  11457. strikethrough: false,
  11458. emoji: false,
  11459. fencedEndRE: null
  11460. };
  11461. },
  11462. copyState: function(s) {
  11463. return {
  11464. f: s.f,
  11465. prevLine: s.prevLine,
  11466. thisLine: s.thisLine,
  11467. block: s.block,
  11468. htmlState: s.htmlState && CodeMirror.copyState(htmlMode, s.htmlState),
  11469. indentation: s.indentation,
  11470. localMode: s.localMode,
  11471. localState: s.localMode ? CodeMirror.copyState(s.localMode, s.localState) : null,
  11472. inline: s.inline,
  11473. text: s.text,
  11474. formatting: false,
  11475. linkText: s.linkText,
  11476. linkTitle: s.linkTitle,
  11477. code: s.code,
  11478. em: s.em,
  11479. strong: s.strong,
  11480. strikethrough: s.strikethrough,
  11481. emoji: s.emoji,
  11482. header: s.header,
  11483. setext: s.setext,
  11484. hr: s.hr,
  11485. taskList: s.taskList,
  11486. list: s.list,
  11487. listStack: s.listStack.slice(0),
  11488. quote: s.quote,
  11489. indentedCode: s.indentedCode,
  11490. trailingSpace: s.trailingSpace,
  11491. trailingSpaceNewLine: s.trailingSpaceNewLine,
  11492. md_inside: s.md_inside,
  11493. fencedEndRE: s.fencedEndRE
  11494. };
  11495. },
  11496. token: function(stream, state) {
  11497. // Reset state.formatting
  11498. state.formatting = false;
  11499. if (stream != state.thisLine.stream) {
  11500. state.header = 0;
  11501. state.hr = false;
  11502. if (stream.match(/^\s*$/, true)) {
  11503. blankLine(state);
  11504. return null;
  11505. }
  11506. state.prevLine = state.thisLine
  11507. state.thisLine = {stream: stream}
  11508. // Reset state.taskList
  11509. state.taskList = false;
  11510. // Reset state.trailingSpace
  11511. state.trailingSpace = 0;
  11512. state.trailingSpaceNewLine = false;
  11513. if (!state.localState) {
  11514. state.f = state.block;
  11515. if (state.f != htmlBlock) {
  11516. var indentation = stream.match(/^\s*/, true)[0].replace(/\t/g, expandedTab).length;
  11517. state.indentation = indentation;
  11518. state.indentationDiff = null;
  11519. if (indentation > 0) return null;
  11520. }
  11521. }
  11522. }
  11523. return state.f(stream, state);
  11524. },
  11525. innerMode: function(state) {
  11526. if (state.block == htmlBlock) return {state: state.htmlState, mode: htmlMode};
  11527. if (state.localState) return {state: state.localState, mode: state.localMode};
  11528. return {state: state, mode: mode};
  11529. },
  11530. indent: function(state, textAfter, line) {
  11531. if (state.block == htmlBlock && htmlMode.indent) return htmlMode.indent(state.htmlState, textAfter, line)
  11532. if (state.localState && state.localMode.indent) return state.localMode.indent(state.localState, textAfter, line)
  11533. return CodeMirror.Pass
  11534. },
  11535. blankLine: blankLine,
  11536. getType: getType,
  11537. closeBrackets: "()[]{}''\"\"``",
  11538. fold: "markdown"
  11539. };
  11540. return mode;
  11541. }, "xml");
  11542. CodeMirror.defineMIME("text/x-markdown", "markdown");
  11543. });
  11544. /***/ }),
  11545. /* 10 */
  11546. /***/ (function(module, exports, __webpack_require__) {
  11547. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  11548. // Distributed under an MIT license: http://codemirror.net/LICENSE
  11549. (function(mod) {
  11550. if (true) // CommonJS
  11551. mod(__webpack_require__(5));
  11552. else if (typeof define == "function" && define.amd) // AMD
  11553. define(["../../lib/codemirror"], mod);
  11554. else // Plain browser env
  11555. mod(CodeMirror);
  11556. })(function(CodeMirror) {
  11557. "use strict";
  11558. var htmlConfig = {
  11559. autoSelfClosers: {'area': true, 'base': true, 'br': true, 'col': true, 'command': true,
  11560. 'embed': true, 'frame': true, 'hr': true, 'img': true, 'input': true,
  11561. 'keygen': true, 'link': true, 'meta': true, 'param': true, 'source': true,
  11562. 'track': true, 'wbr': true, 'menuitem': true},
  11563. implicitlyClosed: {'dd': true, 'li': true, 'optgroup': true, 'option': true, 'p': true,
  11564. 'rp': true, 'rt': true, 'tbody': true, 'td': true, 'tfoot': true,
  11565. 'th': true, 'tr': true},
  11566. contextGrabbers: {
  11567. 'dd': {'dd': true, 'dt': true},
  11568. 'dt': {'dd': true, 'dt': true},
  11569. 'li': {'li': true},
  11570. 'option': {'option': true, 'optgroup': true},
  11571. 'optgroup': {'optgroup': true},
  11572. 'p': {'address': true, 'article': true, 'aside': true, 'blockquote': true, 'dir': true,
  11573. 'div': true, 'dl': true, 'fieldset': true, 'footer': true, 'form': true,
  11574. 'h1': true, 'h2': true, 'h3': true, 'h4': true, 'h5': true, 'h6': true,
  11575. 'header': true, 'hgroup': true, 'hr': true, 'menu': true, 'nav': true, 'ol': true,
  11576. 'p': true, 'pre': true, 'section': true, 'table': true, 'ul': true},
  11577. 'rp': {'rp': true, 'rt': true},
  11578. 'rt': {'rp': true, 'rt': true},
  11579. 'tbody': {'tbody': true, 'tfoot': true},
  11580. 'td': {'td': true, 'th': true},
  11581. 'tfoot': {'tbody': true},
  11582. 'th': {'td': true, 'th': true},
  11583. 'thead': {'tbody': true, 'tfoot': true},
  11584. 'tr': {'tr': true}
  11585. },
  11586. doNotIndent: {"pre": true},
  11587. allowUnquoted: true,
  11588. allowMissing: true,
  11589. caseFold: true
  11590. }
  11591. var xmlConfig = {
  11592. autoSelfClosers: {},
  11593. implicitlyClosed: {},
  11594. contextGrabbers: {},
  11595. doNotIndent: {},
  11596. allowUnquoted: false,
  11597. allowMissing: false,
  11598. caseFold: false
  11599. }
  11600. CodeMirror.defineMode("xml", function(editorConf, config_) {
  11601. var indentUnit = editorConf.indentUnit
  11602. var config = {}
  11603. var defaults = config_.htmlMode ? htmlConfig : xmlConfig
  11604. for (var prop in defaults) config[prop] = defaults[prop]
  11605. for (var prop in config_) config[prop] = config_[prop]
  11606. // Return variables for tokenizers
  11607. var type, setStyle;
  11608. function inText(stream, state) {
  11609. function chain(parser) {
  11610. state.tokenize = parser;
  11611. return parser(stream, state);
  11612. }
  11613. var ch = stream.next();
  11614. if (ch == "<") {
  11615. if (stream.eat("!")) {
  11616. if (stream.eat("[")) {
  11617. if (stream.match("CDATA[")) return chain(inBlock("atom", "]]>"));
  11618. else return null;
  11619. } else if (stream.match("--")) {
  11620. return chain(inBlock("comment", "-->"));
  11621. } else if (stream.match("DOCTYPE", true, true)) {
  11622. stream.eatWhile(/[\w\._\-]/);
  11623. return chain(doctype(1));
  11624. } else {
  11625. return null;
  11626. }
  11627. } else if (stream.eat("?")) {
  11628. stream.eatWhile(/[\w\._\-]/);
  11629. state.tokenize = inBlock("meta", "?>");
  11630. return "meta";
  11631. } else {
  11632. type = stream.eat("/") ? "closeTag" : "openTag";
  11633. state.tokenize = inTag;
  11634. return "tag bracket";
  11635. }
  11636. } else if (ch == "&") {
  11637. var ok;
  11638. if (stream.eat("#")) {
  11639. if (stream.eat("x")) {
  11640. ok = stream.eatWhile(/[a-fA-F\d]/) && stream.eat(";");
  11641. } else {
  11642. ok = stream.eatWhile(/[\d]/) && stream.eat(";");
  11643. }
  11644. } else {
  11645. ok = stream.eatWhile(/[\w\.\-:]/) && stream.eat(";");
  11646. }
  11647. return ok ? "atom" : "error";
  11648. } else {
  11649. stream.eatWhile(/[^&<]/);
  11650. return null;
  11651. }
  11652. }
  11653. inText.isInText = true;
  11654. function inTag(stream, state) {
  11655. var ch = stream.next();
  11656. if (ch == ">" || (ch == "/" && stream.eat(">"))) {
  11657. state.tokenize = inText;
  11658. type = ch == ">" ? "endTag" : "selfcloseTag";
  11659. return "tag bracket";
  11660. } else if (ch == "=") {
  11661. type = "equals";
  11662. return null;
  11663. } else if (ch == "<") {
  11664. state.tokenize = inText;
  11665. state.state = baseState;
  11666. state.tagName = state.tagStart = null;
  11667. var next = state.tokenize(stream, state);
  11668. return next ? next + " tag error" : "tag error";
  11669. } else if (/[\'\"]/.test(ch)) {
  11670. state.tokenize = inAttribute(ch);
  11671. state.stringStartCol = stream.column();
  11672. return state.tokenize(stream, state);
  11673. } else {
  11674. stream.match(/^[^\s\u00a0=<>\"\']*[^\s\u00a0=<>\"\'\/]/);
  11675. return "word";
  11676. }
  11677. }
  11678. function inAttribute(quote) {
  11679. var closure = function(stream, state) {
  11680. while (!stream.eol()) {
  11681. if (stream.next() == quote) {
  11682. state.tokenize = inTag;
  11683. break;
  11684. }
  11685. }
  11686. return "string";
  11687. };
  11688. closure.isInAttribute = true;
  11689. return closure;
  11690. }
  11691. function inBlock(style, terminator) {
  11692. return function(stream, state) {
  11693. while (!stream.eol()) {
  11694. if (stream.match(terminator)) {
  11695. state.tokenize = inText;
  11696. break;
  11697. }
  11698. stream.next();
  11699. }
  11700. return style;
  11701. };
  11702. }
  11703. function doctype(depth) {
  11704. return function(stream, state) {
  11705. var ch;
  11706. while ((ch = stream.next()) != null) {
  11707. if (ch == "<") {
  11708. state.tokenize = doctype(depth + 1);
  11709. return state.tokenize(stream, state);
  11710. } else if (ch == ">") {
  11711. if (depth == 1) {
  11712. state.tokenize = inText;
  11713. break;
  11714. } else {
  11715. state.tokenize = doctype(depth - 1);
  11716. return state.tokenize(stream, state);
  11717. }
  11718. }
  11719. }
  11720. return "meta";
  11721. };
  11722. }
  11723. function Context(state, tagName, startOfLine) {
  11724. this.prev = state.context;
  11725. this.tagName = tagName;
  11726. this.indent = state.indented;
  11727. this.startOfLine = startOfLine;
  11728. if (config.doNotIndent.hasOwnProperty(tagName) || (state.context && state.context.noIndent))
  11729. this.noIndent = true;
  11730. }
  11731. function popContext(state) {
  11732. if (state.context) state.context = state.context.prev;
  11733. }
  11734. function maybePopContext(state, nextTagName) {
  11735. var parentTagName;
  11736. while (true) {
  11737. if (!state.context) {
  11738. return;
  11739. }
  11740. parentTagName = state.context.tagName;
  11741. if (!config.contextGrabbers.hasOwnProperty(parentTagName) ||
  11742. !config.contextGrabbers[parentTagName].hasOwnProperty(nextTagName)) {
  11743. return;
  11744. }
  11745. popContext(state);
  11746. }
  11747. }
  11748. function baseState(type, stream, state) {
  11749. if (type == "openTag") {
  11750. state.tagStart = stream.column();
  11751. return tagNameState;
  11752. } else if (type == "closeTag") {
  11753. return closeTagNameState;
  11754. } else {
  11755. return baseState;
  11756. }
  11757. }
  11758. function tagNameState(type, stream, state) {
  11759. if (type == "word") {
  11760. state.tagName = stream.current();
  11761. setStyle = "tag";
  11762. return attrState;
  11763. } else {
  11764. setStyle = "error";
  11765. return tagNameState;
  11766. }
  11767. }
  11768. function closeTagNameState(type, stream, state) {
  11769. if (type == "word") {
  11770. var tagName = stream.current();
  11771. if (state.context && state.context.tagName != tagName &&
  11772. config.implicitlyClosed.hasOwnProperty(state.context.tagName))
  11773. popContext(state);
  11774. if ((state.context && state.context.tagName == tagName) || config.matchClosing === false) {
  11775. setStyle = "tag";
  11776. return closeState;
  11777. } else {
  11778. setStyle = "tag error";
  11779. return closeStateErr;
  11780. }
  11781. } else {
  11782. setStyle = "error";
  11783. return closeStateErr;
  11784. }
  11785. }
  11786. function closeState(type, _stream, state) {
  11787. if (type != "endTag") {
  11788. setStyle = "error";
  11789. return closeState;
  11790. }
  11791. popContext(state);
  11792. return baseState;
  11793. }
  11794. function closeStateErr(type, stream, state) {
  11795. setStyle = "error";
  11796. return closeState(type, stream, state);
  11797. }
  11798. function attrState(type, _stream, state) {
  11799. if (type == "word") {
  11800. setStyle = "attribute";
  11801. return attrEqState;
  11802. } else if (type == "endTag" || type == "selfcloseTag") {
  11803. var tagName = state.tagName, tagStart = state.tagStart;
  11804. state.tagName = state.tagStart = null;
  11805. if (type == "selfcloseTag" ||
  11806. config.autoSelfClosers.hasOwnProperty(tagName)) {
  11807. maybePopContext(state, tagName);
  11808. } else {
  11809. maybePopContext(state, tagName);
  11810. state.context = new Context(state, tagName, tagStart == state.indented);
  11811. }
  11812. return baseState;
  11813. }
  11814. setStyle = "error";
  11815. return attrState;
  11816. }
  11817. function attrEqState(type, stream, state) {
  11818. if (type == "equals") return attrValueState;
  11819. if (!config.allowMissing) setStyle = "error";
  11820. return attrState(type, stream, state);
  11821. }
  11822. function attrValueState(type, stream, state) {
  11823. if (type == "string") return attrContinuedState;
  11824. if (type == "word" && config.allowUnquoted) {setStyle = "string"; return attrState;}
  11825. setStyle = "error";
  11826. return attrState(type, stream, state);
  11827. }
  11828. function attrContinuedState(type, stream, state) {
  11829. if (type == "string") return attrContinuedState;
  11830. return attrState(type, stream, state);
  11831. }
  11832. return {
  11833. startState: function(baseIndent) {
  11834. var state = {tokenize: inText,
  11835. state: baseState,
  11836. indented: baseIndent || 0,
  11837. tagName: null, tagStart: null,
  11838. context: null}
  11839. if (baseIndent != null) state.baseIndent = baseIndent
  11840. return state
  11841. },
  11842. token: function(stream, state) {
  11843. if (!state.tagName && stream.sol())
  11844. state.indented = stream.indentation();
  11845. if (stream.eatSpace()) return null;
  11846. type = null;
  11847. var style = state.tokenize(stream, state);
  11848. if ((style || type) && style != "comment") {
  11849. setStyle = null;
  11850. state.state = state.state(type || style, stream, state);
  11851. if (setStyle)
  11852. style = setStyle == "error" ? style + " error" : setStyle;
  11853. }
  11854. return style;
  11855. },
  11856. indent: function(state, textAfter, fullLine) {
  11857. var context = state.context;
  11858. // Indent multi-line strings (e.g. css).
  11859. if (state.tokenize.isInAttribute) {
  11860. if (state.tagStart == state.indented)
  11861. return state.stringStartCol + 1;
  11862. else
  11863. return state.indented + indentUnit;
  11864. }
  11865. if (context && context.noIndent) return CodeMirror.Pass;
  11866. if (state.tokenize != inTag && state.tokenize != inText)
  11867. return fullLine ? fullLine.match(/^(\s*)/)[0].length : 0;
  11868. // Indent the starts of attribute names.
  11869. if (state.tagName) {
  11870. if (config.multilineTagIndentPastTag !== false)
  11871. return state.tagStart + state.tagName.length + 2;
  11872. else
  11873. return state.tagStart + indentUnit * (config.multilineTagIndentFactor || 1);
  11874. }
  11875. if (config.alignCDATA && /<!\[CDATA\[/.test(textAfter)) return 0;
  11876. var tagAfter = textAfter && /^<(\/)?([\w_:\.-]*)/.exec(textAfter);
  11877. if (tagAfter && tagAfter[1]) { // Closing tag spotted
  11878. while (context) {
  11879. if (context.tagName == tagAfter[2]) {
  11880. context = context.prev;
  11881. break;
  11882. } else if (config.implicitlyClosed.hasOwnProperty(context.tagName)) {
  11883. context = context.prev;
  11884. } else {
  11885. break;
  11886. }
  11887. }
  11888. } else if (tagAfter) { // Opening tag spotted
  11889. while (context) {
  11890. var grabbers = config.contextGrabbers[context.tagName];
  11891. if (grabbers && grabbers.hasOwnProperty(tagAfter[2]))
  11892. context = context.prev;
  11893. else
  11894. break;
  11895. }
  11896. }
  11897. while (context && context.prev && !context.startOfLine)
  11898. context = context.prev;
  11899. if (context) return context.indent + indentUnit;
  11900. else return state.baseIndent || 0;
  11901. },
  11902. electricInput: /<\/[\s\w:]+>$/,
  11903. blockCommentStart: "<!--",
  11904. blockCommentEnd: "-->",
  11905. configuration: config.htmlMode ? "html" : "xml",
  11906. helperType: config.htmlMode ? "html" : "xml",
  11907. skipAttribute: function(state) {
  11908. if (state.state == attrValueState)
  11909. state.state = attrState
  11910. }
  11911. };
  11912. });
  11913. CodeMirror.defineMIME("text/xml", "xml");
  11914. CodeMirror.defineMIME("application/xml", "xml");
  11915. if (!CodeMirror.mimeModes.hasOwnProperty("text/html"))
  11916. CodeMirror.defineMIME("text/html", {name: "xml", htmlMode: true});
  11917. });
  11918. /***/ }),
  11919. /* 11 */
  11920. /***/ (function(module, exports, __webpack_require__) {
  11921. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  11922. // Distributed under an MIT license: http://codemirror.net/LICENSE
  11923. (function(mod) {
  11924. if (true) // CommonJS
  11925. mod(__webpack_require__(5));
  11926. else if (typeof define == "function" && define.amd) // AMD
  11927. define(["../lib/codemirror"], mod);
  11928. else // Plain browser env
  11929. mod(CodeMirror);
  11930. })(function(CodeMirror) {
  11931. "use strict";
  11932. CodeMirror.modeInfo = [
  11933. {name: "APL", mime: "text/apl", mode: "apl", ext: ["dyalog", "apl"]},
  11934. {name: "PGP", mimes: ["application/pgp", "application/pgp-encrypted", "application/pgp-keys", "application/pgp-signature"], mode: "asciiarmor", ext: ["asc", "pgp", "sig"]},
  11935. {name: "ASN.1", mime: "text/x-ttcn-asn", mode: "asn.1", ext: ["asn", "asn1"]},
  11936. {name: "Asterisk", mime: "text/x-asterisk", mode: "asterisk", file: /^extensions\.conf$/i},
  11937. {name: "Brainfuck", mime: "text/x-brainfuck", mode: "brainfuck", ext: ["b", "bf"]},
  11938. {name: "C", mime: "text/x-csrc", mode: "clike", ext: ["c", "h"]},
  11939. {name: "C++", mime: "text/x-c++src", mode: "clike", ext: ["cpp", "c++", "cc", "cxx", "hpp", "h++", "hh", "hxx"], alias: ["cpp"]},
  11940. {name: "Cobol", mime: "text/x-cobol", mode: "cobol", ext: ["cob", "cpy"]},
  11941. {name: "C#", mime: "text/x-csharp", mode: "clike", ext: ["cs"], alias: ["csharp"]},
  11942. {name: "Clojure", mime: "text/x-clojure", mode: "clojure", ext: ["clj", "cljc", "cljx"]},
  11943. {name: "ClojureScript", mime: "text/x-clojurescript", mode: "clojure", ext: ["cljs"]},
  11944. {name: "Closure Stylesheets (GSS)", mime: "text/x-gss", mode: "css", ext: ["gss"]},
  11945. {name: "CMake", mime: "text/x-cmake", mode: "cmake", ext: ["cmake", "cmake.in"], file: /^CMakeLists.txt$/},
  11946. {name: "CoffeeScript", mimes: ["application/vnd.coffeescript", "text/coffeescript", "text/x-coffeescript"], mode: "coffeescript", ext: ["coffee"], alias: ["coffee", "coffee-script"]},
  11947. {name: "Common Lisp", mime: "text/x-common-lisp", mode: "commonlisp", ext: ["cl", "lisp", "el"], alias: ["lisp"]},
  11948. {name: "Cypher", mime: "application/x-cypher-query", mode: "cypher", ext: ["cyp", "cypher"]},
  11949. {name: "Cython", mime: "text/x-cython", mode: "python", ext: ["pyx", "pxd", "pxi"]},
  11950. {name: "Crystal", mime: "text/x-crystal", mode: "crystal", ext: ["cr"]},
  11951. {name: "CSS", mime: "text/css", mode: "css", ext: ["css"]},
  11952. {name: "CQL", mime: "text/x-cassandra", mode: "sql", ext: ["cql"]},
  11953. {name: "D", mime: "text/x-d", mode: "d", ext: ["d"]},
  11954. {name: "Dart", mimes: ["application/dart", "text/x-dart"], mode: "dart", ext: ["dart"]},
  11955. {name: "diff", mime: "text/x-diff", mode: "diff", ext: ["diff", "patch"]},
  11956. {name: "Django", mime: "text/x-django", mode: "django"},
  11957. {name: "Dockerfile", mime: "text/x-dockerfile", mode: "dockerfile", file: /^Dockerfile$/},
  11958. {name: "DTD", mime: "application/xml-dtd", mode: "dtd", ext: ["dtd"]},
  11959. {name: "Dylan", mime: "text/x-dylan", mode: "dylan", ext: ["dylan", "dyl", "intr"]},
  11960. {name: "EBNF", mime: "text/x-ebnf", mode: "ebnf"},
  11961. {name: "ECL", mime: "text/x-ecl", mode: "ecl", ext: ["ecl"]},
  11962. {name: "edn", mime: "application/edn", mode: "clojure", ext: ["edn"]},
  11963. {name: "Eiffel", mime: "text/x-eiffel", mode: "eiffel", ext: ["e"]},
  11964. {name: "Elm", mime: "text/x-elm", mode: "elm", ext: ["elm"]},
  11965. {name: "Embedded Javascript", mime: "application/x-ejs", mode: "htmlembedded", ext: ["ejs"]},
  11966. {name: "Embedded Ruby", mime: "application/x-erb", mode: "htmlembedded", ext: ["erb"]},
  11967. {name: "Erlang", mime: "text/x-erlang", mode: "erlang", ext: ["erl"]},
  11968. {name: "Esper", mime: "text/x-esper", mode: "sql"},
  11969. {name: "Factor", mime: "text/x-factor", mode: "factor", ext: ["factor"]},
  11970. {name: "FCL", mime: "text/x-fcl", mode: "fcl"},
  11971. {name: "Forth", mime: "text/x-forth", mode: "forth", ext: ["forth", "fth", "4th"]},
  11972. {name: "Fortran", mime: "text/x-fortran", mode: "fortran", ext: ["f", "for", "f77", "f90"]},
  11973. {name: "F#", mime: "text/x-fsharp", mode: "mllike", ext: ["fs"], alias: ["fsharp"]},
  11974. {name: "Gas", mime: "text/x-gas", mode: "gas", ext: ["s"]},
  11975. {name: "Gherkin", mime: "text/x-feature", mode: "gherkin", ext: ["feature"]},
  11976. {name: "GitHub Flavored Markdown", mime: "text/x-gfm", mode: "gfm", file: /^(readme|contributing|history).md$/i},
  11977. {name: "Go", mime: "text/x-go", mode: "go", ext: ["go"]},
  11978. {name: "Groovy", mime: "text/x-groovy", mode: "groovy", ext: ["groovy", "gradle"], file: /^Jenkinsfile$/},
  11979. {name: "HAML", mime: "text/x-haml", mode: "haml", ext: ["haml"]},
  11980. {name: "Haskell", mime: "text/x-haskell", mode: "haskell", ext: ["hs"]},
  11981. {name: "Haskell (Literate)", mime: "text/x-literate-haskell", mode: "haskell-literate", ext: ["lhs"]},
  11982. {name: "Haxe", mime: "text/x-haxe", mode: "haxe", ext: ["hx"]},
  11983. {name: "HXML", mime: "text/x-hxml", mode: "haxe", ext: ["hxml"]},
  11984. {name: "ASP.NET", mime: "application/x-aspx", mode: "htmlembedded", ext: ["aspx"], alias: ["asp", "aspx"]},
  11985. {name: "HTML", mime: "text/html", mode: "htmlmixed", ext: ["html", "htm"], alias: ["xhtml"]},
  11986. {name: "HTTP", mime: "message/http", mode: "http"},
  11987. {name: "IDL", mime: "text/x-idl", mode: "idl", ext: ["pro"]},
  11988. {name: "Pug", mime: "text/x-pug", mode: "pug", ext: ["jade", "pug"], alias: ["jade"]},
  11989. {name: "Java", mime: "text/x-java", mode: "clike", ext: ["java"]},
  11990. {name: "Java Server Pages", mime: "application/x-jsp", mode: "htmlembedded", ext: ["jsp"], alias: ["jsp"]},
  11991. {name: "JavaScript", mimes: ["text/javascript", "text/ecmascript", "application/javascript", "application/x-javascript", "application/ecmascript"],
  11992. mode: "javascript", ext: ["js"], alias: ["ecmascript", "js", "node"]},
  11993. {name: "JSON", mimes: ["application/json", "application/x-json"], mode: "javascript", ext: ["json", "map"], alias: ["json5"]},
  11994. {name: "JSON-LD", mime: "application/ld+json", mode: "javascript", ext: ["jsonld"], alias: ["jsonld"]},
  11995. {name: "JSX", mime: "text/jsx", mode: "jsx", ext: ["jsx"]},
  11996. {name: "Jinja2", mime: "null", mode: "jinja2"},
  11997. {name: "Julia", mime: "text/x-julia", mode: "julia", ext: ["jl"]},
  11998. {name: "Kotlin", mime: "text/x-kotlin", mode: "clike", ext: ["kt"]},
  11999. {name: "LESS", mime: "text/x-less", mode: "css", ext: ["less"]},
  12000. {name: "LiveScript", mime: "text/x-livescript", mode: "livescript", ext: ["ls"], alias: ["ls"]},
  12001. {name: "Lua", mime: "text/x-lua", mode: "lua", ext: ["lua"]},
  12002. {name: "Markdown", mime: "text/x-markdown", mode: "markdown", ext: ["markdown", "md", "mkd"]},
  12003. {name: "mIRC", mime: "text/mirc", mode: "mirc"},
  12004. {name: "MariaDB SQL", mime: "text/x-mariadb", mode: "sql"},
  12005. {name: "Mathematica", mime: "text/x-mathematica", mode: "mathematica", ext: ["m", "nb"]},
  12006. {name: "Modelica", mime: "text/x-modelica", mode: "modelica", ext: ["mo"]},
  12007. {name: "MUMPS", mime: "text/x-mumps", mode: "mumps", ext: ["mps"]},
  12008. {name: "MS SQL", mime: "text/x-mssql", mode: "sql"},
  12009. {name: "mbox", mime: "application/mbox", mode: "mbox", ext: ["mbox"]},
  12010. {name: "MySQL", mime: "text/x-mysql", mode: "sql"},
  12011. {name: "Nginx", mime: "text/x-nginx-conf", mode: "nginx", file: /nginx.*\.conf$/i},
  12012. {name: "NSIS", mime: "text/x-nsis", mode: "nsis", ext: ["nsh", "nsi"]},
  12013. {name: "NTriples", mimes: ["application/n-triples", "application/n-quads", "text/n-triples"],
  12014. mode: "ntriples", ext: ["nt", "nq"]},
  12015. {name: "Objective C", mime: "text/x-objectivec", mode: "clike", ext: ["m", "mm"], alias: ["objective-c", "objc"]},
  12016. {name: "OCaml", mime: "text/x-ocaml", mode: "mllike", ext: ["ml", "mli", "mll", "mly"]},
  12017. {name: "Octave", mime: "text/x-octave", mode: "octave", ext: ["m"]},
  12018. {name: "Oz", mime: "text/x-oz", mode: "oz", ext: ["oz"]},
  12019. {name: "Pascal", mime: "text/x-pascal", mode: "pascal", ext: ["p", "pas"]},
  12020. {name: "PEG.js", mime: "null", mode: "pegjs", ext: ["jsonld"]},
  12021. {name: "Perl", mime: "text/x-perl", mode: "perl", ext: ["pl", "pm"]},
  12022. {name: "PHP", mime: ["application/x-httpd-php", "text/x-php"], mode: "php", ext: ["php", "php3", "php4", "php5", "php7", "phtml"]},
  12023. {name: "Pig", mime: "text/x-pig", mode: "pig", ext: ["pig"]},
  12024. {name: "Plain Text", mime: "text/plain", mode: "null", ext: ["txt", "text", "conf", "def", "list", "log"]},
  12025. {name: "PLSQL", mime: "text/x-plsql", mode: "sql", ext: ["pls"]},
  12026. {name: "PowerShell", mime: "application/x-powershell", mode: "powershell", ext: ["ps1", "psd1", "psm1"]},
  12027. {name: "Properties files", mime: "text/x-properties", mode: "properties", ext: ["properties", "ini", "in"], alias: ["ini", "properties"]},
  12028. {name: "ProtoBuf", mime: "text/x-protobuf", mode: "protobuf", ext: ["proto"]},
  12029. {name: "Python", mime: "text/x-python", mode: "python", ext: ["BUILD", "bzl", "py", "pyw"], file: /^(BUCK|BUILD)$/},
  12030. {name: "Puppet", mime: "text/x-puppet", mode: "puppet", ext: ["pp"]},
  12031. {name: "Q", mime: "text/x-q", mode: "q", ext: ["q"]},
  12032. {name: "R", mime: "text/x-rsrc", mode: "r", ext: ["r", "R"], alias: ["rscript"]},
  12033. {name: "reStructuredText", mime: "text/x-rst", mode: "rst", ext: ["rst"], alias: ["rst"]},
  12034. {name: "RPM Changes", mime: "text/x-rpm-changes", mode: "rpm"},
  12035. {name: "RPM Spec", mime: "text/x-rpm-spec", mode: "rpm", ext: ["spec"]},
  12036. {name: "Ruby", mime: "text/x-ruby", mode: "ruby", ext: ["rb"], alias: ["jruby", "macruby", "rake", "rb", "rbx"]},
  12037. {name: "Rust", mime: "text/x-rustsrc", mode: "rust", ext: ["rs"]},
  12038. {name: "SAS", mime: "text/x-sas", mode: "sas", ext: ["sas"]},
  12039. {name: "Sass", mime: "text/x-sass", mode: "sass", ext: ["sass"]},
  12040. {name: "Scala", mime: "text/x-scala", mode: "clike", ext: ["scala"]},
  12041. {name: "Scheme", mime: "text/x-scheme", mode: "scheme", ext: ["scm", "ss"]},
  12042. {name: "SCSS", mime: "text/x-scss", mode: "css", ext: ["scss"]},
  12043. {name: "Shell", mimes: ["text/x-sh", "application/x-sh"], mode: "shell", ext: ["sh", "ksh", "bash"], alias: ["bash", "sh", "zsh"], file: /^PKGBUILD$/},
  12044. {name: "Sieve", mime: "application/sieve", mode: "sieve", ext: ["siv", "sieve"]},
  12045. {name: "Slim", mimes: ["text/x-slim", "application/x-slim"], mode: "slim", ext: ["slim"]},
  12046. {name: "Smalltalk", mime: "text/x-stsrc", mode: "smalltalk", ext: ["st"]},
  12047. {name: "Smarty", mime: "text/x-smarty", mode: "smarty", ext: ["tpl"]},
  12048. {name: "Solr", mime: "text/x-solr", mode: "solr"},
  12049. {name: "Soy", mime: "text/x-soy", mode: "soy", ext: ["soy"], alias: ["closure template"]},
  12050. {name: "SPARQL", mime: "application/sparql-query", mode: "sparql", ext: ["rq", "sparql"], alias: ["sparul"]},
  12051. {name: "Spreadsheet", mime: "text/x-spreadsheet", mode: "spreadsheet", alias: ["excel", "formula"]},
  12052. {name: "SQL", mime: "text/x-sql", mode: "sql", ext: ["sql"]},
  12053. {name: "SQLite", mime: "text/x-sqlite", mode: "sql"},
  12054. {name: "Squirrel", mime: "text/x-squirrel", mode: "clike", ext: ["nut"]},
  12055. {name: "Stylus", mime: "text/x-styl", mode: "stylus", ext: ["styl"]},
  12056. {name: "Swift", mime: "text/x-swift", mode: "swift", ext: ["swift"]},
  12057. {name: "sTeX", mime: "text/x-stex", mode: "stex"},
  12058. {name: "LaTeX", mime: "text/x-latex", mode: "stex", ext: ["text", "ltx"], alias: ["tex"]},
  12059. {name: "SystemVerilog", mime: "text/x-systemverilog", mode: "verilog", ext: ["v", "sv", "svh"]},
  12060. {name: "Tcl", mime: "text/x-tcl", mode: "tcl", ext: ["tcl"]},
  12061. {name: "Textile", mime: "text/x-textile", mode: "textile", ext: ["textile"]},
  12062. {name: "TiddlyWiki ", mime: "text/x-tiddlywiki", mode: "tiddlywiki"},
  12063. {name: "Tiki wiki", mime: "text/tiki", mode: "tiki"},
  12064. {name: "TOML", mime: "text/x-toml", mode: "toml", ext: ["toml"]},
  12065. {name: "Tornado", mime: "text/x-tornado", mode: "tornado"},
  12066. {name: "troff", mime: "text/troff", mode: "troff", ext: ["1", "2", "3", "4", "5", "6", "7", "8", "9"]},
  12067. {name: "TTCN", mime: "text/x-ttcn", mode: "ttcn", ext: ["ttcn", "ttcn3", "ttcnpp"]},
  12068. {name: "TTCN_CFG", mime: "text/x-ttcn-cfg", mode: "ttcn-cfg", ext: ["cfg"]},
  12069. {name: "Turtle", mime: "text/turtle", mode: "turtle", ext: ["ttl"]},
  12070. {name: "TypeScript", mime: "application/typescript", mode: "javascript", ext: ["ts"], alias: ["ts"]},
  12071. {name: "TypeScript-JSX", mime: "text/typescript-jsx", mode: "jsx", ext: ["tsx"], alias: ["tsx"]},
  12072. {name: "Twig", mime: "text/x-twig", mode: "twig"},
  12073. {name: "Web IDL", mime: "text/x-webidl", mode: "webidl", ext: ["webidl"]},
  12074. {name: "VB.NET", mime: "text/x-vb", mode: "vb", ext: ["vb"]},
  12075. {name: "VBScript", mime: "text/vbscript", mode: "vbscript", ext: ["vbs"]},
  12076. {name: "Velocity", mime: "text/velocity", mode: "velocity", ext: ["vtl"]},
  12077. {name: "Verilog", mime: "text/x-verilog", mode: "verilog", ext: ["v"]},
  12078. {name: "VHDL", mime: "text/x-vhdl", mode: "vhdl", ext: ["vhd", "vhdl"]},
  12079. {name: "Vue.js Component", mimes: ["script/x-vue", "text/x-vue"], mode: "vue", ext: ["vue"]},
  12080. {name: "XML", mimes: ["application/xml", "text/xml"], mode: "xml", ext: ["xml", "xsl", "xsd", "svg"], alias: ["rss", "wsdl", "xsd"]},
  12081. {name: "XQuery", mime: "application/xquery", mode: "xquery", ext: ["xy", "xquery"]},
  12082. {name: "Yacas", mime: "text/x-yacas", mode: "yacas", ext: ["ys"]},
  12083. {name: "YAML", mimes: ["text/x-yaml", "text/yaml"], mode: "yaml", ext: ["yaml", "yml"], alias: ["yml"]},
  12084. {name: "Z80", mime: "text/x-z80", mode: "z80", ext: ["z80"]},
  12085. {name: "mscgen", mime: "text/x-mscgen", mode: "mscgen", ext: ["mscgen", "mscin", "msc"]},
  12086. {name: "xu", mime: "text/x-xu", mode: "mscgen", ext: ["xu"]},
  12087. {name: "msgenny", mime: "text/x-msgenny", mode: "mscgen", ext: ["msgenny"]}
  12088. ];
  12089. // Ensure all modes have a mime property for backwards compatibility
  12090. for (var i = 0; i < CodeMirror.modeInfo.length; i++) {
  12091. var info = CodeMirror.modeInfo[i];
  12092. if (info.mimes) info.mime = info.mimes[0];
  12093. }
  12094. CodeMirror.findModeByMIME = function(mime) {
  12095. mime = mime.toLowerCase();
  12096. for (var i = 0; i < CodeMirror.modeInfo.length; i++) {
  12097. var info = CodeMirror.modeInfo[i];
  12098. if (info.mime == mime) return info;
  12099. if (info.mimes) for (var j = 0; j < info.mimes.length; j++)
  12100. if (info.mimes[j] == mime) return info;
  12101. }
  12102. if (/\+xml$/.test(mime)) return CodeMirror.findModeByMIME("application/xml")
  12103. if (/\+json$/.test(mime)) return CodeMirror.findModeByMIME("application/json")
  12104. };
  12105. CodeMirror.findModeByExtension = function(ext) {
  12106. for (var i = 0; i < CodeMirror.modeInfo.length; i++) {
  12107. var info = CodeMirror.modeInfo[i];
  12108. if (info.ext) for (var j = 0; j < info.ext.length; j++)
  12109. if (info.ext[j] == ext) return info;
  12110. }
  12111. };
  12112. CodeMirror.findModeByFileName = function(filename) {
  12113. for (var i = 0; i < CodeMirror.modeInfo.length; i++) {
  12114. var info = CodeMirror.modeInfo[i];
  12115. if (info.file && info.file.test(filename)) return info;
  12116. }
  12117. var dot = filename.lastIndexOf(".");
  12118. var ext = dot > -1 && filename.substring(dot + 1, filename.length);
  12119. if (ext) return CodeMirror.findModeByExtension(ext);
  12120. };
  12121. CodeMirror.findModeByName = function(name) {
  12122. name = name.toLowerCase();
  12123. for (var i = 0; i < CodeMirror.modeInfo.length; i++) {
  12124. var info = CodeMirror.modeInfo[i];
  12125. if (info.name.toLowerCase() == name) return info;
  12126. if (info.alias) for (var j = 0; j < info.alias.length; j++)
  12127. if (info.alias[j].toLowerCase() == name) return info;
  12128. }
  12129. };
  12130. });
  12131. /***/ }),
  12132. /* 12 */
  12133. /***/ (function(module, exports, __webpack_require__) {
  12134. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  12135. // Distributed under an MIT license: http://codemirror.net/LICENSE
  12136. // Utility function that allows modes to be combined. The mode given
  12137. // as the base argument takes care of most of the normal mode
  12138. // functionality, but a second (typically simple) mode is used, which
  12139. // can override the style of text. Both modes get to parse all of the
  12140. // text, but when both assign a non-null style to a piece of code, the
  12141. // overlay wins, unless the combine argument was true and not overridden,
  12142. // or state.overlay.combineTokens was true, in which case the styles are
  12143. // combined.
  12144. (function(mod) {
  12145. if (true) // CommonJS
  12146. mod(__webpack_require__(5));
  12147. else if (typeof define == "function" && define.amd) // AMD
  12148. define(["../../lib/codemirror"], mod);
  12149. else // Plain browser env
  12150. mod(CodeMirror);
  12151. })(function(CodeMirror) {
  12152. "use strict";
  12153. CodeMirror.overlayMode = function(base, overlay, combine) {
  12154. return {
  12155. startState: function() {
  12156. return {
  12157. base: CodeMirror.startState(base),
  12158. overlay: CodeMirror.startState(overlay),
  12159. basePos: 0, baseCur: null,
  12160. overlayPos: 0, overlayCur: null,
  12161. streamSeen: null
  12162. };
  12163. },
  12164. copyState: function(state) {
  12165. return {
  12166. base: CodeMirror.copyState(base, state.base),
  12167. overlay: CodeMirror.copyState(overlay, state.overlay),
  12168. basePos: state.basePos, baseCur: null,
  12169. overlayPos: state.overlayPos, overlayCur: null
  12170. };
  12171. },
  12172. token: function(stream, state) {
  12173. if (stream != state.streamSeen ||
  12174. Math.min(state.basePos, state.overlayPos) < stream.start) {
  12175. state.streamSeen = stream;
  12176. state.basePos = state.overlayPos = stream.start;
  12177. }
  12178. if (stream.start == state.basePos) {
  12179. state.baseCur = base.token(stream, state.base);
  12180. state.basePos = stream.pos;
  12181. }
  12182. if (stream.start == state.overlayPos) {
  12183. stream.pos = stream.start;
  12184. state.overlayCur = overlay.token(stream, state.overlay);
  12185. state.overlayPos = stream.pos;
  12186. }
  12187. stream.pos = Math.min(state.basePos, state.overlayPos);
  12188. // state.overlay.combineTokens always takes precedence over combine,
  12189. // unless set to null
  12190. if (state.overlayCur == null) return state.baseCur;
  12191. else if (state.baseCur != null &&
  12192. state.overlay.combineTokens ||
  12193. combine && state.overlay.combineTokens == null)
  12194. return state.baseCur + " " + state.overlayCur;
  12195. else return state.overlayCur;
  12196. },
  12197. indent: base.indent && function(state, textAfter) {
  12198. return base.indent(state.base, textAfter);
  12199. },
  12200. electricChars: base.electricChars,
  12201. innerMode: function(state) { return {state: state.base, mode: base}; },
  12202. blankLine: function(state) {
  12203. var baseToken, overlayToken;
  12204. if (base.blankLine) baseToken = base.blankLine(state.base);
  12205. if (overlay.blankLine) overlayToken = overlay.blankLine(state.overlay);
  12206. return overlayToken == null ?
  12207. baseToken :
  12208. (combine && baseToken != null ? baseToken + " " + overlayToken : overlayToken);
  12209. }
  12210. };
  12211. };
  12212. });
  12213. /***/ }),
  12214. /* 13 */
  12215. /***/ (function(module, exports, __webpack_require__) {
  12216. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  12217. // Distributed under an MIT license: http://codemirror.net/LICENSE
  12218. (function(mod) {
  12219. if (true) // CommonJS
  12220. mod(__webpack_require__(5));
  12221. else if (typeof define == "function" && define.amd) // AMD
  12222. define(["../../lib/codemirror"], mod);
  12223. else // Plain browser env
  12224. mod(CodeMirror);
  12225. })(function(CodeMirror) {
  12226. CodeMirror.defineOption("placeholder", "", function(cm, val, old) {
  12227. var prev = old && old != CodeMirror.Init;
  12228. if (val && !prev) {
  12229. cm.on("blur", onBlur);
  12230. cm.on("change", onChange);
  12231. cm.on("swapDoc", onChange);
  12232. onChange(cm);
  12233. } else if (!val && prev) {
  12234. cm.off("blur", onBlur);
  12235. cm.off("change", onChange);
  12236. cm.off("swapDoc", onChange);
  12237. clearPlaceholder(cm);
  12238. var wrapper = cm.getWrapperElement();
  12239. wrapper.className = wrapper.className.replace(" CodeMirror-empty", "");
  12240. }
  12241. if (val && !cm.hasFocus()) onBlur(cm);
  12242. });
  12243. function clearPlaceholder(cm) {
  12244. if (cm.state.placeholder) {
  12245. cm.state.placeholder.parentNode.removeChild(cm.state.placeholder);
  12246. cm.state.placeholder = null;
  12247. }
  12248. }
  12249. function setPlaceholder(cm) {
  12250. clearPlaceholder(cm);
  12251. var elt = cm.state.placeholder = document.createElement("pre");
  12252. elt.style.cssText = "height: 0; overflow: visible";
  12253. elt.className = "CodeMirror-placeholder";
  12254. var placeHolder = cm.getOption("placeholder")
  12255. if (typeof placeHolder == "string") placeHolder = document.createTextNode(placeHolder)
  12256. elt.appendChild(placeHolder)
  12257. cm.display.lineSpace.insertBefore(elt, cm.display.lineSpace.firstChild);
  12258. }
  12259. function onBlur(cm) {
  12260. if (isEmpty(cm)) setPlaceholder(cm);
  12261. }
  12262. function onChange(cm) {
  12263. var wrapper = cm.getWrapperElement(), empty = isEmpty(cm);
  12264. wrapper.className = wrapper.className.replace(" CodeMirror-empty", "") + (empty ? " CodeMirror-empty" : "");
  12265. if (empty) setPlaceholder(cm);
  12266. else clearPlaceholder(cm);
  12267. }
  12268. function isEmpty(cm) {
  12269. return (cm.lineCount() === 1) && (cm.getLine(0) === "");
  12270. }
  12271. });
  12272. /***/ }),
  12273. /* 14 */
  12274. /***/ (function(module, exports, __webpack_require__) {
  12275. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  12276. // Distributed under an MIT license: http://codemirror.net/LICENSE
  12277. // Because sometimes you need to mark the selected *text*.
  12278. //
  12279. // Adds an option 'styleSelectedText' which, when enabled, gives
  12280. // selected text the CSS class given as option value, or
  12281. // "CodeMirror-selectedtext" when the value is not a string.
  12282. (function(mod) {
  12283. if (true) // CommonJS
  12284. mod(__webpack_require__(5));
  12285. else if (typeof define == "function" && define.amd) // AMD
  12286. define(["../../lib/codemirror"], mod);
  12287. else // Plain browser env
  12288. mod(CodeMirror);
  12289. })(function(CodeMirror) {
  12290. "use strict";
  12291. CodeMirror.defineOption("styleSelectedText", false, function(cm, val, old) {
  12292. var prev = old && old != CodeMirror.Init;
  12293. if (val && !prev) {
  12294. cm.state.markedSelection = [];
  12295. cm.state.markedSelectionStyle = typeof val == "string" ? val : "CodeMirror-selectedtext";
  12296. reset(cm);
  12297. cm.on("cursorActivity", onCursorActivity);
  12298. cm.on("change", onChange);
  12299. } else if (!val && prev) {
  12300. cm.off("cursorActivity", onCursorActivity);
  12301. cm.off("change", onChange);
  12302. clear(cm);
  12303. cm.state.markedSelection = cm.state.markedSelectionStyle = null;
  12304. }
  12305. });
  12306. function onCursorActivity(cm) {
  12307. if (cm.state.markedSelection)
  12308. cm.operation(function() { update(cm); });
  12309. }
  12310. function onChange(cm) {
  12311. if (cm.state.markedSelection && cm.state.markedSelection.length)
  12312. cm.operation(function() { clear(cm); });
  12313. }
  12314. var CHUNK_SIZE = 8;
  12315. var Pos = CodeMirror.Pos;
  12316. var cmp = CodeMirror.cmpPos;
  12317. function coverRange(cm, from, to, addAt) {
  12318. if (cmp(from, to) == 0) return;
  12319. var array = cm.state.markedSelection;
  12320. var cls = cm.state.markedSelectionStyle;
  12321. for (var line = from.line;;) {
  12322. var start = line == from.line ? from : Pos(line, 0);
  12323. var endLine = line + CHUNK_SIZE, atEnd = endLine >= to.line;
  12324. var end = atEnd ? to : Pos(endLine, 0);
  12325. var mark = cm.markText(start, end, {className: cls});
  12326. if (addAt == null) array.push(mark);
  12327. else array.splice(addAt++, 0, mark);
  12328. if (atEnd) break;
  12329. line = endLine;
  12330. }
  12331. }
  12332. function clear(cm) {
  12333. var array = cm.state.markedSelection;
  12334. for (var i = 0; i < array.length; ++i) array[i].clear();
  12335. array.length = 0;
  12336. }
  12337. function reset(cm) {
  12338. clear(cm);
  12339. var ranges = cm.listSelections();
  12340. for (var i = 0; i < ranges.length; i++)
  12341. coverRange(cm, ranges[i].from(), ranges[i].to());
  12342. }
  12343. function update(cm) {
  12344. if (!cm.somethingSelected()) return clear(cm);
  12345. if (cm.listSelections().length > 1) return reset(cm);
  12346. var from = cm.getCursor("start"), to = cm.getCursor("end");
  12347. var array = cm.state.markedSelection;
  12348. if (!array.length) return coverRange(cm, from, to);
  12349. var coverStart = array[0].find(), coverEnd = array[array.length - 1].find();
  12350. if (!coverStart || !coverEnd || to.line - from.line <= CHUNK_SIZE ||
  12351. cmp(from, coverEnd.to) >= 0 || cmp(to, coverStart.from) <= 0)
  12352. return reset(cm);
  12353. while (cmp(from, coverStart.from) > 0) {
  12354. array.shift().clear();
  12355. coverStart = array[0].find();
  12356. }
  12357. if (cmp(from, coverStart.from) < 0) {
  12358. if (coverStart.to.line - from.line < CHUNK_SIZE) {
  12359. array.shift().clear();
  12360. coverRange(cm, from, coverStart.to, 0);
  12361. } else {
  12362. coverRange(cm, from, coverStart.from, 0);
  12363. }
  12364. }
  12365. while (cmp(to, coverEnd.to) < 0) {
  12366. array.pop().clear();
  12367. coverEnd = array[array.length - 1].find();
  12368. }
  12369. if (cmp(to, coverEnd.to) > 0) {
  12370. if (to.line - coverEnd.from.line < CHUNK_SIZE) {
  12371. array.pop().clear();
  12372. coverRange(cm, coverEnd.from, to);
  12373. } else {
  12374. coverRange(cm, coverEnd.to, to);
  12375. }
  12376. }
  12377. }
  12378. });
  12379. /***/ }),
  12380. /* 15 */
  12381. /***/ (function(module, exports, __webpack_require__) {
  12382. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  12383. // Distributed under an MIT license: http://codemirror.net/LICENSE
  12384. (function(mod) {
  12385. if (true) // CommonJS
  12386. mod(__webpack_require__(5), __webpack_require__(9), __webpack_require__(12));
  12387. else if (typeof define == "function" && define.amd) // AMD
  12388. define(["../../lib/codemirror", "../markdown/markdown", "../../addon/mode/overlay"], mod);
  12389. else // Plain browser env
  12390. mod(CodeMirror);
  12391. })(function(CodeMirror) {
  12392. "use strict";
  12393. var urlRE = /^((?:(?:aaas?|about|acap|adiumxtra|af[ps]|aim|apt|attachment|aw|beshare|bitcoin|bolo|callto|cap|chrome(?:-extension)?|cid|coap|com-eventbrite-attendee|content|crid|cvs|data|dav|dict|dlna-(?:playcontainer|playsingle)|dns|doi|dtn|dvb|ed2k|facetime|feed|file|finger|fish|ftp|geo|gg|git|gizmoproject|go|gopher|gtalk|h323|hcp|https?|iax|icap|icon|im|imap|info|ipn|ipp|irc[6s]?|iris(?:\.beep|\.lwz|\.xpc|\.xpcs)?|itms|jar|javascript|jms|keyparc|lastfm|ldaps?|magnet|mailto|maps|market|message|mid|mms|ms-help|msnim|msrps?|mtqp|mumble|mupdate|mvn|news|nfs|nih?|nntp|notes|oid|opaquelocktoken|palm|paparazzi|platform|pop|pres|proxy|psyc|query|res(?:ource)?|rmi|rsync|rtmp|rtsp|secondlife|service|session|sftp|sgn|shttp|sieve|sips?|skype|sm[bs]|snmp|soap\.beeps?|soldat|spotify|ssh|steam|svn|tag|teamspeak|tel(?:net)?|tftp|things|thismessage|tip|tn3270|tv|udp|unreal|urn|ut2004|vemmi|ventrilo|view-source|webcal|wss?|wtai|wyciwyg|xcon(?:-userid)?|xfire|xmlrpc\.beeps?|xmpp|xri|ymsgr|z39\.50[rs]?):(?:\/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]|\([^\s()<>]*\))+(?:\([^\s()<>]*\)|[^\s`*!()\[\]{};:'".,<>?«»“”‘’]))/i
  12394. CodeMirror.defineMode("gfm", function(config, modeConfig) {
  12395. var codeDepth = 0;
  12396. function blankLine(state) {
  12397. state.code = false;
  12398. return null;
  12399. }
  12400. var gfmOverlay = {
  12401. startState: function() {
  12402. return {
  12403. code: false,
  12404. codeBlock: false,
  12405. ateSpace: false
  12406. };
  12407. },
  12408. copyState: function(s) {
  12409. return {
  12410. code: s.code,
  12411. codeBlock: s.codeBlock,
  12412. ateSpace: s.ateSpace
  12413. };
  12414. },
  12415. token: function(stream, state) {
  12416. state.combineTokens = null;
  12417. // Hack to prevent formatting override inside code blocks (block and inline)
  12418. if (state.codeBlock) {
  12419. if (stream.match(/^```+/)) {
  12420. state.codeBlock = false;
  12421. return null;
  12422. }
  12423. stream.skipToEnd();
  12424. return null;
  12425. }
  12426. if (stream.sol()) {
  12427. state.code = false;
  12428. }
  12429. if (stream.sol() && stream.match(/^```+/)) {
  12430. stream.skipToEnd();
  12431. state.codeBlock = true;
  12432. return null;
  12433. }
  12434. // If this block is changed, it may need to be updated in Markdown mode
  12435. if (stream.peek() === '`') {
  12436. stream.next();
  12437. var before = stream.pos;
  12438. stream.eatWhile('`');
  12439. var difference = 1 + stream.pos - before;
  12440. if (!state.code) {
  12441. codeDepth = difference;
  12442. state.code = true;
  12443. } else {
  12444. if (difference === codeDepth) { // Must be exact
  12445. state.code = false;
  12446. }
  12447. }
  12448. return null;
  12449. } else if (state.code) {
  12450. stream.next();
  12451. return null;
  12452. }
  12453. // Check if space. If so, links can be formatted later on
  12454. if (stream.eatSpace()) {
  12455. state.ateSpace = true;
  12456. return null;
  12457. }
  12458. if (stream.sol() || state.ateSpace) {
  12459. state.ateSpace = false;
  12460. if (modeConfig.gitHubSpice !== false) {
  12461. if(stream.match(/^(?:[a-zA-Z0-9\-_]+\/)?(?:[a-zA-Z0-9\-_]+@)?(?=.{0,6}\d)(?:[a-f0-9]{7,40}\b)/)) {
  12462. // User/Project@SHA
  12463. // User@SHA
  12464. // SHA
  12465. state.combineTokens = true;
  12466. return "link";
  12467. } else if (stream.match(/^(?:[a-zA-Z0-9\-_]+\/)?(?:[a-zA-Z0-9\-_]+)?#[0-9]+\b/)) {
  12468. // User/Project#Num
  12469. // User#Num
  12470. // #Num
  12471. state.combineTokens = true;
  12472. return "link";
  12473. }
  12474. }
  12475. }
  12476. if (stream.match(urlRE) &&
  12477. stream.string.slice(stream.start - 2, stream.start) != "](" &&
  12478. (stream.start == 0 || /\W/.test(stream.string.charAt(stream.start - 1)))) {
  12479. // URLs
  12480. // Taken from http://daringfireball.net/2010/07/improved_regex_for_matching_urls
  12481. // And then (issue #1160) simplified to make it not crash the Chrome Regexp engine
  12482. // And then limited url schemes to the CommonMark list, so foo:bar isn't matched as a URL
  12483. state.combineTokens = true;
  12484. return "link";
  12485. }
  12486. stream.next();
  12487. return null;
  12488. },
  12489. blankLine: blankLine
  12490. };
  12491. var markdownConfig = {
  12492. taskLists: true,
  12493. strikethrough: true,
  12494. emoji: true
  12495. };
  12496. for (var attr in modeConfig) {
  12497. markdownConfig[attr] = modeConfig[attr];
  12498. }
  12499. markdownConfig.name = "markdown";
  12500. return CodeMirror.overlayMode(CodeMirror.getMode(config, markdownConfig), gfmOverlay);
  12501. }, "markdown");
  12502. CodeMirror.defineMIME("text/x-gfm", "gfm");
  12503. });
  12504. /***/ }),
  12505. /* 16 */
  12506. /***/ (function(module, exports, __webpack_require__) {
  12507. // Use strict mode (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode)
  12508. "use strict";
  12509. // Requires
  12510. var Typo = __webpack_require__(17);
  12511. // Create function
  12512. function CodeMirrorSpellChecker(options) {
  12513. // Initialize
  12514. options = options || {};
  12515. // Verify
  12516. if(typeof options.codeMirrorInstance !== "function" || typeof options.codeMirrorInstance.defineMode !== "function") {
  12517. console.log("CodeMirror Spell Checker: You must provide an instance of CodeMirror via the option `codeMirrorInstance`");
  12518. return;
  12519. }
  12520. // Because some browsers don't support this functionality yet
  12521. if(!String.prototype.includes) {
  12522. String.prototype.includes = function() {
  12523. "use strict";
  12524. return String.prototype.indexOf.apply(this, arguments) !== -1;
  12525. };
  12526. }
  12527. // Define the new mode
  12528. options.codeMirrorInstance.defineMode("spell-checker", function(config) {
  12529. // Load AFF/DIC data
  12530. if(!CodeMirrorSpellChecker.aff_loading) {
  12531. CodeMirrorSpellChecker.aff_loading = true;
  12532. var xhr_aff = new XMLHttpRequest();
  12533. xhr_aff.open("GET", "https://cdn.jsdelivr.net/codemirror.spell-checker/latest/en_US.aff", true);
  12534. xhr_aff.onload = function() {
  12535. if(xhr_aff.readyState === 4 && xhr_aff.status === 200) {
  12536. CodeMirrorSpellChecker.aff_data = xhr_aff.responseText;
  12537. CodeMirrorSpellChecker.num_loaded++;
  12538. if(CodeMirrorSpellChecker.num_loaded == 2) {
  12539. CodeMirrorSpellChecker.typo = new Typo("en_US", CodeMirrorSpellChecker.aff_data, CodeMirrorSpellChecker.dic_data, {
  12540. platform: "any"
  12541. });
  12542. }
  12543. }
  12544. };
  12545. xhr_aff.send(null);
  12546. }
  12547. if(!CodeMirrorSpellChecker.dic_loading) {
  12548. CodeMirrorSpellChecker.dic_loading = true;
  12549. var xhr_dic = new XMLHttpRequest();
  12550. xhr_dic.open("GET", "https://cdn.jsdelivr.net/codemirror.spell-checker/latest/en_US.dic", true);
  12551. xhr_dic.onload = function() {
  12552. if(xhr_dic.readyState === 4 && xhr_dic.status === 200) {
  12553. CodeMirrorSpellChecker.dic_data = xhr_dic.responseText;
  12554. CodeMirrorSpellChecker.num_loaded++;
  12555. if(CodeMirrorSpellChecker.num_loaded == 2) {
  12556. CodeMirrorSpellChecker.typo = new Typo("en_US", CodeMirrorSpellChecker.aff_data, CodeMirrorSpellChecker.dic_data, {
  12557. platform: "any"
  12558. });
  12559. }
  12560. }
  12561. };
  12562. xhr_dic.send(null);
  12563. }
  12564. // Define what separates a word
  12565. var rx_word = "!\"#$%&()*+,-./:;<=>?@[\\]^_`{|}~ ";
  12566. // Create the overlay and such
  12567. var overlay = {
  12568. token: function(stream) {
  12569. var ch = stream.peek();
  12570. var word = "";
  12571. if(rx_word.includes(ch)) {
  12572. stream.next();
  12573. return null;
  12574. }
  12575. while((ch = stream.peek()) != null && !rx_word.includes(ch)) {
  12576. word += ch;
  12577. stream.next();
  12578. }
  12579. if(CodeMirrorSpellChecker.typo && !CodeMirrorSpellChecker.typo.check(word))
  12580. return "spell-error"; // CSS class: cm-spell-error
  12581. return null;
  12582. }
  12583. };
  12584. var mode = options.codeMirrorInstance.getMode(
  12585. config, config.backdrop || "text/plain"
  12586. );
  12587. return options.codeMirrorInstance.overlayMode(mode, overlay, true);
  12588. });
  12589. }
  12590. // Initialize data globally to reduce memory consumption
  12591. CodeMirrorSpellChecker.num_loaded = 0;
  12592. CodeMirrorSpellChecker.aff_loading = false;
  12593. CodeMirrorSpellChecker.dic_loading = false;
  12594. CodeMirrorSpellChecker.aff_data = "";
  12595. CodeMirrorSpellChecker.dic_data = "";
  12596. CodeMirrorSpellChecker.typo;
  12597. // Export
  12598. module.exports = CodeMirrorSpellChecker;
  12599. /***/ }),
  12600. /* 17 */
  12601. /***/ (function(module, exports, __webpack_require__) {
  12602. /* WEBPACK VAR INJECTION */(function(__dirname, Buffer) {/* globals chrome: false */
  12603. /* globals __dirname: false */
  12604. /* globals require: false */
  12605. /* globals Buffer: false */
  12606. /* globals module: false */
  12607. /**
  12608. * Typo is a JavaScript implementation of a spellchecker using hunspell-style
  12609. * dictionaries.
  12610. */
  12611. var Typo;
  12612. (function () {
  12613. "use strict";
  12614. /**
  12615. * Typo constructor.
  12616. *
  12617. * @param {String} [dictionary] The locale code of the dictionary being used. e.g.,
  12618. * "en_US". This is only used to auto-load dictionaries.
  12619. * @param {String} [affData] The data from the dictionary's .aff file. If omitted
  12620. * and Typo.js is being used in a Chrome extension, the .aff
  12621. * file will be loaded automatically from
  12622. * lib/typo/dictionaries/[dictionary]/[dictionary].aff
  12623. * In other environments, it will be loaded from
  12624. * [settings.dictionaryPath]/dictionaries/[dictionary]/[dictionary].aff
  12625. * @param {String} [wordsData] The data from the dictionary's .dic file. If omitted
  12626. * and Typo.js is being used in a Chrome extension, the .dic
  12627. * file will be loaded automatically from
  12628. * lib/typo/dictionaries/[dictionary]/[dictionary].dic
  12629. * In other environments, it will be loaded from
  12630. * [settings.dictionaryPath]/dictionaries/[dictionary]/[dictionary].dic
  12631. * @param {Object} [settings] Constructor settings. Available properties are:
  12632. * {String} [dictionaryPath]: path to load dictionary from in non-chrome
  12633. * environment.
  12634. * {Object} [flags]: flag information.
  12635. * {Boolean} [asyncLoad]: If true, affData and wordsData will be loaded
  12636. * asynchronously.
  12637. * {Function} [loadedCallback]: Called when both affData and wordsData
  12638. * have been loaded. Only used if asyncLoad is set to true. The parameter
  12639. * is the instantiated Typo object.
  12640. *
  12641. * @returns {Typo} A Typo object.
  12642. */
  12643. Typo = function (dictionary, affData, wordsData, settings) {
  12644. settings = settings || {};
  12645. this.dictionary = null;
  12646. this.rules = {};
  12647. this.dictionaryTable = {};
  12648. this.compoundRules = [];
  12649. this.compoundRuleCodes = {};
  12650. this.replacementTable = [];
  12651. this.flags = settings.flags || {};
  12652. this.memoized = {};
  12653. this.loaded = false;
  12654. var self = this;
  12655. var path;
  12656. // Loop-control variables.
  12657. var i, j, _len, _jlen;
  12658. if (dictionary) {
  12659. self.dictionary = dictionary;
  12660. // If the data is preloaded, just setup the Typo object.
  12661. if (affData && wordsData) {
  12662. setup();
  12663. }
  12664. // Loading data for Chrome extentions.
  12665. else if (typeof window !== 'undefined' && 'chrome' in window && 'extension' in window.chrome && 'getURL' in window.chrome.extension) {
  12666. if (settings.dictionaryPath) {
  12667. path = settings.dictionaryPath;
  12668. }
  12669. else {
  12670. path = "typo/dictionaries";
  12671. }
  12672. if (!affData) readDataFile(chrome.extension.getURL(path + "/" + dictionary + "/" + dictionary + ".aff"), setAffData);
  12673. if (!wordsData) readDataFile(chrome.extension.getURL(path + "/" + dictionary + "/" + dictionary + ".dic"), setWordsData);
  12674. }
  12675. else {
  12676. if (settings.dictionaryPath) {
  12677. path = settings.dictionaryPath;
  12678. }
  12679. else if (true) {
  12680. path = __dirname + '/dictionaries';
  12681. }
  12682. else {
  12683. path = './dictionaries';
  12684. }
  12685. if (!affData) readDataFile(path + "/" + dictionary + "/" + dictionary + ".aff", setAffData);
  12686. if (!wordsData) readDataFile(path + "/" + dictionary + "/" + dictionary + ".dic", setWordsData);
  12687. }
  12688. }
  12689. function readDataFile(url, setFunc) {
  12690. var response = self._readFile(url, null, settings.asyncLoad);
  12691. if (settings.asyncLoad) {
  12692. response.then(function(data) {
  12693. setFunc(data);
  12694. });
  12695. }
  12696. else {
  12697. setFunc(response);
  12698. }
  12699. }
  12700. function setAffData(data) {
  12701. affData = data;
  12702. if (wordsData) {
  12703. setup();
  12704. }
  12705. }
  12706. function setWordsData(data) {
  12707. wordsData = data;
  12708. if (affData) {
  12709. setup();
  12710. }
  12711. }
  12712. function setup() {
  12713. self.rules = self._parseAFF(affData);
  12714. // Save the rule codes that are used in compound rules.
  12715. self.compoundRuleCodes = {};
  12716. for (i = 0, _len = self.compoundRules.length; i < _len; i++) {
  12717. var rule = self.compoundRules[i];
  12718. for (j = 0, _jlen = rule.length; j < _jlen; j++) {
  12719. self.compoundRuleCodes[rule[j]] = [];
  12720. }
  12721. }
  12722. // If we add this ONLYINCOMPOUND flag to self.compoundRuleCodes, then _parseDIC
  12723. // will do the work of saving the list of words that are compound-only.
  12724. if ("ONLYINCOMPOUND" in self.flags) {
  12725. self.compoundRuleCodes[self.flags.ONLYINCOMPOUND] = [];
  12726. }
  12727. self.dictionaryTable = self._parseDIC(wordsData);
  12728. // Get rid of any codes from the compound rule codes that are never used
  12729. // (or that were special regex characters). Not especially necessary...
  12730. for (i in self.compoundRuleCodes) {
  12731. if (self.compoundRuleCodes[i].length === 0) {
  12732. delete self.compoundRuleCodes[i];
  12733. }
  12734. }
  12735. // Build the full regular expressions for each compound rule.
  12736. // I have a feeling (but no confirmation yet) that this method of
  12737. // testing for compound words is probably slow.
  12738. for (i = 0, _len = self.compoundRules.length; i < _len; i++) {
  12739. var ruleText = self.compoundRules[i];
  12740. var expressionText = "";
  12741. for (j = 0, _jlen = ruleText.length; j < _jlen; j++) {
  12742. var character = ruleText[j];
  12743. if (character in self.compoundRuleCodes) {
  12744. expressionText += "(" + self.compoundRuleCodes[character].join("|") + ")";
  12745. }
  12746. else {
  12747. expressionText += character;
  12748. }
  12749. }
  12750. self.compoundRules[i] = new RegExp(expressionText, "i");
  12751. }
  12752. self.loaded = true;
  12753. if (settings.asyncLoad && settings.loadedCallback) {
  12754. settings.loadedCallback(self);
  12755. }
  12756. }
  12757. return this;
  12758. };
  12759. Typo.prototype = {
  12760. /**
  12761. * Loads a Typo instance from a hash of all of the Typo properties.
  12762. *
  12763. * @param object obj A hash of Typo properties, probably gotten from a JSON.parse(JSON.stringify(typo_instance)).
  12764. */
  12765. load : function (obj) {
  12766. for (var i in obj) {
  12767. if (obj.hasOwnProperty(i)) {
  12768. this[i] = obj[i];
  12769. }
  12770. }
  12771. return this;
  12772. },
  12773. /**
  12774. * Read the contents of a file.
  12775. *
  12776. * @param {String} path The path (relative) to the file.
  12777. * @param {String} [charset="ISO8859-1"] The expected charset of the file
  12778. * @param {Boolean} async If true, the file will be read asynchronously. For node.js this does nothing, all
  12779. * files are read synchronously.
  12780. * @returns {String} The file data if async is false, otherwise a promise object. If running node.js, the data is
  12781. * always returned.
  12782. */
  12783. _readFile : function (path, charset, async) {
  12784. charset = charset || "utf8";
  12785. if (typeof XMLHttpRequest !== 'undefined') {
  12786. var promise;
  12787. var req = new XMLHttpRequest();
  12788. req.open("GET", path, async);
  12789. if (async) {
  12790. promise = new Promise(function(resolve, reject) {
  12791. req.onload = function() {
  12792. if (req.status === 200) {
  12793. resolve(req.responseText);
  12794. }
  12795. else {
  12796. reject(req.statusText);
  12797. }
  12798. };
  12799. req.onerror = function() {
  12800. reject(req.statusText);
  12801. }
  12802. });
  12803. }
  12804. if (req.overrideMimeType)
  12805. req.overrideMimeType("text/plain; charset=" + charset);
  12806. req.send(null);
  12807. return async ? promise : req.responseText;
  12808. }
  12809. else if (true) {
  12810. // Node.js
  12811. var fs = __webpack_require__(22);
  12812. try {
  12813. if (fs.existsSync(path)) {
  12814. var stats = fs.statSync(path);
  12815. var fileDescriptor = fs.openSync(path, 'r');
  12816. var buffer = new Buffer(stats.size);
  12817. fs.readSync(fileDescriptor, buffer, 0, buffer.length, null);
  12818. return buffer.toString(charset, 0, buffer.length);
  12819. }
  12820. else {
  12821. console.log("Path " + path + " does not exist.");
  12822. }
  12823. } catch (e) {
  12824. console.log(e);
  12825. return '';
  12826. }
  12827. }
  12828. },
  12829. /**
  12830. * Parse the rules out from a .aff file.
  12831. *
  12832. * @param {String} data The contents of the affix file.
  12833. * @returns object The rules from the file.
  12834. */
  12835. _parseAFF : function (data) {
  12836. var rules = {};
  12837. var line, subline, numEntries, lineParts;
  12838. var i, j, _len, _jlen;
  12839. // Remove comment lines
  12840. data = this._removeAffixComments(data);
  12841. var lines = data.split("\n");
  12842. for (i = 0, _len = lines.length; i < _len; i++) {
  12843. line = lines[i];
  12844. var definitionParts = line.split(/\s+/);
  12845. var ruleType = definitionParts[0];
  12846. if (ruleType == "PFX" || ruleType == "SFX") {
  12847. var ruleCode = definitionParts[1];
  12848. var combineable = definitionParts[2];
  12849. numEntries = parseInt(definitionParts[3], 10);
  12850. var entries = [];
  12851. for (j = i + 1, _jlen = i + 1 + numEntries; j < _jlen; j++) {
  12852. subline = lines[j];
  12853. lineParts = subline.split(/\s+/);
  12854. var charactersToRemove = lineParts[2];
  12855. var additionParts = lineParts[3].split("/");
  12856. var charactersToAdd = additionParts[0];
  12857. if (charactersToAdd === "0") charactersToAdd = "";
  12858. var continuationClasses = this.parseRuleCodes(additionParts[1]);
  12859. var regexToMatch = lineParts[4];
  12860. var entry = {};
  12861. entry.add = charactersToAdd;
  12862. if (continuationClasses.length > 0) entry.continuationClasses = continuationClasses;
  12863. if (regexToMatch !== ".") {
  12864. if (ruleType === "SFX") {
  12865. entry.match = new RegExp(regexToMatch + "$");
  12866. }
  12867. else {
  12868. entry.match = new RegExp("^" + regexToMatch);
  12869. }
  12870. }
  12871. if (charactersToRemove != "0") {
  12872. if (ruleType === "SFX") {
  12873. entry.remove = new RegExp(charactersToRemove + "$");
  12874. }
  12875. else {
  12876. entry.remove = charactersToRemove;
  12877. }
  12878. }
  12879. entries.push(entry);
  12880. }
  12881. rules[ruleCode] = { "type" : ruleType, "combineable" : (combineable == "Y"), "entries" : entries };
  12882. i += numEntries;
  12883. }
  12884. else if (ruleType === "COMPOUNDRULE") {
  12885. numEntries = parseInt(definitionParts[1], 10);
  12886. for (j = i + 1, _jlen = i + 1 + numEntries; j < _jlen; j++) {
  12887. line = lines[j];
  12888. lineParts = line.split(/\s+/);
  12889. this.compoundRules.push(lineParts[1]);
  12890. }
  12891. i += numEntries;
  12892. }
  12893. else if (ruleType === "REP") {
  12894. lineParts = line.split(/\s+/);
  12895. if (lineParts.length === 3) {
  12896. this.replacementTable.push([ lineParts[1], lineParts[2] ]);
  12897. }
  12898. }
  12899. else {
  12900. // ONLYINCOMPOUND
  12901. // COMPOUNDMIN
  12902. // FLAG
  12903. // KEEPCASE
  12904. // NEEDAFFIX
  12905. this.flags[ruleType] = definitionParts[1];
  12906. }
  12907. }
  12908. return rules;
  12909. },
  12910. /**
  12911. * Removes comment lines and then cleans up blank lines and trailing whitespace.
  12912. *
  12913. * @param {String} data The data from an affix file.
  12914. * @return {String} The cleaned-up data.
  12915. */
  12916. _removeAffixComments : function (data) {
  12917. // Remove comments
  12918. // This used to remove any string starting with '#' up to the end of the line,
  12919. // but some COMPOUNDRULE definitions include '#' as part of the rule.
  12920. // I haven't seen any affix files that use comments on the same line as real data,
  12921. // so I don't think this will break anything.
  12922. data = data.replace(/^\s*#.*$/mg, "");
  12923. // Trim each line
  12924. data = data.replace(/^\s\s*/m, '').replace(/\s\s*$/m, '');
  12925. // Remove blank lines.
  12926. data = data.replace(/\n{2,}/g, "\n");
  12927. // Trim the entire string
  12928. data = data.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
  12929. return data;
  12930. },
  12931. /**
  12932. * Parses the words out from the .dic file.
  12933. *
  12934. * @param {String} data The data from the dictionary file.
  12935. * @returns object The lookup table containing all of the words and
  12936. * word forms from the dictionary.
  12937. */
  12938. _parseDIC : function (data) {
  12939. data = this._removeDicComments(data);
  12940. var lines = data.split("\n");
  12941. var dictionaryTable = {};
  12942. function addWord(word, rules) {
  12943. // Some dictionaries will list the same word multiple times with different rule sets.
  12944. if (!dictionaryTable.hasOwnProperty(word)) {
  12945. dictionaryTable[word] = null;
  12946. }
  12947. if (rules.length > 0) {
  12948. if (dictionaryTable[word] === null) {
  12949. dictionaryTable[word] = [];
  12950. }
  12951. dictionaryTable[word].push(rules);
  12952. }
  12953. }
  12954. // The first line is the number of words in the dictionary.
  12955. for (var i = 1, _len = lines.length; i < _len; i++) {
  12956. var line = lines[i];
  12957. var parts = line.split("/", 2);
  12958. var word = parts[0];
  12959. // Now for each affix rule, generate that form of the word.
  12960. if (parts.length > 1) {
  12961. var ruleCodesArray = this.parseRuleCodes(parts[1]);
  12962. // Save the ruleCodes for compound word situations.
  12963. if (!("NEEDAFFIX" in this.flags) || ruleCodesArray.indexOf(this.flags.NEEDAFFIX) == -1) {
  12964. addWord(word, ruleCodesArray);
  12965. }
  12966. for (var j = 0, _jlen = ruleCodesArray.length; j < _jlen; j++) {
  12967. var code = ruleCodesArray[j];
  12968. var rule = this.rules[code];
  12969. if (rule) {
  12970. var newWords = this._applyRule(word, rule);
  12971. for (var ii = 0, _iilen = newWords.length; ii < _iilen; ii++) {
  12972. var newWord = newWords[ii];
  12973. addWord(newWord, []);
  12974. if (rule.combineable) {
  12975. for (var k = j + 1; k < _jlen; k++) {
  12976. var combineCode = ruleCodesArray[k];
  12977. var combineRule = this.rules[combineCode];
  12978. if (combineRule) {
  12979. if (combineRule.combineable && (rule.type != combineRule.type)) {
  12980. var otherNewWords = this._applyRule(newWord, combineRule);
  12981. for (var iii = 0, _iiilen = otherNewWords.length; iii < _iiilen; iii++) {
  12982. var otherNewWord = otherNewWords[iii];
  12983. addWord(otherNewWord, []);
  12984. }
  12985. }
  12986. }
  12987. }
  12988. }
  12989. }
  12990. }
  12991. if (code in this.compoundRuleCodes) {
  12992. this.compoundRuleCodes[code].push(word);
  12993. }
  12994. }
  12995. }
  12996. else {
  12997. addWord(word.trim(), []);
  12998. }
  12999. }
  13000. return dictionaryTable;
  13001. },
  13002. /**
  13003. * Removes comment lines and then cleans up blank lines and trailing whitespace.
  13004. *
  13005. * @param {String} data The data from a .dic file.
  13006. * @return {String} The cleaned-up data.
  13007. */
  13008. _removeDicComments : function (data) {
  13009. // I can't find any official documentation on it, but at least the de_DE
  13010. // dictionary uses tab-indented lines as comments.
  13011. // Remove comments
  13012. data = data.replace(/^\t.*$/mg, "");
  13013. return data;
  13014. },
  13015. parseRuleCodes : function (textCodes) {
  13016. if (!textCodes) {
  13017. return [];
  13018. }
  13019. else if (!("FLAG" in this.flags)) {
  13020. return textCodes.split("");
  13021. }
  13022. else if (this.flags.FLAG === "long") {
  13023. var flags = [];
  13024. for (var i = 0, _len = textCodes.length; i < _len; i += 2) {
  13025. flags.push(textCodes.substr(i, 2));
  13026. }
  13027. return flags;
  13028. }
  13029. else if (this.flags.FLAG === "num") {
  13030. return textCodes.split(",");
  13031. }
  13032. },
  13033. /**
  13034. * Applies an affix rule to a word.
  13035. *
  13036. * @param {String} word The base word.
  13037. * @param {Object} rule The affix rule.
  13038. * @returns {String[]} The new words generated by the rule.
  13039. */
  13040. _applyRule : function (word, rule) {
  13041. var entries = rule.entries;
  13042. var newWords = [];
  13043. for (var i = 0, _len = entries.length; i < _len; i++) {
  13044. var entry = entries[i];
  13045. if (!entry.match || word.match(entry.match)) {
  13046. var newWord = word;
  13047. if (entry.remove) {
  13048. newWord = newWord.replace(entry.remove, "");
  13049. }
  13050. if (rule.type === "SFX") {
  13051. newWord = newWord + entry.add;
  13052. }
  13053. else {
  13054. newWord = entry.add + newWord;
  13055. }
  13056. newWords.push(newWord);
  13057. if ("continuationClasses" in entry) {
  13058. for (var j = 0, _jlen = entry.continuationClasses.length; j < _jlen; j++) {
  13059. var continuationRule = this.rules[entry.continuationClasses[j]];
  13060. if (continuationRule) {
  13061. newWords = newWords.concat(this._applyRule(newWord, continuationRule));
  13062. }
  13063. /*
  13064. else {
  13065. // This shouldn't happen, but it does, at least in the de_DE dictionary.
  13066. // I think the author mistakenly supplied lower-case rule codes instead
  13067. // of upper-case.
  13068. }
  13069. */
  13070. }
  13071. }
  13072. }
  13073. }
  13074. return newWords;
  13075. },
  13076. /**
  13077. * Checks whether a word or a capitalization variant exists in the current dictionary.
  13078. * The word is trimmed and several variations of capitalizations are checked.
  13079. * If you want to check a word without any changes made to it, call checkExact()
  13080. *
  13081. * @see http://blog.stevenlevithan.com/archives/faster-trim-javascript re:trimming function
  13082. *
  13083. * @param {String} aWord The word to check.
  13084. * @returns {Boolean}
  13085. */
  13086. check : function (aWord) {
  13087. if (!this.loaded) {
  13088. throw "Dictionary not loaded.";
  13089. }
  13090. // Remove leading and trailing whitespace
  13091. var trimmedWord = aWord.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
  13092. if (this.checkExact(trimmedWord)) {
  13093. return true;
  13094. }
  13095. // The exact word is not in the dictionary.
  13096. if (trimmedWord.toUpperCase() === trimmedWord) {
  13097. // The word was supplied in all uppercase.
  13098. // Check for a capitalized form of the word.
  13099. var capitalizedWord = trimmedWord[0] + trimmedWord.substring(1).toLowerCase();
  13100. if (this.hasFlag(capitalizedWord, "KEEPCASE")) {
  13101. // Capitalization variants are not allowed for this word.
  13102. return false;
  13103. }
  13104. if (this.checkExact(capitalizedWord)) {
  13105. return true;
  13106. }
  13107. }
  13108. var lowercaseWord = trimmedWord.toLowerCase();
  13109. if (lowercaseWord !== trimmedWord) {
  13110. if (this.hasFlag(lowercaseWord, "KEEPCASE")) {
  13111. // Capitalization variants are not allowed for this word.
  13112. return false;
  13113. }
  13114. // Check for a lowercase form
  13115. if (this.checkExact(lowercaseWord)) {
  13116. return true;
  13117. }
  13118. }
  13119. return false;
  13120. },
  13121. /**
  13122. * Checks whether a word exists in the current dictionary.
  13123. *
  13124. * @param {String} word The word to check.
  13125. * @returns {Boolean}
  13126. */
  13127. checkExact : function (word) {
  13128. if (!this.loaded) {
  13129. throw "Dictionary not loaded.";
  13130. }
  13131. var ruleCodes = this.dictionaryTable[word];
  13132. var i, _len;
  13133. if (typeof ruleCodes === 'undefined') {
  13134. // Check if this might be a compound word.
  13135. if ("COMPOUNDMIN" in this.flags && word.length >= this.flags.COMPOUNDMIN) {
  13136. for (i = 0, _len = this.compoundRules.length; i < _len; i++) {
  13137. if (word.match(this.compoundRules[i])) {
  13138. return true;
  13139. }
  13140. }
  13141. }
  13142. }
  13143. else if (ruleCodes === null) {
  13144. // a null (but not undefined) value for an entry in the dictionary table
  13145. // means that the word is in the dictionary but has no flags.
  13146. return true;
  13147. }
  13148. else if (typeof ruleCodes === 'object') { // this.dictionary['hasOwnProperty'] will be a function.
  13149. for (i = 0, _len = ruleCodes.length; i < _len; i++) {
  13150. if (!this.hasFlag(word, "ONLYINCOMPOUND", ruleCodes[i])) {
  13151. return true;
  13152. }
  13153. }
  13154. }
  13155. return false;
  13156. },
  13157. /**
  13158. * Looks up whether a given word is flagged with a given flag.
  13159. *
  13160. * @param {String} word The word in question.
  13161. * @param {String} flag The flag in question.
  13162. * @return {Boolean}
  13163. */
  13164. hasFlag : function (word, flag, wordFlags) {
  13165. if (!this.loaded) {
  13166. throw "Dictionary not loaded.";
  13167. }
  13168. if (flag in this.flags) {
  13169. if (typeof wordFlags === 'undefined') {
  13170. wordFlags = Array.prototype.concat.apply([], this.dictionaryTable[word]);
  13171. }
  13172. if (wordFlags && wordFlags.indexOf(this.flags[flag]) !== -1) {
  13173. return true;
  13174. }
  13175. }
  13176. return false;
  13177. },
  13178. /**
  13179. * Returns a list of suggestions for a misspelled word.
  13180. *
  13181. * @see http://www.norvig.com/spell-correct.html for the basis of this suggestor.
  13182. * This suggestor is primitive, but it works.
  13183. *
  13184. * @param {String} word The misspelling.
  13185. * @param {Number} [limit=5] The maximum number of suggestions to return.
  13186. * @returns {String[]} The array of suggestions.
  13187. */
  13188. alphabet : "",
  13189. suggest : function (word, limit) {
  13190. if (!this.loaded) {
  13191. throw "Dictionary not loaded.";
  13192. }
  13193. limit = limit || 5;
  13194. if (this.memoized.hasOwnProperty(word)) {
  13195. var memoizedLimit = this.memoized[word]['limit'];
  13196. // Only return the cached list if it's big enough or if there weren't enough suggestions
  13197. // to fill a smaller limit.
  13198. if (limit <= memoizedLimit || this.memoized[word]['suggestions'].length < memoizedLimit) {
  13199. return this.memoized[word]['suggestions'].slice(0, limit);
  13200. }
  13201. }
  13202. if (this.check(word)) return [];
  13203. // Check the replacement table.
  13204. for (var i = 0, _len = this.replacementTable.length; i < _len; i++) {
  13205. var replacementEntry = this.replacementTable[i];
  13206. if (word.indexOf(replacementEntry[0]) !== -1) {
  13207. var correctedWord = word.replace(replacementEntry[0], replacementEntry[1]);
  13208. if (this.check(correctedWord)) {
  13209. return [ correctedWord ];
  13210. }
  13211. }
  13212. }
  13213. var self = this;
  13214. self.alphabet = "abcdefghijklmnopqrstuvwxyz";
  13215. /*
  13216. if (!self.alphabet) {
  13217. // Use the alphabet as implicitly defined by the words in the dictionary.
  13218. var alphaHash = {};
  13219. for (var i in self.dictionaryTable) {
  13220. for (var j = 0, _len = i.length; j < _len; j++) {
  13221. alphaHash[i[j]] = true;
  13222. }
  13223. }
  13224. for (var i in alphaHash) {
  13225. self.alphabet += i;
  13226. }
  13227. var alphaArray = self.alphabet.split("");
  13228. alphaArray.sort();
  13229. self.alphabet = alphaArray.join("");
  13230. }
  13231. */
  13232. function edits1(words) {
  13233. var rv = [];
  13234. var ii, i, j, _iilen, _len, _jlen;
  13235. for (ii = 0, _iilen = words.length; ii < _iilen; ii++) {
  13236. var word = words[ii];
  13237. for (i = 0, _len = word.length + 1; i < _len; i++) {
  13238. var s = [ word.substring(0, i), word.substring(i) ];
  13239. if (s[1]) {
  13240. rv.push(s[0] + s[1].substring(1));
  13241. }
  13242. // Eliminate transpositions of identical letters
  13243. if (s[1].length > 1 && s[1][1] !== s[1][0]) {
  13244. rv.push(s[0] + s[1][1] + s[1][0] + s[1].substring(2));
  13245. }
  13246. if (s[1]) {
  13247. for (j = 0, _jlen = self.alphabet.length; j < _jlen; j++) {
  13248. // Eliminate replacement of a letter by itself
  13249. if (self.alphabet[j] != s[1].substring(0,1)){
  13250. rv.push(s[0] + self.alphabet[j] + s[1].substring(1));
  13251. }
  13252. }
  13253. }
  13254. if (s[1]) {
  13255. for (j = 0, _jlen = self.alphabet.length; j < _jlen; j++) {
  13256. rv.push(s[0] + self.alphabet[j] + s[1]);
  13257. }
  13258. }
  13259. }
  13260. }
  13261. return rv;
  13262. }
  13263. function known(words) {
  13264. var rv = [];
  13265. for (var i = 0, _len = words.length; i < _len; i++) {
  13266. if (self.check(words[i])) {
  13267. rv.push(words[i]);
  13268. }
  13269. }
  13270. return rv;
  13271. }
  13272. function correct(word) {
  13273. // Get the edit-distance-1 and edit-distance-2 forms of this word.
  13274. var ed1 = edits1([word]);
  13275. var ed2 = edits1(ed1);
  13276. var corrections = known(ed1.concat(ed2));
  13277. var i, _len;
  13278. // Sort the edits based on how many different ways they were created.
  13279. var weighted_corrections = {};
  13280. for (i = 0, _len = corrections.length; i < _len; i++) {
  13281. if (!(corrections[i] in weighted_corrections)) {
  13282. weighted_corrections[corrections[i]] = 1;
  13283. }
  13284. else {
  13285. weighted_corrections[corrections[i]] += 1;
  13286. }
  13287. }
  13288. var sorted_corrections = [];
  13289. for (i in weighted_corrections) {
  13290. if (weighted_corrections.hasOwnProperty(i)) {
  13291. sorted_corrections.push([ i, weighted_corrections[i] ]);
  13292. }
  13293. }
  13294. function sorter(a, b) {
  13295. if (a[1] < b[1]) {
  13296. return -1;
  13297. }
  13298. return 1;
  13299. }
  13300. sorted_corrections.sort(sorter).reverse();
  13301. var rv = [];
  13302. var capitalization_scheme = "lowercase";
  13303. if (word.toUpperCase() === word) {
  13304. capitalization_scheme = "uppercase";
  13305. }
  13306. else if (word.substr(0, 1).toUpperCase() + word.substr(1).toLowerCase() === word) {
  13307. capitalization_scheme = "capitalized";
  13308. }
  13309. for (i = 0, _len = Math.min(limit, sorted_corrections.length); i < _len; i++) {
  13310. if ("uppercase" === capitalization_scheme) {
  13311. sorted_corrections[i][0] = sorted_corrections[i][0].toUpperCase();
  13312. }
  13313. else if ("capitalized" === capitalization_scheme) {
  13314. sorted_corrections[i][0] = sorted_corrections[i][0].substr(0, 1).toUpperCase() + sorted_corrections[i][0].substr(1);
  13315. }
  13316. if (!self.hasFlag(sorted_corrections[i][0], "NOSUGGEST")) {
  13317. rv.push(sorted_corrections[i][0]);
  13318. }
  13319. }
  13320. return rv;
  13321. }
  13322. this.memoized[word] = {
  13323. 'suggestions': correct(word),
  13324. 'limit': limit
  13325. };
  13326. return this.memoized[word]['suggestions'];
  13327. }
  13328. };
  13329. })();
  13330. // Support for use as a node.js module.
  13331. if (true) {
  13332. module.exports = Typo;
  13333. }
  13334. /* WEBPACK VAR INJECTION */}.call(exports, "/", __webpack_require__(18).Buffer))
  13335. /***/ }),
  13336. /* 18 */
  13337. /***/ (function(module, exports, __webpack_require__) {
  13338. /* WEBPACK VAR INJECTION */(function(global) {/*!
  13339. * The buffer module from node.js, for the browser.
  13340. *
  13341. * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
  13342. * @license MIT
  13343. */
  13344. /* eslint-disable no-proto */
  13345. 'use strict'
  13346. var base64 = __webpack_require__(19)
  13347. var ieee754 = __webpack_require__(20)
  13348. var isArray = __webpack_require__(21)
  13349. exports.Buffer = Buffer
  13350. exports.SlowBuffer = SlowBuffer
  13351. exports.INSPECT_MAX_BYTES = 50
  13352. /**
  13353. * If `Buffer.TYPED_ARRAY_SUPPORT`:
  13354. * === true Use Uint8Array implementation (fastest)
  13355. * === false Use Object implementation (most compatible, even IE6)
  13356. *
  13357. * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
  13358. * Opera 11.6+, iOS 4.2+.
  13359. *
  13360. * Due to various browser bugs, sometimes the Object implementation will be used even
  13361. * when the browser supports typed arrays.
  13362. *
  13363. * Note:
  13364. *
  13365. * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,
  13366. * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
  13367. *
  13368. * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
  13369. *
  13370. * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
  13371. * incorrect length in some situations.
  13372. * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they
  13373. * get the Object implementation, which is slower but behaves correctly.
  13374. */
  13375. Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined
  13376. ? global.TYPED_ARRAY_SUPPORT
  13377. : typedArraySupport()
  13378. /*
  13379. * Export kMaxLength after typed array support is determined.
  13380. */
  13381. exports.kMaxLength = kMaxLength()
  13382. function typedArraySupport () {
  13383. try {
  13384. var arr = new Uint8Array(1)
  13385. arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }}
  13386. return arr.foo() === 42 && // typed array instances can be augmented
  13387. typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`
  13388. arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`
  13389. } catch (e) {
  13390. return false
  13391. }
  13392. }
  13393. function kMaxLength () {
  13394. return Buffer.TYPED_ARRAY_SUPPORT
  13395. ? 0x7fffffff
  13396. : 0x3fffffff
  13397. }
  13398. function createBuffer (that, length) {
  13399. if (kMaxLength() < length) {
  13400. throw new RangeError('Invalid typed array length')
  13401. }
  13402. if (Buffer.TYPED_ARRAY_SUPPORT) {
  13403. // Return an augmented `Uint8Array` instance, for best performance
  13404. that = new Uint8Array(length)
  13405. that.__proto__ = Buffer.prototype
  13406. } else {
  13407. // Fallback: Return an object instance of the Buffer class
  13408. if (that === null) {
  13409. that = new Buffer(length)
  13410. }
  13411. that.length = length
  13412. }
  13413. return that
  13414. }
  13415. /**
  13416. * The Buffer constructor returns instances of `Uint8Array` that have their
  13417. * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
  13418. * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
  13419. * and the `Uint8Array` methods. Square bracket notation works as expected -- it
  13420. * returns a single octet.
  13421. *
  13422. * The `Uint8Array` prototype remains unmodified.
  13423. */
  13424. function Buffer (arg, encodingOrOffset, length) {
  13425. if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) {
  13426. return new Buffer(arg, encodingOrOffset, length)
  13427. }
  13428. // Common case.
  13429. if (typeof arg === 'number') {
  13430. if (typeof encodingOrOffset === 'string') {
  13431. throw new Error(
  13432. 'If encoding is specified then the first argument must be a string'
  13433. )
  13434. }
  13435. return allocUnsafe(this, arg)
  13436. }
  13437. return from(this, arg, encodingOrOffset, length)
  13438. }
  13439. Buffer.poolSize = 8192 // not used by this implementation
  13440. // TODO: Legacy, not needed anymore. Remove in next major version.
  13441. Buffer._augment = function (arr) {
  13442. arr.__proto__ = Buffer.prototype
  13443. return arr
  13444. }
  13445. function from (that, value, encodingOrOffset, length) {
  13446. if (typeof value === 'number') {
  13447. throw new TypeError('"value" argument must not be a number')
  13448. }
  13449. if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {
  13450. return fromArrayBuffer(that, value, encodingOrOffset, length)
  13451. }
  13452. if (typeof value === 'string') {
  13453. return fromString(that, value, encodingOrOffset)
  13454. }
  13455. return fromObject(that, value)
  13456. }
  13457. /**
  13458. * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
  13459. * if value is a number.
  13460. * Buffer.from(str[, encoding])
  13461. * Buffer.from(array)
  13462. * Buffer.from(buffer)
  13463. * Buffer.from(arrayBuffer[, byteOffset[, length]])
  13464. **/
  13465. Buffer.from = function (value, encodingOrOffset, length) {
  13466. return from(null, value, encodingOrOffset, length)
  13467. }
  13468. if (Buffer.TYPED_ARRAY_SUPPORT) {
  13469. Buffer.prototype.__proto__ = Uint8Array.prototype
  13470. Buffer.__proto__ = Uint8Array
  13471. if (typeof Symbol !== 'undefined' && Symbol.species &&
  13472. Buffer[Symbol.species] === Buffer) {
  13473. // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
  13474. Object.defineProperty(Buffer, Symbol.species, {
  13475. value: null,
  13476. configurable: true
  13477. })
  13478. }
  13479. }
  13480. function assertSize (size) {
  13481. if (typeof size !== 'number') {
  13482. throw new TypeError('"size" argument must be a number')
  13483. } else if (size < 0) {
  13484. throw new RangeError('"size" argument must not be negative')
  13485. }
  13486. }
  13487. function alloc (that, size, fill, encoding) {
  13488. assertSize(size)
  13489. if (size <= 0) {
  13490. return createBuffer(that, size)
  13491. }
  13492. if (fill !== undefined) {
  13493. // Only pay attention to encoding if it's a string. This
  13494. // prevents accidentally sending in a number that would
  13495. // be interpretted as a start offset.
  13496. return typeof encoding === 'string'
  13497. ? createBuffer(that, size).fill(fill, encoding)
  13498. : createBuffer(that, size).fill(fill)
  13499. }
  13500. return createBuffer(that, size)
  13501. }
  13502. /**
  13503. * Creates a new filled Buffer instance.
  13504. * alloc(size[, fill[, encoding]])
  13505. **/
  13506. Buffer.alloc = function (size, fill, encoding) {
  13507. return alloc(null, size, fill, encoding)
  13508. }
  13509. function allocUnsafe (that, size) {
  13510. assertSize(size)
  13511. that = createBuffer(that, size < 0 ? 0 : checked(size) | 0)
  13512. if (!Buffer.TYPED_ARRAY_SUPPORT) {
  13513. for (var i = 0; i < size; ++i) {
  13514. that[i] = 0
  13515. }
  13516. }
  13517. return that
  13518. }
  13519. /**
  13520. * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
  13521. * */
  13522. Buffer.allocUnsafe = function (size) {
  13523. return allocUnsafe(null, size)
  13524. }
  13525. /**
  13526. * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
  13527. */
  13528. Buffer.allocUnsafeSlow = function (size) {
  13529. return allocUnsafe(null, size)
  13530. }
  13531. function fromString (that, string, encoding) {
  13532. if (typeof encoding !== 'string' || encoding === '') {
  13533. encoding = 'utf8'
  13534. }
  13535. if (!Buffer.isEncoding(encoding)) {
  13536. throw new TypeError('"encoding" must be a valid string encoding')
  13537. }
  13538. var length = byteLength(string, encoding) | 0
  13539. that = createBuffer(that, length)
  13540. var actual = that.write(string, encoding)
  13541. if (actual !== length) {
  13542. // Writing a hex string, for example, that contains invalid characters will
  13543. // cause everything after the first invalid character to be ignored. (e.g.
  13544. // 'abxxcd' will be treated as 'ab')
  13545. that = that.slice(0, actual)
  13546. }
  13547. return that
  13548. }
  13549. function fromArrayLike (that, array) {
  13550. var length = array.length < 0 ? 0 : checked(array.length) | 0
  13551. that = createBuffer(that, length)
  13552. for (var i = 0; i < length; i += 1) {
  13553. that[i] = array[i] & 255
  13554. }
  13555. return that
  13556. }
  13557. function fromArrayBuffer (that, array, byteOffset, length) {
  13558. array.byteLength // this throws if `array` is not a valid ArrayBuffer
  13559. if (byteOffset < 0 || array.byteLength < byteOffset) {
  13560. throw new RangeError('\'offset\' is out of bounds')
  13561. }
  13562. if (array.byteLength < byteOffset + (length || 0)) {
  13563. throw new RangeError('\'length\' is out of bounds')
  13564. }
  13565. if (byteOffset === undefined && length === undefined) {
  13566. array = new Uint8Array(array)
  13567. } else if (length === undefined) {
  13568. array = new Uint8Array(array, byteOffset)
  13569. } else {
  13570. array = new Uint8Array(array, byteOffset, length)
  13571. }
  13572. if (Buffer.TYPED_ARRAY_SUPPORT) {
  13573. // Return an augmented `Uint8Array` instance, for best performance
  13574. that = array
  13575. that.__proto__ = Buffer.prototype
  13576. } else {
  13577. // Fallback: Return an object instance of the Buffer class
  13578. that = fromArrayLike(that, array)
  13579. }
  13580. return that
  13581. }
  13582. function fromObject (that, obj) {
  13583. if (Buffer.isBuffer(obj)) {
  13584. var len = checked(obj.length) | 0
  13585. that = createBuffer(that, len)
  13586. if (that.length === 0) {
  13587. return that
  13588. }
  13589. obj.copy(that, 0, 0, len)
  13590. return that
  13591. }
  13592. if (obj) {
  13593. if ((typeof ArrayBuffer !== 'undefined' &&
  13594. obj.buffer instanceof ArrayBuffer) || 'length' in obj) {
  13595. if (typeof obj.length !== 'number' || isnan(obj.length)) {
  13596. return createBuffer(that, 0)
  13597. }
  13598. return fromArrayLike(that, obj)
  13599. }
  13600. if (obj.type === 'Buffer' && isArray(obj.data)) {
  13601. return fromArrayLike(that, obj.data)
  13602. }
  13603. }
  13604. throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')
  13605. }
  13606. function checked (length) {
  13607. // Note: cannot use `length < kMaxLength()` here because that fails when
  13608. // length is NaN (which is otherwise coerced to zero.)
  13609. if (length >= kMaxLength()) {
  13610. throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
  13611. 'size: 0x' + kMaxLength().toString(16) + ' bytes')
  13612. }
  13613. return length | 0
  13614. }
  13615. function SlowBuffer (length) {
  13616. if (+length != length) { // eslint-disable-line eqeqeq
  13617. length = 0
  13618. }
  13619. return Buffer.alloc(+length)
  13620. }
  13621. Buffer.isBuffer = function isBuffer (b) {
  13622. return !!(b != null && b._isBuffer)
  13623. }
  13624. Buffer.compare = function compare (a, b) {
  13625. if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
  13626. throw new TypeError('Arguments must be Buffers')
  13627. }
  13628. if (a === b) return 0
  13629. var x = a.length
  13630. var y = b.length
  13631. for (var i = 0, len = Math.min(x, y); i < len; ++i) {
  13632. if (a[i] !== b[i]) {
  13633. x = a[i]
  13634. y = b[i]
  13635. break
  13636. }
  13637. }
  13638. if (x < y) return -1
  13639. if (y < x) return 1
  13640. return 0
  13641. }
  13642. Buffer.isEncoding = function isEncoding (encoding) {
  13643. switch (String(encoding).toLowerCase()) {
  13644. case 'hex':
  13645. case 'utf8':
  13646. case 'utf-8':
  13647. case 'ascii':
  13648. case 'latin1':
  13649. case 'binary':
  13650. case 'base64':
  13651. case 'ucs2':
  13652. case 'ucs-2':
  13653. case 'utf16le':
  13654. case 'utf-16le':
  13655. return true
  13656. default:
  13657. return false
  13658. }
  13659. }
  13660. Buffer.concat = function concat (list, length) {
  13661. if (!isArray(list)) {
  13662. throw new TypeError('"list" argument must be an Array of Buffers')
  13663. }
  13664. if (list.length === 0) {
  13665. return Buffer.alloc(0)
  13666. }
  13667. var i
  13668. if (length === undefined) {
  13669. length = 0
  13670. for (i = 0; i < list.length; ++i) {
  13671. length += list[i].length
  13672. }
  13673. }
  13674. var buffer = Buffer.allocUnsafe(length)
  13675. var pos = 0
  13676. for (i = 0; i < list.length; ++i) {
  13677. var buf = list[i]
  13678. if (!Buffer.isBuffer(buf)) {
  13679. throw new TypeError('"list" argument must be an Array of Buffers')
  13680. }
  13681. buf.copy(buffer, pos)
  13682. pos += buf.length
  13683. }
  13684. return buffer
  13685. }
  13686. function byteLength (string, encoding) {
  13687. if (Buffer.isBuffer(string)) {
  13688. return string.length
  13689. }
  13690. if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' &&
  13691. (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) {
  13692. return string.byteLength
  13693. }
  13694. if (typeof string !== 'string') {
  13695. string = '' + string
  13696. }
  13697. var len = string.length
  13698. if (len === 0) return 0
  13699. // Use a for loop to avoid recursion
  13700. var loweredCase = false
  13701. for (;;) {
  13702. switch (encoding) {
  13703. case 'ascii':
  13704. case 'latin1':
  13705. case 'binary':
  13706. return len
  13707. case 'utf8':
  13708. case 'utf-8':
  13709. case undefined:
  13710. return utf8ToBytes(string).length
  13711. case 'ucs2':
  13712. case 'ucs-2':
  13713. case 'utf16le':
  13714. case 'utf-16le':
  13715. return len * 2
  13716. case 'hex':
  13717. return len >>> 1
  13718. case 'base64':
  13719. return base64ToBytes(string).length
  13720. default:
  13721. if (loweredCase) return utf8ToBytes(string).length // assume utf8
  13722. encoding = ('' + encoding).toLowerCase()
  13723. loweredCase = true
  13724. }
  13725. }
  13726. }
  13727. Buffer.byteLength = byteLength
  13728. function slowToString (encoding, start, end) {
  13729. var loweredCase = false
  13730. // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
  13731. // property of a typed array.
  13732. // This behaves neither like String nor Uint8Array in that we set start/end
  13733. // to their upper/lower bounds if the value passed is out of range.
  13734. // undefined is handled specially as per ECMA-262 6th Edition,
  13735. // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
  13736. if (start === undefined || start < 0) {
  13737. start = 0
  13738. }
  13739. // Return early if start > this.length. Done here to prevent potential uint32
  13740. // coercion fail below.
  13741. if (start > this.length) {
  13742. return ''
  13743. }
  13744. if (end === undefined || end > this.length) {
  13745. end = this.length
  13746. }
  13747. if (end <= 0) {
  13748. return ''
  13749. }
  13750. // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
  13751. end >>>= 0
  13752. start >>>= 0
  13753. if (end <= start) {
  13754. return ''
  13755. }
  13756. if (!encoding) encoding = 'utf8'
  13757. while (true) {
  13758. switch (encoding) {
  13759. case 'hex':
  13760. return hexSlice(this, start, end)
  13761. case 'utf8':
  13762. case 'utf-8':
  13763. return utf8Slice(this, start, end)
  13764. case 'ascii':
  13765. return asciiSlice(this, start, end)
  13766. case 'latin1':
  13767. case 'binary':
  13768. return latin1Slice(this, start, end)
  13769. case 'base64':
  13770. return base64Slice(this, start, end)
  13771. case 'ucs2':
  13772. case 'ucs-2':
  13773. case 'utf16le':
  13774. case 'utf-16le':
  13775. return utf16leSlice(this, start, end)
  13776. default:
  13777. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  13778. encoding = (encoding + '').toLowerCase()
  13779. loweredCase = true
  13780. }
  13781. }
  13782. }
  13783. // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect
  13784. // Buffer instances.
  13785. Buffer.prototype._isBuffer = true
  13786. function swap (b, n, m) {
  13787. var i = b[n]
  13788. b[n] = b[m]
  13789. b[m] = i
  13790. }
  13791. Buffer.prototype.swap16 = function swap16 () {
  13792. var len = this.length
  13793. if (len % 2 !== 0) {
  13794. throw new RangeError('Buffer size must be a multiple of 16-bits')
  13795. }
  13796. for (var i = 0; i < len; i += 2) {
  13797. swap(this, i, i + 1)
  13798. }
  13799. return this
  13800. }
  13801. Buffer.prototype.swap32 = function swap32 () {
  13802. var len = this.length
  13803. if (len % 4 !== 0) {
  13804. throw new RangeError('Buffer size must be a multiple of 32-bits')
  13805. }
  13806. for (var i = 0; i < len; i += 4) {
  13807. swap(this, i, i + 3)
  13808. swap(this, i + 1, i + 2)
  13809. }
  13810. return this
  13811. }
  13812. Buffer.prototype.swap64 = function swap64 () {
  13813. var len = this.length
  13814. if (len % 8 !== 0) {
  13815. throw new RangeError('Buffer size must be a multiple of 64-bits')
  13816. }
  13817. for (var i = 0; i < len; i += 8) {
  13818. swap(this, i, i + 7)
  13819. swap(this, i + 1, i + 6)
  13820. swap(this, i + 2, i + 5)
  13821. swap(this, i + 3, i + 4)
  13822. }
  13823. return this
  13824. }
  13825. Buffer.prototype.toString = function toString () {
  13826. var length = this.length | 0
  13827. if (length === 0) return ''
  13828. if (arguments.length === 0) return utf8Slice(this, 0, length)
  13829. return slowToString.apply(this, arguments)
  13830. }
  13831. Buffer.prototype.equals = function equals (b) {
  13832. if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
  13833. if (this === b) return true
  13834. return Buffer.compare(this, b) === 0
  13835. }
  13836. Buffer.prototype.inspect = function inspect () {
  13837. var str = ''
  13838. var max = exports.INSPECT_MAX_BYTES
  13839. if (this.length > 0) {
  13840. str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')
  13841. if (this.length > max) str += ' ... '
  13842. }
  13843. return '<Buffer ' + str + '>'
  13844. }
  13845. Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
  13846. if (!Buffer.isBuffer(target)) {
  13847. throw new TypeError('Argument must be a Buffer')
  13848. }
  13849. if (start === undefined) {
  13850. start = 0
  13851. }
  13852. if (end === undefined) {
  13853. end = target ? target.length : 0
  13854. }
  13855. if (thisStart === undefined) {
  13856. thisStart = 0
  13857. }
  13858. if (thisEnd === undefined) {
  13859. thisEnd = this.length
  13860. }
  13861. if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
  13862. throw new RangeError('out of range index')
  13863. }
  13864. if (thisStart >= thisEnd && start >= end) {
  13865. return 0
  13866. }
  13867. if (thisStart >= thisEnd) {
  13868. return -1
  13869. }
  13870. if (start >= end) {
  13871. return 1
  13872. }
  13873. start >>>= 0
  13874. end >>>= 0
  13875. thisStart >>>= 0
  13876. thisEnd >>>= 0
  13877. if (this === target) return 0
  13878. var x = thisEnd - thisStart
  13879. var y = end - start
  13880. var len = Math.min(x, y)
  13881. var thisCopy = this.slice(thisStart, thisEnd)
  13882. var targetCopy = target.slice(start, end)
  13883. for (var i = 0; i < len; ++i) {
  13884. if (thisCopy[i] !== targetCopy[i]) {
  13885. x = thisCopy[i]
  13886. y = targetCopy[i]
  13887. break
  13888. }
  13889. }
  13890. if (x < y) return -1
  13891. if (y < x) return 1
  13892. return 0
  13893. }
  13894. // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
  13895. // OR the last index of `val` in `buffer` at offset <= `byteOffset`.
  13896. //
  13897. // Arguments:
  13898. // - buffer - a Buffer to search
  13899. // - val - a string, Buffer, or number
  13900. // - byteOffset - an index into `buffer`; will be clamped to an int32
  13901. // - encoding - an optional encoding, relevant is val is a string
  13902. // - dir - true for indexOf, false for lastIndexOf
  13903. function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
  13904. // Empty buffer means no match
  13905. if (buffer.length === 0) return -1
  13906. // Normalize byteOffset
  13907. if (typeof byteOffset === 'string') {
  13908. encoding = byteOffset
  13909. byteOffset = 0
  13910. } else if (byteOffset > 0x7fffffff) {
  13911. byteOffset = 0x7fffffff
  13912. } else if (byteOffset < -0x80000000) {
  13913. byteOffset = -0x80000000
  13914. }
  13915. byteOffset = +byteOffset // Coerce to Number.
  13916. if (isNaN(byteOffset)) {
  13917. // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
  13918. byteOffset = dir ? 0 : (buffer.length - 1)
  13919. }
  13920. // Normalize byteOffset: negative offsets start from the end of the buffer
  13921. if (byteOffset < 0) byteOffset = buffer.length + byteOffset
  13922. if (byteOffset >= buffer.length) {
  13923. if (dir) return -1
  13924. else byteOffset = buffer.length - 1
  13925. } else if (byteOffset < 0) {
  13926. if (dir) byteOffset = 0
  13927. else return -1
  13928. }
  13929. // Normalize val
  13930. if (typeof val === 'string') {
  13931. val = Buffer.from(val, encoding)
  13932. }
  13933. // Finally, search either indexOf (if dir is true) or lastIndexOf
  13934. if (Buffer.isBuffer(val)) {
  13935. // Special case: looking for empty string/buffer always fails
  13936. if (val.length === 0) {
  13937. return -1
  13938. }
  13939. return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
  13940. } else if (typeof val === 'number') {
  13941. val = val & 0xFF // Search for a byte value [0-255]
  13942. if (Buffer.TYPED_ARRAY_SUPPORT &&
  13943. typeof Uint8Array.prototype.indexOf === 'function') {
  13944. if (dir) {
  13945. return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
  13946. } else {
  13947. return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
  13948. }
  13949. }
  13950. return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
  13951. }
  13952. throw new TypeError('val must be string, number or Buffer')
  13953. }
  13954. function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
  13955. var indexSize = 1
  13956. var arrLength = arr.length
  13957. var valLength = val.length
  13958. if (encoding !== undefined) {
  13959. encoding = String(encoding).toLowerCase()
  13960. if (encoding === 'ucs2' || encoding === 'ucs-2' ||
  13961. encoding === 'utf16le' || encoding === 'utf-16le') {
  13962. if (arr.length < 2 || val.length < 2) {
  13963. return -1
  13964. }
  13965. indexSize = 2
  13966. arrLength /= 2
  13967. valLength /= 2
  13968. byteOffset /= 2
  13969. }
  13970. }
  13971. function read (buf, i) {
  13972. if (indexSize === 1) {
  13973. return buf[i]
  13974. } else {
  13975. return buf.readUInt16BE(i * indexSize)
  13976. }
  13977. }
  13978. var i
  13979. if (dir) {
  13980. var foundIndex = -1
  13981. for (i = byteOffset; i < arrLength; i++) {
  13982. if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
  13983. if (foundIndex === -1) foundIndex = i
  13984. if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
  13985. } else {
  13986. if (foundIndex !== -1) i -= i - foundIndex
  13987. foundIndex = -1
  13988. }
  13989. }
  13990. } else {
  13991. if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
  13992. for (i = byteOffset; i >= 0; i--) {
  13993. var found = true
  13994. for (var j = 0; j < valLength; j++) {
  13995. if (read(arr, i + j) !== read(val, j)) {
  13996. found = false
  13997. break
  13998. }
  13999. }
  14000. if (found) return i
  14001. }
  14002. }
  14003. return -1
  14004. }
  14005. Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
  14006. return this.indexOf(val, byteOffset, encoding) !== -1
  14007. }
  14008. Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
  14009. return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
  14010. }
  14011. Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
  14012. return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
  14013. }
  14014. function hexWrite (buf, string, offset, length) {
  14015. offset = Number(offset) || 0
  14016. var remaining = buf.length - offset
  14017. if (!length) {
  14018. length = remaining
  14019. } else {
  14020. length = Number(length)
  14021. if (length > remaining) {
  14022. length = remaining
  14023. }
  14024. }
  14025. // must be an even number of digits
  14026. var strLen = string.length
  14027. if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')
  14028. if (length > strLen / 2) {
  14029. length = strLen / 2
  14030. }
  14031. for (var i = 0; i < length; ++i) {
  14032. var parsed = parseInt(string.substr(i * 2, 2), 16)
  14033. if (isNaN(parsed)) return i
  14034. buf[offset + i] = parsed
  14035. }
  14036. return i
  14037. }
  14038. function utf8Write (buf, string, offset, length) {
  14039. return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
  14040. }
  14041. function asciiWrite (buf, string, offset, length) {
  14042. return blitBuffer(asciiToBytes(string), buf, offset, length)
  14043. }
  14044. function latin1Write (buf, string, offset, length) {
  14045. return asciiWrite(buf, string, offset, length)
  14046. }
  14047. function base64Write (buf, string, offset, length) {
  14048. return blitBuffer(base64ToBytes(string), buf, offset, length)
  14049. }
  14050. function ucs2Write (buf, string, offset, length) {
  14051. return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
  14052. }
  14053. Buffer.prototype.write = function write (string, offset, length, encoding) {
  14054. // Buffer#write(string)
  14055. if (offset === undefined) {
  14056. encoding = 'utf8'
  14057. length = this.length
  14058. offset = 0
  14059. // Buffer#write(string, encoding)
  14060. } else if (length === undefined && typeof offset === 'string') {
  14061. encoding = offset
  14062. length = this.length
  14063. offset = 0
  14064. // Buffer#write(string, offset[, length][, encoding])
  14065. } else if (isFinite(offset)) {
  14066. offset = offset | 0
  14067. if (isFinite(length)) {
  14068. length = length | 0
  14069. if (encoding === undefined) encoding = 'utf8'
  14070. } else {
  14071. encoding = length
  14072. length = undefined
  14073. }
  14074. // legacy write(string, encoding, offset, length) - remove in v0.13
  14075. } else {
  14076. throw new Error(
  14077. 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
  14078. )
  14079. }
  14080. var remaining = this.length - offset
  14081. if (length === undefined || length > remaining) length = remaining
  14082. if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
  14083. throw new RangeError('Attempt to write outside buffer bounds')
  14084. }
  14085. if (!encoding) encoding = 'utf8'
  14086. var loweredCase = false
  14087. for (;;) {
  14088. switch (encoding) {
  14089. case 'hex':
  14090. return hexWrite(this, string, offset, length)
  14091. case 'utf8':
  14092. case 'utf-8':
  14093. return utf8Write(this, string, offset, length)
  14094. case 'ascii':
  14095. return asciiWrite(this, string, offset, length)
  14096. case 'latin1':
  14097. case 'binary':
  14098. return latin1Write(this, string, offset, length)
  14099. case 'base64':
  14100. // Warning: maxLength not taken into account in base64Write
  14101. return base64Write(this, string, offset, length)
  14102. case 'ucs2':
  14103. case 'ucs-2':
  14104. case 'utf16le':
  14105. case 'utf-16le':
  14106. return ucs2Write(this, string, offset, length)
  14107. default:
  14108. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  14109. encoding = ('' + encoding).toLowerCase()
  14110. loweredCase = true
  14111. }
  14112. }
  14113. }
  14114. Buffer.prototype.toJSON = function toJSON () {
  14115. return {
  14116. type: 'Buffer',
  14117. data: Array.prototype.slice.call(this._arr || this, 0)
  14118. }
  14119. }
  14120. function base64Slice (buf, start, end) {
  14121. if (start === 0 && end === buf.length) {
  14122. return base64.fromByteArray(buf)
  14123. } else {
  14124. return base64.fromByteArray(buf.slice(start, end))
  14125. }
  14126. }
  14127. function utf8Slice (buf, start, end) {
  14128. end = Math.min(buf.length, end)
  14129. var res = []
  14130. var i = start
  14131. while (i < end) {
  14132. var firstByte = buf[i]
  14133. var codePoint = null
  14134. var bytesPerSequence = (firstByte > 0xEF) ? 4
  14135. : (firstByte > 0xDF) ? 3
  14136. : (firstByte > 0xBF) ? 2
  14137. : 1
  14138. if (i + bytesPerSequence <= end) {
  14139. var secondByte, thirdByte, fourthByte, tempCodePoint
  14140. switch (bytesPerSequence) {
  14141. case 1:
  14142. if (firstByte < 0x80) {
  14143. codePoint = firstByte
  14144. }
  14145. break
  14146. case 2:
  14147. secondByte = buf[i + 1]
  14148. if ((secondByte & 0xC0) === 0x80) {
  14149. tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
  14150. if (tempCodePoint > 0x7F) {
  14151. codePoint = tempCodePoint
  14152. }
  14153. }
  14154. break
  14155. case 3:
  14156. secondByte = buf[i + 1]
  14157. thirdByte = buf[i + 2]
  14158. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
  14159. tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
  14160. if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
  14161. codePoint = tempCodePoint
  14162. }
  14163. }
  14164. break
  14165. case 4:
  14166. secondByte = buf[i + 1]
  14167. thirdByte = buf[i + 2]
  14168. fourthByte = buf[i + 3]
  14169. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
  14170. tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
  14171. if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
  14172. codePoint = tempCodePoint
  14173. }
  14174. }
  14175. }
  14176. }
  14177. if (codePoint === null) {
  14178. // we did not generate a valid codePoint so insert a
  14179. // replacement char (U+FFFD) and advance only 1 byte
  14180. codePoint = 0xFFFD
  14181. bytesPerSequence = 1
  14182. } else if (codePoint > 0xFFFF) {
  14183. // encode to utf16 (surrogate pair dance)
  14184. codePoint -= 0x10000
  14185. res.push(codePoint >>> 10 & 0x3FF | 0xD800)
  14186. codePoint = 0xDC00 | codePoint & 0x3FF
  14187. }
  14188. res.push(codePoint)
  14189. i += bytesPerSequence
  14190. }
  14191. return decodeCodePointsArray(res)
  14192. }
  14193. // Based on http://stackoverflow.com/a/22747272/680742, the browser with
  14194. // the lowest limit is Chrome, with 0x10000 args.
  14195. // We go 1 magnitude less, for safety
  14196. var MAX_ARGUMENTS_LENGTH = 0x1000
  14197. function decodeCodePointsArray (codePoints) {
  14198. var len = codePoints.length
  14199. if (len <= MAX_ARGUMENTS_LENGTH) {
  14200. return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
  14201. }
  14202. // Decode in chunks to avoid "call stack size exceeded".
  14203. var res = ''
  14204. var i = 0
  14205. while (i < len) {
  14206. res += String.fromCharCode.apply(
  14207. String,
  14208. codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
  14209. )
  14210. }
  14211. return res
  14212. }
  14213. function asciiSlice (buf, start, end) {
  14214. var ret = ''
  14215. end = Math.min(buf.length, end)
  14216. for (var i = start; i < end; ++i) {
  14217. ret += String.fromCharCode(buf[i] & 0x7F)
  14218. }
  14219. return ret
  14220. }
  14221. function latin1Slice (buf, start, end) {
  14222. var ret = ''
  14223. end = Math.min(buf.length, end)
  14224. for (var i = start; i < end; ++i) {
  14225. ret += String.fromCharCode(buf[i])
  14226. }
  14227. return ret
  14228. }
  14229. function hexSlice (buf, start, end) {
  14230. var len = buf.length
  14231. if (!start || start < 0) start = 0
  14232. if (!end || end < 0 || end > len) end = len
  14233. var out = ''
  14234. for (var i = start; i < end; ++i) {
  14235. out += toHex(buf[i])
  14236. }
  14237. return out
  14238. }
  14239. function utf16leSlice (buf, start, end) {
  14240. var bytes = buf.slice(start, end)
  14241. var res = ''
  14242. for (var i = 0; i < bytes.length; i += 2) {
  14243. res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)
  14244. }
  14245. return res
  14246. }
  14247. Buffer.prototype.slice = function slice (start, end) {
  14248. var len = this.length
  14249. start = ~~start
  14250. end = end === undefined ? len : ~~end
  14251. if (start < 0) {
  14252. start += len
  14253. if (start < 0) start = 0
  14254. } else if (start > len) {
  14255. start = len
  14256. }
  14257. if (end < 0) {
  14258. end += len
  14259. if (end < 0) end = 0
  14260. } else if (end > len) {
  14261. end = len
  14262. }
  14263. if (end < start) end = start
  14264. var newBuf
  14265. if (Buffer.TYPED_ARRAY_SUPPORT) {
  14266. newBuf = this.subarray(start, end)
  14267. newBuf.__proto__ = Buffer.prototype
  14268. } else {
  14269. var sliceLen = end - start
  14270. newBuf = new Buffer(sliceLen, undefined)
  14271. for (var i = 0; i < sliceLen; ++i) {
  14272. newBuf[i] = this[i + start]
  14273. }
  14274. }
  14275. return newBuf
  14276. }
  14277. /*
  14278. * Need to make sure that buffer isn't trying to write out of bounds.
  14279. */
  14280. function checkOffset (offset, ext, length) {
  14281. if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
  14282. if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
  14283. }
  14284. Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
  14285. offset = offset | 0
  14286. byteLength = byteLength | 0
  14287. if (!noAssert) checkOffset(offset, byteLength, this.length)
  14288. var val = this[offset]
  14289. var mul = 1
  14290. var i = 0
  14291. while (++i < byteLength && (mul *= 0x100)) {
  14292. val += this[offset + i] * mul
  14293. }
  14294. return val
  14295. }
  14296. Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
  14297. offset = offset | 0
  14298. byteLength = byteLength | 0
  14299. if (!noAssert) {
  14300. checkOffset(offset, byteLength, this.length)
  14301. }
  14302. var val = this[offset + --byteLength]
  14303. var mul = 1
  14304. while (byteLength > 0 && (mul *= 0x100)) {
  14305. val += this[offset + --byteLength] * mul
  14306. }
  14307. return val
  14308. }
  14309. Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
  14310. if (!noAssert) checkOffset(offset, 1, this.length)
  14311. return this[offset]
  14312. }
  14313. Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
  14314. if (!noAssert) checkOffset(offset, 2, this.length)
  14315. return this[offset] | (this[offset + 1] << 8)
  14316. }
  14317. Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
  14318. if (!noAssert) checkOffset(offset, 2, this.length)
  14319. return (this[offset] << 8) | this[offset + 1]
  14320. }
  14321. Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
  14322. if (!noAssert) checkOffset(offset, 4, this.length)
  14323. return ((this[offset]) |
  14324. (this[offset + 1] << 8) |
  14325. (this[offset + 2] << 16)) +
  14326. (this[offset + 3] * 0x1000000)
  14327. }
  14328. Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
  14329. if (!noAssert) checkOffset(offset, 4, this.length)
  14330. return (this[offset] * 0x1000000) +
  14331. ((this[offset + 1] << 16) |
  14332. (this[offset + 2] << 8) |
  14333. this[offset + 3])
  14334. }
  14335. Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
  14336. offset = offset | 0
  14337. byteLength = byteLength | 0
  14338. if (!noAssert) checkOffset(offset, byteLength, this.length)
  14339. var val = this[offset]
  14340. var mul = 1
  14341. var i = 0
  14342. while (++i < byteLength && (mul *= 0x100)) {
  14343. val += this[offset + i] * mul
  14344. }
  14345. mul *= 0x80
  14346. if (val >= mul) val -= Math.pow(2, 8 * byteLength)
  14347. return val
  14348. }
  14349. Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
  14350. offset = offset | 0
  14351. byteLength = byteLength | 0
  14352. if (!noAssert) checkOffset(offset, byteLength, this.length)
  14353. var i = byteLength
  14354. var mul = 1
  14355. var val = this[offset + --i]
  14356. while (i > 0 && (mul *= 0x100)) {
  14357. val += this[offset + --i] * mul
  14358. }
  14359. mul *= 0x80
  14360. if (val >= mul) val -= Math.pow(2, 8 * byteLength)
  14361. return val
  14362. }
  14363. Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
  14364. if (!noAssert) checkOffset(offset, 1, this.length)
  14365. if (!(this[offset] & 0x80)) return (this[offset])
  14366. return ((0xff - this[offset] + 1) * -1)
  14367. }
  14368. Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
  14369. if (!noAssert) checkOffset(offset, 2, this.length)
  14370. var val = this[offset] | (this[offset + 1] << 8)
  14371. return (val & 0x8000) ? val | 0xFFFF0000 : val
  14372. }
  14373. Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
  14374. if (!noAssert) checkOffset(offset, 2, this.length)
  14375. var val = this[offset + 1] | (this[offset] << 8)
  14376. return (val & 0x8000) ? val | 0xFFFF0000 : val
  14377. }
  14378. Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
  14379. if (!noAssert) checkOffset(offset, 4, this.length)
  14380. return (this[offset]) |
  14381. (this[offset + 1] << 8) |
  14382. (this[offset + 2] << 16) |
  14383. (this[offset + 3] << 24)
  14384. }
  14385. Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
  14386. if (!noAssert) checkOffset(offset, 4, this.length)
  14387. return (this[offset] << 24) |
  14388. (this[offset + 1] << 16) |
  14389. (this[offset + 2] << 8) |
  14390. (this[offset + 3])
  14391. }
  14392. Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
  14393. if (!noAssert) checkOffset(offset, 4, this.length)
  14394. return ieee754.read(this, offset, true, 23, 4)
  14395. }
  14396. Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
  14397. if (!noAssert) checkOffset(offset, 4, this.length)
  14398. return ieee754.read(this, offset, false, 23, 4)
  14399. }
  14400. Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
  14401. if (!noAssert) checkOffset(offset, 8, this.length)
  14402. return ieee754.read(this, offset, true, 52, 8)
  14403. }
  14404. Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
  14405. if (!noAssert) checkOffset(offset, 8, this.length)
  14406. return ieee754.read(this, offset, false, 52, 8)
  14407. }
  14408. function checkInt (buf, value, offset, ext, max, min) {
  14409. if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
  14410. if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
  14411. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  14412. }
  14413. Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
  14414. value = +value
  14415. offset = offset | 0
  14416. byteLength = byteLength | 0
  14417. if (!noAssert) {
  14418. var maxBytes = Math.pow(2, 8 * byteLength) - 1
  14419. checkInt(this, value, offset, byteLength, maxBytes, 0)
  14420. }
  14421. var mul = 1
  14422. var i = 0
  14423. this[offset] = value & 0xFF
  14424. while (++i < byteLength && (mul *= 0x100)) {
  14425. this[offset + i] = (value / mul) & 0xFF
  14426. }
  14427. return offset + byteLength
  14428. }
  14429. Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
  14430. value = +value
  14431. offset = offset | 0
  14432. byteLength = byteLength | 0
  14433. if (!noAssert) {
  14434. var maxBytes = Math.pow(2, 8 * byteLength) - 1
  14435. checkInt(this, value, offset, byteLength, maxBytes, 0)
  14436. }
  14437. var i = byteLength - 1
  14438. var mul = 1
  14439. this[offset + i] = value & 0xFF
  14440. while (--i >= 0 && (mul *= 0x100)) {
  14441. this[offset + i] = (value / mul) & 0xFF
  14442. }
  14443. return offset + byteLength
  14444. }
  14445. Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
  14446. value = +value
  14447. offset = offset | 0
  14448. if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
  14449. if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
  14450. this[offset] = (value & 0xff)
  14451. return offset + 1
  14452. }
  14453. function objectWriteUInt16 (buf, value, offset, littleEndian) {
  14454. if (value < 0) value = 0xffff + value + 1
  14455. for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) {
  14456. buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
  14457. (littleEndian ? i : 1 - i) * 8
  14458. }
  14459. }
  14460. Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
  14461. value = +value
  14462. offset = offset | 0
  14463. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  14464. if (Buffer.TYPED_ARRAY_SUPPORT) {
  14465. this[offset] = (value & 0xff)
  14466. this[offset + 1] = (value >>> 8)
  14467. } else {
  14468. objectWriteUInt16(this, value, offset, true)
  14469. }
  14470. return offset + 2
  14471. }
  14472. Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
  14473. value = +value
  14474. offset = offset | 0
  14475. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  14476. if (Buffer.TYPED_ARRAY_SUPPORT) {
  14477. this[offset] = (value >>> 8)
  14478. this[offset + 1] = (value & 0xff)
  14479. } else {
  14480. objectWriteUInt16(this, value, offset, false)
  14481. }
  14482. return offset + 2
  14483. }
  14484. function objectWriteUInt32 (buf, value, offset, littleEndian) {
  14485. if (value < 0) value = 0xffffffff + value + 1
  14486. for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) {
  14487. buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff
  14488. }
  14489. }
  14490. Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
  14491. value = +value
  14492. offset = offset | 0
  14493. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  14494. if (Buffer.TYPED_ARRAY_SUPPORT) {
  14495. this[offset + 3] = (value >>> 24)
  14496. this[offset + 2] = (value >>> 16)
  14497. this[offset + 1] = (value >>> 8)
  14498. this[offset] = (value & 0xff)
  14499. } else {
  14500. objectWriteUInt32(this, value, offset, true)
  14501. }
  14502. return offset + 4
  14503. }
  14504. Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
  14505. value = +value
  14506. offset = offset | 0
  14507. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  14508. if (Buffer.TYPED_ARRAY_SUPPORT) {
  14509. this[offset] = (value >>> 24)
  14510. this[offset + 1] = (value >>> 16)
  14511. this[offset + 2] = (value >>> 8)
  14512. this[offset + 3] = (value & 0xff)
  14513. } else {
  14514. objectWriteUInt32(this, value, offset, false)
  14515. }
  14516. return offset + 4
  14517. }
  14518. Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
  14519. value = +value
  14520. offset = offset | 0
  14521. if (!noAssert) {
  14522. var limit = Math.pow(2, 8 * byteLength - 1)
  14523. checkInt(this, value, offset, byteLength, limit - 1, -limit)
  14524. }
  14525. var i = 0
  14526. var mul = 1
  14527. var sub = 0
  14528. this[offset] = value & 0xFF
  14529. while (++i < byteLength && (mul *= 0x100)) {
  14530. if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
  14531. sub = 1
  14532. }
  14533. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  14534. }
  14535. return offset + byteLength
  14536. }
  14537. Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
  14538. value = +value
  14539. offset = offset | 0
  14540. if (!noAssert) {
  14541. var limit = Math.pow(2, 8 * byteLength - 1)
  14542. checkInt(this, value, offset, byteLength, limit - 1, -limit)
  14543. }
  14544. var i = byteLength - 1
  14545. var mul = 1
  14546. var sub = 0
  14547. this[offset + i] = value & 0xFF
  14548. while (--i >= 0 && (mul *= 0x100)) {
  14549. if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
  14550. sub = 1
  14551. }
  14552. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  14553. }
  14554. return offset + byteLength
  14555. }
  14556. Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
  14557. value = +value
  14558. offset = offset | 0
  14559. if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
  14560. if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
  14561. if (value < 0) value = 0xff + value + 1
  14562. this[offset] = (value & 0xff)
  14563. return offset + 1
  14564. }
  14565. Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
  14566. value = +value
  14567. offset = offset | 0
  14568. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  14569. if (Buffer.TYPED_ARRAY_SUPPORT) {
  14570. this[offset] = (value & 0xff)
  14571. this[offset + 1] = (value >>> 8)
  14572. } else {
  14573. objectWriteUInt16(this, value, offset, true)
  14574. }
  14575. return offset + 2
  14576. }
  14577. Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
  14578. value = +value
  14579. offset = offset | 0
  14580. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  14581. if (Buffer.TYPED_ARRAY_SUPPORT) {
  14582. this[offset] = (value >>> 8)
  14583. this[offset + 1] = (value & 0xff)
  14584. } else {
  14585. objectWriteUInt16(this, value, offset, false)
  14586. }
  14587. return offset + 2
  14588. }
  14589. Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
  14590. value = +value
  14591. offset = offset | 0
  14592. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  14593. if (Buffer.TYPED_ARRAY_SUPPORT) {
  14594. this[offset] = (value & 0xff)
  14595. this[offset + 1] = (value >>> 8)
  14596. this[offset + 2] = (value >>> 16)
  14597. this[offset + 3] = (value >>> 24)
  14598. } else {
  14599. objectWriteUInt32(this, value, offset, true)
  14600. }
  14601. return offset + 4
  14602. }
  14603. Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
  14604. value = +value
  14605. offset = offset | 0
  14606. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  14607. if (value < 0) value = 0xffffffff + value + 1
  14608. if (Buffer.TYPED_ARRAY_SUPPORT) {
  14609. this[offset] = (value >>> 24)
  14610. this[offset + 1] = (value >>> 16)
  14611. this[offset + 2] = (value >>> 8)
  14612. this[offset + 3] = (value & 0xff)
  14613. } else {
  14614. objectWriteUInt32(this, value, offset, false)
  14615. }
  14616. return offset + 4
  14617. }
  14618. function checkIEEE754 (buf, value, offset, ext, max, min) {
  14619. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  14620. if (offset < 0) throw new RangeError('Index out of range')
  14621. }
  14622. function writeFloat (buf, value, offset, littleEndian, noAssert) {
  14623. if (!noAssert) {
  14624. checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
  14625. }
  14626. ieee754.write(buf, value, offset, littleEndian, 23, 4)
  14627. return offset + 4
  14628. }
  14629. Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
  14630. return writeFloat(this, value, offset, true, noAssert)
  14631. }
  14632. Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
  14633. return writeFloat(this, value, offset, false, noAssert)
  14634. }
  14635. function writeDouble (buf, value, offset, littleEndian, noAssert) {
  14636. if (!noAssert) {
  14637. checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
  14638. }
  14639. ieee754.write(buf, value, offset, littleEndian, 52, 8)
  14640. return offset + 8
  14641. }
  14642. Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
  14643. return writeDouble(this, value, offset, true, noAssert)
  14644. }
  14645. Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
  14646. return writeDouble(this, value, offset, false, noAssert)
  14647. }
  14648. // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
  14649. Buffer.prototype.copy = function copy (target, targetStart, start, end) {
  14650. if (!start) start = 0
  14651. if (!end && end !== 0) end = this.length
  14652. if (targetStart >= target.length) targetStart = target.length
  14653. if (!targetStart) targetStart = 0
  14654. if (end > 0 && end < start) end = start
  14655. // Copy 0 bytes; we're done
  14656. if (end === start) return 0
  14657. if (target.length === 0 || this.length === 0) return 0
  14658. // Fatal error conditions
  14659. if (targetStart < 0) {
  14660. throw new RangeError('targetStart out of bounds')
  14661. }
  14662. if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
  14663. if (end < 0) throw new RangeError('sourceEnd out of bounds')
  14664. // Are we oob?
  14665. if (end > this.length) end = this.length
  14666. if (target.length - targetStart < end - start) {
  14667. end = target.length - targetStart + start
  14668. }
  14669. var len = end - start
  14670. var i
  14671. if (this === target && start < targetStart && targetStart < end) {
  14672. // descending copy from end
  14673. for (i = len - 1; i >= 0; --i) {
  14674. target[i + targetStart] = this[i + start]
  14675. }
  14676. } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {
  14677. // ascending copy from start
  14678. for (i = 0; i < len; ++i) {
  14679. target[i + targetStart] = this[i + start]
  14680. }
  14681. } else {
  14682. Uint8Array.prototype.set.call(
  14683. target,
  14684. this.subarray(start, start + len),
  14685. targetStart
  14686. )
  14687. }
  14688. return len
  14689. }
  14690. // Usage:
  14691. // buffer.fill(number[, offset[, end]])
  14692. // buffer.fill(buffer[, offset[, end]])
  14693. // buffer.fill(string[, offset[, end]][, encoding])
  14694. Buffer.prototype.fill = function fill (val, start, end, encoding) {
  14695. // Handle string cases:
  14696. if (typeof val === 'string') {
  14697. if (typeof start === 'string') {
  14698. encoding = start
  14699. start = 0
  14700. end = this.length
  14701. } else if (typeof end === 'string') {
  14702. encoding = end
  14703. end = this.length
  14704. }
  14705. if (val.length === 1) {
  14706. var code = val.charCodeAt(0)
  14707. if (code < 256) {
  14708. val = code
  14709. }
  14710. }
  14711. if (encoding !== undefined && typeof encoding !== 'string') {
  14712. throw new TypeError('encoding must be a string')
  14713. }
  14714. if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
  14715. throw new TypeError('Unknown encoding: ' + encoding)
  14716. }
  14717. } else if (typeof val === 'number') {
  14718. val = val & 255
  14719. }
  14720. // Invalid ranges are not set to a default, so can range check early.
  14721. if (start < 0 || this.length < start || this.length < end) {
  14722. throw new RangeError('Out of range index')
  14723. }
  14724. if (end <= start) {
  14725. return this
  14726. }
  14727. start = start >>> 0
  14728. end = end === undefined ? this.length : end >>> 0
  14729. if (!val) val = 0
  14730. var i
  14731. if (typeof val === 'number') {
  14732. for (i = start; i < end; ++i) {
  14733. this[i] = val
  14734. }
  14735. } else {
  14736. var bytes = Buffer.isBuffer(val)
  14737. ? val
  14738. : utf8ToBytes(new Buffer(val, encoding).toString())
  14739. var len = bytes.length
  14740. for (i = 0; i < end - start; ++i) {
  14741. this[i + start] = bytes[i % len]
  14742. }
  14743. }
  14744. return this
  14745. }
  14746. // HELPER FUNCTIONS
  14747. // ================
  14748. var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g
  14749. function base64clean (str) {
  14750. // Node strips out invalid characters like \n and \t from the string, base64-js does not
  14751. str = stringtrim(str).replace(INVALID_BASE64_RE, '')
  14752. // Node converts strings with length < 2 to ''
  14753. if (str.length < 2) return ''
  14754. // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
  14755. while (str.length % 4 !== 0) {
  14756. str = str + '='
  14757. }
  14758. return str
  14759. }
  14760. function stringtrim (str) {
  14761. if (str.trim) return str.trim()
  14762. return str.replace(/^\s+|\s+$/g, '')
  14763. }
  14764. function toHex (n) {
  14765. if (n < 16) return '0' + n.toString(16)
  14766. return n.toString(16)
  14767. }
  14768. function utf8ToBytes (string, units) {
  14769. units = units || Infinity
  14770. var codePoint
  14771. var length = string.length
  14772. var leadSurrogate = null
  14773. var bytes = []
  14774. for (var i = 0; i < length; ++i) {
  14775. codePoint = string.charCodeAt(i)
  14776. // is surrogate component
  14777. if (codePoint > 0xD7FF && codePoint < 0xE000) {
  14778. // last char was a lead
  14779. if (!leadSurrogate) {
  14780. // no lead yet
  14781. if (codePoint > 0xDBFF) {
  14782. // unexpected trail
  14783. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  14784. continue
  14785. } else if (i + 1 === length) {
  14786. // unpaired lead
  14787. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  14788. continue
  14789. }
  14790. // valid lead
  14791. leadSurrogate = codePoint
  14792. continue
  14793. }
  14794. // 2 leads in a row
  14795. if (codePoint < 0xDC00) {
  14796. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  14797. leadSurrogate = codePoint
  14798. continue
  14799. }
  14800. // valid surrogate pair
  14801. codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
  14802. } else if (leadSurrogate) {
  14803. // valid bmp char, but last char was a lead
  14804. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  14805. }
  14806. leadSurrogate = null
  14807. // encode utf8
  14808. if (codePoint < 0x80) {
  14809. if ((units -= 1) < 0) break
  14810. bytes.push(codePoint)
  14811. } else if (codePoint < 0x800) {
  14812. if ((units -= 2) < 0) break
  14813. bytes.push(
  14814. codePoint >> 0x6 | 0xC0,
  14815. codePoint & 0x3F | 0x80
  14816. )
  14817. } else if (codePoint < 0x10000) {
  14818. if ((units -= 3) < 0) break
  14819. bytes.push(
  14820. codePoint >> 0xC | 0xE0,
  14821. codePoint >> 0x6 & 0x3F | 0x80,
  14822. codePoint & 0x3F | 0x80
  14823. )
  14824. } else if (codePoint < 0x110000) {
  14825. if ((units -= 4) < 0) break
  14826. bytes.push(
  14827. codePoint >> 0x12 | 0xF0,
  14828. codePoint >> 0xC & 0x3F | 0x80,
  14829. codePoint >> 0x6 & 0x3F | 0x80,
  14830. codePoint & 0x3F | 0x80
  14831. )
  14832. } else {
  14833. throw new Error('Invalid code point')
  14834. }
  14835. }
  14836. return bytes
  14837. }
  14838. function asciiToBytes (str) {
  14839. var byteArray = []
  14840. for (var i = 0; i < str.length; ++i) {
  14841. // Node's code seems to be doing this and not & 0x7F..
  14842. byteArray.push(str.charCodeAt(i) & 0xFF)
  14843. }
  14844. return byteArray
  14845. }
  14846. function utf16leToBytes (str, units) {
  14847. var c, hi, lo
  14848. var byteArray = []
  14849. for (var i = 0; i < str.length; ++i) {
  14850. if ((units -= 2) < 0) break
  14851. c = str.charCodeAt(i)
  14852. hi = c >> 8
  14853. lo = c % 256
  14854. byteArray.push(lo)
  14855. byteArray.push(hi)
  14856. }
  14857. return byteArray
  14858. }
  14859. function base64ToBytes (str) {
  14860. return base64.toByteArray(base64clean(str))
  14861. }
  14862. function blitBuffer (src, dst, offset, length) {
  14863. for (var i = 0; i < length; ++i) {
  14864. if ((i + offset >= dst.length) || (i >= src.length)) break
  14865. dst[i + offset] = src[i]
  14866. }
  14867. return i
  14868. }
  14869. function isnan (val) {
  14870. return val !== val // eslint-disable-line no-self-compare
  14871. }
  14872. /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }())))
  14873. /***/ }),
  14874. /* 19 */
  14875. /***/ (function(module, exports) {
  14876. 'use strict'
  14877. exports.byteLength = byteLength
  14878. exports.toByteArray = toByteArray
  14879. exports.fromByteArray = fromByteArray
  14880. var lookup = []
  14881. var revLookup = []
  14882. var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
  14883. var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
  14884. for (var i = 0, len = code.length; i < len; ++i) {
  14885. lookup[i] = code[i]
  14886. revLookup[code.charCodeAt(i)] = i
  14887. }
  14888. revLookup['-'.charCodeAt(0)] = 62
  14889. revLookup['_'.charCodeAt(0)] = 63
  14890. function placeHoldersCount (b64) {
  14891. var len = b64.length
  14892. if (len % 4 > 0) {
  14893. throw new Error('Invalid string. Length must be a multiple of 4')
  14894. }
  14895. // the number of equal signs (place holders)
  14896. // if there are two placeholders, than the two characters before it
  14897. // represent one byte
  14898. // if there is only one, then the three characters before it represent 2 bytes
  14899. // this is just a cheap hack to not do indexOf twice
  14900. return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0
  14901. }
  14902. function byteLength (b64) {
  14903. // base64 is 4/3 + up to two characters of the original data
  14904. return (b64.length * 3 / 4) - placeHoldersCount(b64)
  14905. }
  14906. function toByteArray (b64) {
  14907. var i, l, tmp, placeHolders, arr
  14908. var len = b64.length
  14909. placeHolders = placeHoldersCount(b64)
  14910. arr = new Arr((len * 3 / 4) - placeHolders)
  14911. // if there are placeholders, only get up to the last complete 4 chars
  14912. l = placeHolders > 0 ? len - 4 : len
  14913. var L = 0
  14914. for (i = 0; i < l; i += 4) {
  14915. tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]
  14916. arr[L++] = (tmp >> 16) & 0xFF
  14917. arr[L++] = (tmp >> 8) & 0xFF
  14918. arr[L++] = tmp & 0xFF
  14919. }
  14920. if (placeHolders === 2) {
  14921. tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4)
  14922. arr[L++] = tmp & 0xFF
  14923. } else if (placeHolders === 1) {
  14924. tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2)
  14925. arr[L++] = (tmp >> 8) & 0xFF
  14926. arr[L++] = tmp & 0xFF
  14927. }
  14928. return arr
  14929. }
  14930. function tripletToBase64 (num) {
  14931. return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]
  14932. }
  14933. function encodeChunk (uint8, start, end) {
  14934. var tmp
  14935. var output = []
  14936. for (var i = start; i < end; i += 3) {
  14937. tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2])
  14938. output.push(tripletToBase64(tmp))
  14939. }
  14940. return output.join('')
  14941. }
  14942. function fromByteArray (uint8) {
  14943. var tmp
  14944. var len = uint8.length
  14945. var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
  14946. var output = ''
  14947. var parts = []
  14948. var maxChunkLength = 16383 // must be multiple of 3
  14949. // go through the array every three bytes, we'll deal with trailing stuff later
  14950. for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
  14951. parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))
  14952. }
  14953. // pad the end with zeros, but make sure to not forget the extra bytes
  14954. if (extraBytes === 1) {
  14955. tmp = uint8[len - 1]
  14956. output += lookup[tmp >> 2]
  14957. output += lookup[(tmp << 4) & 0x3F]
  14958. output += '=='
  14959. } else if (extraBytes === 2) {
  14960. tmp = (uint8[len - 2] << 8) + (uint8[len - 1])
  14961. output += lookup[tmp >> 10]
  14962. output += lookup[(tmp >> 4) & 0x3F]
  14963. output += lookup[(tmp << 2) & 0x3F]
  14964. output += '='
  14965. }
  14966. parts.push(output)
  14967. return parts.join('')
  14968. }
  14969. /***/ }),
  14970. /* 20 */
  14971. /***/ (function(module, exports) {
  14972. exports.read = function (buffer, offset, isLE, mLen, nBytes) {
  14973. var e, m
  14974. var eLen = nBytes * 8 - mLen - 1
  14975. var eMax = (1 << eLen) - 1
  14976. var eBias = eMax >> 1
  14977. var nBits = -7
  14978. var i = isLE ? (nBytes - 1) : 0
  14979. var d = isLE ? -1 : 1
  14980. var s = buffer[offset + i]
  14981. i += d
  14982. e = s & ((1 << (-nBits)) - 1)
  14983. s >>= (-nBits)
  14984. nBits += eLen
  14985. for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
  14986. m = e & ((1 << (-nBits)) - 1)
  14987. e >>= (-nBits)
  14988. nBits += mLen
  14989. for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
  14990. if (e === 0) {
  14991. e = 1 - eBias
  14992. } else if (e === eMax) {
  14993. return m ? NaN : ((s ? -1 : 1) * Infinity)
  14994. } else {
  14995. m = m + Math.pow(2, mLen)
  14996. e = e - eBias
  14997. }
  14998. return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
  14999. }
  15000. exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
  15001. var e, m, c
  15002. var eLen = nBytes * 8 - mLen - 1
  15003. var eMax = (1 << eLen) - 1
  15004. var eBias = eMax >> 1
  15005. var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
  15006. var i = isLE ? 0 : (nBytes - 1)
  15007. var d = isLE ? 1 : -1
  15008. var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
  15009. value = Math.abs(value)
  15010. if (isNaN(value) || value === Infinity) {
  15011. m = isNaN(value) ? 1 : 0
  15012. e = eMax
  15013. } else {
  15014. e = Math.floor(Math.log(value) / Math.LN2)
  15015. if (value * (c = Math.pow(2, -e)) < 1) {
  15016. e--
  15017. c *= 2
  15018. }
  15019. if (e + eBias >= 1) {
  15020. value += rt / c
  15021. } else {
  15022. value += rt * Math.pow(2, 1 - eBias)
  15023. }
  15024. if (value * c >= 2) {
  15025. e++
  15026. c /= 2
  15027. }
  15028. if (e + eBias >= eMax) {
  15029. m = 0
  15030. e = eMax
  15031. } else if (e + eBias >= 1) {
  15032. m = (value * c - 1) * Math.pow(2, mLen)
  15033. e = e + eBias
  15034. } else {
  15035. m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
  15036. e = 0
  15037. }
  15038. }
  15039. for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
  15040. e = (e << mLen) | m
  15041. eLen += mLen
  15042. for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
  15043. buffer[offset + i - d] |= s * 128
  15044. }
  15045. /***/ }),
  15046. /* 21 */
  15047. /***/ (function(module, exports) {
  15048. var toString = {}.toString;
  15049. module.exports = Array.isArray || function (arr) {
  15050. return toString.call(arr) == '[object Array]';
  15051. };
  15052. /***/ }),
  15053. /* 22 */
  15054. /***/ (function(module, exports) {
  15055. /* (ignored) */
  15056. /***/ }),
  15057. /* 23 */
  15058. /***/ (function(module, exports, __webpack_require__) {
  15059. /* WEBPACK VAR INJECTION */(function(global) {/**
  15060. * marked - a markdown parser
  15061. * Copyright (c) 2011-2014, Christopher Jeffrey. (MIT Licensed)
  15062. * https://github.com/chjj/marked
  15063. */
  15064. ;(function() {
  15065. /**
  15066. * Block-Level Grammar
  15067. */
  15068. var block = {
  15069. newline: /^\n+/,
  15070. code: /^( {4}[^\n]+\n*)+/,
  15071. fences: noop,
  15072. hr: /^( *[-*_]){3,} *(?:\n+|$)/,
  15073. heading: /^ *(#{1,6}) *([^\n]+?) *#* *(?:\n+|$)/,
  15074. nptable: noop,
  15075. lheading: /^([^\n]+)\n *(=|-){2,} *(?:\n+|$)/,
  15076. blockquote: /^( *>[^\n]+(\n(?!def)[^\n]+)*\n*)+/,
  15077. list: /^( *)(bull) [\s\S]+?(?:hr|def|\n{2,}(?! )(?!\1bull )\n*|\s*$)/,
  15078. html: /^ *(?:comment *(?:\n|\s*$)|closed *(?:\n{2,}|\s*$)|closing *(?:\n{2,}|\s*$))/,
  15079. def: /^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +["(]([^\n]+)[")])? *(?:\n+|$)/,
  15080. table: noop,
  15081. paragraph: /^((?:[^\n]+\n?(?!hr|heading|lheading|blockquote|tag|def))+)\n*/,
  15082. text: /^[^\n]+/
  15083. };
  15084. block.bullet = /(?:[*+-]|\d+\.)/;
  15085. block.item = /^( *)(bull) [^\n]*(?:\n(?!\1bull )[^\n]*)*/;
  15086. block.item = replace(block.item, 'gm')
  15087. (/bull/g, block.bullet)
  15088. ();
  15089. block.list = replace(block.list)
  15090. (/bull/g, block.bullet)
  15091. ('hr', '\\n+(?=\\1?(?:[-*_] *){3,}(?:\\n+|$))')
  15092. ('def', '\\n+(?=' + block.def.source + ')')
  15093. ();
  15094. block.blockquote = replace(block.blockquote)
  15095. ('def', block.def)
  15096. ();
  15097. block._tag = '(?!(?:'
  15098. + 'a|em|strong|small|s|cite|q|dfn|abbr|data|time|code'
  15099. + '|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo'
  15100. + '|span|br|wbr|ins|del|img)\\b)\\w+(?!:/|[^\\w\\s@]*@)\\b';
  15101. block.html = replace(block.html)
  15102. ('comment', /<!--[\s\S]*?-->/)
  15103. ('closed', /<(tag)[\s\S]+?<\/\1>/)
  15104. ('closing', /<tag(?:"[^"]*"|'[^']*'|[^'">])*?>/)
  15105. (/tag/g, block._tag)
  15106. ();
  15107. block.paragraph = replace(block.paragraph)
  15108. ('hr', block.hr)
  15109. ('heading', block.heading)
  15110. ('lheading', block.lheading)
  15111. ('blockquote', block.blockquote)
  15112. ('tag', '<' + block._tag)
  15113. ('def', block.def)
  15114. ();
  15115. /**
  15116. * Normal Block Grammar
  15117. */
  15118. block.normal = merge({}, block);
  15119. /**
  15120. * GFM Block Grammar
  15121. */
  15122. block.gfm = merge({}, block.normal, {
  15123. fences: /^ *(`{3,}|~{3,})[ \.]*(\S+)? *\n([\s\S]*?)\s*\1 *(?:\n+|$)/,
  15124. paragraph: /^/,
  15125. heading: /^ *(#{1,6}) +([^\n]+?) *#* *(?:\n+|$)/
  15126. });
  15127. block.gfm.paragraph = replace(block.paragraph)
  15128. ('(?!', '(?!'
  15129. + block.gfm.fences.source.replace('\\1', '\\2') + '|'
  15130. + block.list.source.replace('\\1', '\\3') + '|')
  15131. ();
  15132. /**
  15133. * GFM + Tables Block Grammar
  15134. */
  15135. block.tables = merge({}, block.gfm, {
  15136. nptable: /^ *(\S.*\|.*)\n *([-:]+ *\|[-| :]*)\n((?:.*\|.*(?:\n|$))*)\n*/,
  15137. table: /^ *\|(.+)\n *\|( *[-:]+[-| :]*)\n((?: *\|.*(?:\n|$))*)\n*/
  15138. });
  15139. /**
  15140. * Block Lexer
  15141. */
  15142. function Lexer(options) {
  15143. this.tokens = [];
  15144. this.tokens.links = {};
  15145. this.options = options || marked.defaults;
  15146. this.rules = block.normal;
  15147. if (this.options.gfm) {
  15148. if (this.options.tables) {
  15149. this.rules = block.tables;
  15150. } else {
  15151. this.rules = block.gfm;
  15152. }
  15153. }
  15154. }
  15155. /**
  15156. * Expose Block Rules
  15157. */
  15158. Lexer.rules = block;
  15159. /**
  15160. * Static Lex Method
  15161. */
  15162. Lexer.lex = function(src, options) {
  15163. var lexer = new Lexer(options);
  15164. return lexer.lex(src);
  15165. };
  15166. /**
  15167. * Preprocessing
  15168. */
  15169. Lexer.prototype.lex = function(src) {
  15170. src = src
  15171. .replace(/\r\n|\r/g, '\n')
  15172. .replace(/\t/g, ' ')
  15173. .replace(/\u00a0/g, ' ')
  15174. .replace(/\u2424/g, '\n');
  15175. return this.token(src, true);
  15176. };
  15177. /**
  15178. * Lexing
  15179. */
  15180. Lexer.prototype.token = function(src, top, bq) {
  15181. var src = src.replace(/^ +$/gm, '')
  15182. , next
  15183. , loose
  15184. , cap
  15185. , bull
  15186. , b
  15187. , item
  15188. , space
  15189. , i
  15190. , l;
  15191. while (src) {
  15192. // newline
  15193. if (cap = this.rules.newline.exec(src)) {
  15194. src = src.substring(cap[0].length);
  15195. if (cap[0].length > 1) {
  15196. this.tokens.push({
  15197. type: 'space'
  15198. });
  15199. }
  15200. }
  15201. // code
  15202. if (cap = this.rules.code.exec(src)) {
  15203. src = src.substring(cap[0].length);
  15204. cap = cap[0].replace(/^ {4}/gm, '');
  15205. this.tokens.push({
  15206. type: 'code',
  15207. text: !this.options.pedantic
  15208. ? cap.replace(/\n+$/, '')
  15209. : cap
  15210. });
  15211. continue;
  15212. }
  15213. // fences (gfm)
  15214. if (cap = this.rules.fences.exec(src)) {
  15215. src = src.substring(cap[0].length);
  15216. this.tokens.push({
  15217. type: 'code',
  15218. lang: cap[2],
  15219. text: cap[3] || ''
  15220. });
  15221. continue;
  15222. }
  15223. // heading
  15224. if (cap = this.rules.heading.exec(src)) {
  15225. src = src.substring(cap[0].length);
  15226. this.tokens.push({
  15227. type: 'heading',
  15228. depth: cap[1].length,
  15229. text: cap[2]
  15230. });
  15231. continue;
  15232. }
  15233. // table no leading pipe (gfm)
  15234. if (top && (cap = this.rules.nptable.exec(src))) {
  15235. src = src.substring(cap[0].length);
  15236. item = {
  15237. type: 'table',
  15238. header: cap[1].replace(/^ *| *\| *$/g, '').split(/ *\| */),
  15239. align: cap[2].replace(/^ *|\| *$/g, '').split(/ *\| */),
  15240. cells: cap[3].replace(/\n$/, '').split('\n')
  15241. };
  15242. for (i = 0; i < item.align.length; i++) {
  15243. if (/^ *-+: *$/.test(item.align[i])) {
  15244. item.align[i] = 'right';
  15245. } else if (/^ *:-+: *$/.test(item.align[i])) {
  15246. item.align[i] = 'center';
  15247. } else if (/^ *:-+ *$/.test(item.align[i])) {
  15248. item.align[i] = 'left';
  15249. } else {
  15250. item.align[i] = null;
  15251. }
  15252. }
  15253. for (i = 0; i < item.cells.length; i++) {
  15254. item.cells[i] = item.cells[i].split(/ *\| */);
  15255. }
  15256. this.tokens.push(item);
  15257. continue;
  15258. }
  15259. // lheading
  15260. if (cap = this.rules.lheading.exec(src)) {
  15261. src = src.substring(cap[0].length);
  15262. this.tokens.push({
  15263. type: 'heading',
  15264. depth: cap[2] === '=' ? 1 : 2,
  15265. text: cap[1]
  15266. });
  15267. continue;
  15268. }
  15269. // hr
  15270. if (cap = this.rules.hr.exec(src)) {
  15271. src = src.substring(cap[0].length);
  15272. this.tokens.push({
  15273. type: 'hr'
  15274. });
  15275. continue;
  15276. }
  15277. // blockquote
  15278. if (cap = this.rules.blockquote.exec(src)) {
  15279. src = src.substring(cap[0].length);
  15280. this.tokens.push({
  15281. type: 'blockquote_start'
  15282. });
  15283. cap = cap[0].replace(/^ *> ?/gm, '');
  15284. // Pass `top` to keep the current
  15285. // "toplevel" state. This is exactly
  15286. // how markdown.pl works.
  15287. this.token(cap, top, true);
  15288. this.tokens.push({
  15289. type: 'blockquote_end'
  15290. });
  15291. continue;
  15292. }
  15293. // list
  15294. if (cap = this.rules.list.exec(src)) {
  15295. src = src.substring(cap[0].length);
  15296. bull = cap[2];
  15297. this.tokens.push({
  15298. type: 'list_start',
  15299. ordered: bull.length > 1
  15300. });
  15301. // Get each top-level item.
  15302. cap = cap[0].match(this.rules.item);
  15303. next = false;
  15304. l = cap.length;
  15305. i = 0;
  15306. for (; i < l; i++) {
  15307. item = cap[i];
  15308. // Remove the list item's bullet
  15309. // so it is seen as the next token.
  15310. space = item.length;
  15311. item = item.replace(/^ *([*+-]|\d+\.) +/, '');
  15312. // Outdent whatever the
  15313. // list item contains. Hacky.
  15314. if (~item.indexOf('\n ')) {
  15315. space -= item.length;
  15316. item = !this.options.pedantic
  15317. ? item.replace(new RegExp('^ {1,' + space + '}', 'gm'), '')
  15318. : item.replace(/^ {1,4}/gm, '');
  15319. }
  15320. // Determine whether the next list item belongs here.
  15321. // Backpedal if it does not belong in this list.
  15322. if (this.options.smartLists && i !== l - 1) {
  15323. b = block.bullet.exec(cap[i + 1])[0];
  15324. if (bull !== b && !(bull.length > 1 && b.length > 1)) {
  15325. src = cap.slice(i + 1).join('\n') + src;
  15326. i = l - 1;
  15327. }
  15328. }
  15329. // Determine whether item is loose or not.
  15330. // Use: /(^|\n)(?! )[^\n]+\n\n(?!\s*$)/
  15331. // for discount behavior.
  15332. loose = next || /\n\n(?!\s*$)/.test(item);
  15333. if (i !== l - 1) {
  15334. next = item.charAt(item.length - 1) === '\n';
  15335. if (!loose) loose = next;
  15336. }
  15337. this.tokens.push({
  15338. type: loose
  15339. ? 'loose_item_start'
  15340. : 'list_item_start'
  15341. });
  15342. // Recurse.
  15343. this.token(item, false, bq);
  15344. this.tokens.push({
  15345. type: 'list_item_end'
  15346. });
  15347. }
  15348. this.tokens.push({
  15349. type: 'list_end'
  15350. });
  15351. continue;
  15352. }
  15353. // html
  15354. if (cap = this.rules.html.exec(src)) {
  15355. src = src.substring(cap[0].length);
  15356. this.tokens.push({
  15357. type: this.options.sanitize
  15358. ? 'paragraph'
  15359. : 'html',
  15360. pre: !this.options.sanitizer
  15361. && (cap[1] === 'pre' || cap[1] === 'script' || cap[1] === 'style'),
  15362. text: cap[0]
  15363. });
  15364. continue;
  15365. }
  15366. // def
  15367. if ((!bq && top) && (cap = this.rules.def.exec(src))) {
  15368. src = src.substring(cap[0].length);
  15369. this.tokens.links[cap[1].toLowerCase()] = {
  15370. href: cap[2],
  15371. title: cap[3]
  15372. };
  15373. continue;
  15374. }
  15375. // table (gfm)
  15376. if (top && (cap = this.rules.table.exec(src))) {
  15377. src = src.substring(cap[0].length);
  15378. item = {
  15379. type: 'table',
  15380. header: cap[1].replace(/^ *| *\| *$/g, '').split(/ *\| */),
  15381. align: cap[2].replace(/^ *|\| *$/g, '').split(/ *\| */),
  15382. cells: cap[3].replace(/(?: *\| *)?\n$/, '').split('\n')
  15383. };
  15384. for (i = 0; i < item.align.length; i++) {
  15385. if (/^ *-+: *$/.test(item.align[i])) {
  15386. item.align[i] = 'right';
  15387. } else if (/^ *:-+: *$/.test(item.align[i])) {
  15388. item.align[i] = 'center';
  15389. } else if (/^ *:-+ *$/.test(item.align[i])) {
  15390. item.align[i] = 'left';
  15391. } else {
  15392. item.align[i] = null;
  15393. }
  15394. }
  15395. for (i = 0; i < item.cells.length; i++) {
  15396. item.cells[i] = item.cells[i]
  15397. .replace(/^ *\| *| *\| *$/g, '')
  15398. .split(/ *\| */);
  15399. }
  15400. this.tokens.push(item);
  15401. continue;
  15402. }
  15403. // top-level paragraph
  15404. if (top && (cap = this.rules.paragraph.exec(src))) {
  15405. src = src.substring(cap[0].length);
  15406. this.tokens.push({
  15407. type: 'paragraph',
  15408. text: cap[1].charAt(cap[1].length - 1) === '\n'
  15409. ? cap[1].slice(0, -1)
  15410. : cap[1]
  15411. });
  15412. continue;
  15413. }
  15414. // text
  15415. if (cap = this.rules.text.exec(src)) {
  15416. // Top-level should never reach here.
  15417. src = src.substring(cap[0].length);
  15418. this.tokens.push({
  15419. type: 'text',
  15420. text: cap[0]
  15421. });
  15422. continue;
  15423. }
  15424. if (src) {
  15425. throw new
  15426. Error('Infinite loop on byte: ' + src.charCodeAt(0));
  15427. }
  15428. }
  15429. return this.tokens;
  15430. };
  15431. /**
  15432. * Inline-Level Grammar
  15433. */
  15434. var inline = {
  15435. escape: /^\\([\\`*{}\[\]()#+\-.!_>])/,
  15436. autolink: /^<([^ >]+(@|:\/)[^ >]+)>/,
  15437. url: noop,
  15438. tag: /^<!--[\s\S]*?-->|^<\/?\w+(?:"[^"]*"|'[^']*'|[^'">])*?>/,
  15439. link: /^!?\[(inside)\]\(href\)/,
  15440. reflink: /^!?\[(inside)\]\s*\[([^\]]*)\]/,
  15441. nolink: /^!?\[((?:\[[^\]]*\]|[^\[\]])*)\]/,
  15442. strong: /^__([\s\S]+?)__(?!_)|^\*\*([\s\S]+?)\*\*(?!\*)/,
  15443. em: /^\b_((?:[^_]|__)+?)_\b|^\*((?:\*\*|[\s\S])+?)\*(?!\*)/,
  15444. code: /^(`+)\s*([\s\S]*?[^`])\s*\1(?!`)/,
  15445. br: /^ {2,}\n(?!\s*$)/,
  15446. del: noop,
  15447. text: /^[\s\S]+?(?=[\\<!\[_*`]| {2,}\n|$)/
  15448. };
  15449. inline._inside = /(?:\[[^\]]*\]|[^\[\]]|\](?=[^\[]*\]))*/;
  15450. inline._href = /\s*<?([\s\S]*?)>?(?:\s+['"]([\s\S]*?)['"])?\s*/;
  15451. inline.link = replace(inline.link)
  15452. ('inside', inline._inside)
  15453. ('href', inline._href)
  15454. ();
  15455. inline.reflink = replace(inline.reflink)
  15456. ('inside', inline._inside)
  15457. ();
  15458. /**
  15459. * Normal Inline Grammar
  15460. */
  15461. inline.normal = merge({}, inline);
  15462. /**
  15463. * Pedantic Inline Grammar
  15464. */
  15465. inline.pedantic = merge({}, inline.normal, {
  15466. strong: /^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/,
  15467. em: /^_(?=\S)([\s\S]*?\S)_(?!_)|^\*(?=\S)([\s\S]*?\S)\*(?!\*)/
  15468. });
  15469. /**
  15470. * GFM Inline Grammar
  15471. */
  15472. inline.gfm = merge({}, inline.normal, {
  15473. escape: replace(inline.escape)('])', '~|])')(),
  15474. url: /^(https?:\/\/[^\s<]+[^<.,:;"')\]\s])/,
  15475. del: /^~~(?=\S)([\s\S]*?\S)~~/,
  15476. text: replace(inline.text)
  15477. (']|', '~]|')
  15478. ('|', '|https?://|')
  15479. ()
  15480. });
  15481. /**
  15482. * GFM + Line Breaks Inline Grammar
  15483. */
  15484. inline.breaks = merge({}, inline.gfm, {
  15485. br: replace(inline.br)('{2,}', '*')(),
  15486. text: replace(inline.gfm.text)('{2,}', '*')()
  15487. });
  15488. /**
  15489. * Inline Lexer & Compiler
  15490. */
  15491. function InlineLexer(links, options) {
  15492. this.options = options || marked.defaults;
  15493. this.links = links;
  15494. this.rules = inline.normal;
  15495. this.renderer = this.options.renderer || new Renderer;
  15496. this.renderer.options = this.options;
  15497. if (!this.links) {
  15498. throw new
  15499. Error('Tokens array requires a `links` property.');
  15500. }
  15501. if (this.options.gfm) {
  15502. if (this.options.breaks) {
  15503. this.rules = inline.breaks;
  15504. } else {
  15505. this.rules = inline.gfm;
  15506. }
  15507. } else if (this.options.pedantic) {
  15508. this.rules = inline.pedantic;
  15509. }
  15510. }
  15511. /**
  15512. * Expose Inline Rules
  15513. */
  15514. InlineLexer.rules = inline;
  15515. /**
  15516. * Static Lexing/Compiling Method
  15517. */
  15518. InlineLexer.output = function(src, links, options) {
  15519. var inline = new InlineLexer(links, options);
  15520. return inline.output(src);
  15521. };
  15522. /**
  15523. * Lexing/Compiling
  15524. */
  15525. InlineLexer.prototype.output = function(src) {
  15526. var out = ''
  15527. , link
  15528. , text
  15529. , href
  15530. , cap;
  15531. while (src) {
  15532. // escape
  15533. if (cap = this.rules.escape.exec(src)) {
  15534. src = src.substring(cap[0].length);
  15535. out += cap[1];
  15536. continue;
  15537. }
  15538. // autolink
  15539. if (cap = this.rules.autolink.exec(src)) {
  15540. src = src.substring(cap[0].length);
  15541. if (cap[2] === '@') {
  15542. text = cap[1].charAt(6) === ':'
  15543. ? this.mangle(cap[1].substring(7))
  15544. : this.mangle(cap[1]);
  15545. href = this.mangle('mailto:') + text;
  15546. } else {
  15547. text = escape(cap[1]);
  15548. href = text;
  15549. }
  15550. out += this.renderer.link(href, null, text);
  15551. continue;
  15552. }
  15553. // url (gfm)
  15554. if (!this.inLink && (cap = this.rules.url.exec(src))) {
  15555. src = src.substring(cap[0].length);
  15556. text = escape(cap[1]);
  15557. href = text;
  15558. out += this.renderer.link(href, null, text);
  15559. continue;
  15560. }
  15561. // tag
  15562. if (cap = this.rules.tag.exec(src)) {
  15563. if (!this.inLink && /^<a /i.test(cap[0])) {
  15564. this.inLink = true;
  15565. } else if (this.inLink && /^<\/a>/i.test(cap[0])) {
  15566. this.inLink = false;
  15567. }
  15568. src = src.substring(cap[0].length);
  15569. out += this.options.sanitize
  15570. ? this.options.sanitizer
  15571. ? this.options.sanitizer(cap[0])
  15572. : escape(cap[0])
  15573. : cap[0]
  15574. continue;
  15575. }
  15576. // link
  15577. if (cap = this.rules.link.exec(src)) {
  15578. src = src.substring(cap[0].length);
  15579. this.inLink = true;
  15580. out += this.outputLink(cap, {
  15581. href: cap[2],
  15582. title: cap[3]
  15583. });
  15584. this.inLink = false;
  15585. continue;
  15586. }
  15587. // reflink, nolink
  15588. if ((cap = this.rules.reflink.exec(src))
  15589. || (cap = this.rules.nolink.exec(src))) {
  15590. src = src.substring(cap[0].length);
  15591. link = (cap[2] || cap[1]).replace(/\s+/g, ' ');
  15592. link = this.links[link.toLowerCase()];
  15593. if (!link || !link.href) {
  15594. out += cap[0].charAt(0);
  15595. src = cap[0].substring(1) + src;
  15596. continue;
  15597. }
  15598. this.inLink = true;
  15599. out += this.outputLink(cap, link);
  15600. this.inLink = false;
  15601. continue;
  15602. }
  15603. // strong
  15604. if (cap = this.rules.strong.exec(src)) {
  15605. src = src.substring(cap[0].length);
  15606. out += this.renderer.strong(this.output(cap[2] || cap[1]));
  15607. continue;
  15608. }
  15609. // em
  15610. if (cap = this.rules.em.exec(src)) {
  15611. src = src.substring(cap[0].length);
  15612. out += this.renderer.em(this.output(cap[2] || cap[1]));
  15613. continue;
  15614. }
  15615. // code
  15616. if (cap = this.rules.code.exec(src)) {
  15617. src = src.substring(cap[0].length);
  15618. out += this.renderer.codespan(escape(cap[2], true));
  15619. continue;
  15620. }
  15621. // br
  15622. if (cap = this.rules.br.exec(src)) {
  15623. src = src.substring(cap[0].length);
  15624. out += this.renderer.br();
  15625. continue;
  15626. }
  15627. // del (gfm)
  15628. if (cap = this.rules.del.exec(src)) {
  15629. src = src.substring(cap[0].length);
  15630. out += this.renderer.del(this.output(cap[1]));
  15631. continue;
  15632. }
  15633. // text
  15634. if (cap = this.rules.text.exec(src)) {
  15635. src = src.substring(cap[0].length);
  15636. out += this.renderer.text(escape(this.smartypants(cap[0])));
  15637. continue;
  15638. }
  15639. if (src) {
  15640. throw new
  15641. Error('Infinite loop on byte: ' + src.charCodeAt(0));
  15642. }
  15643. }
  15644. return out;
  15645. };
  15646. /**
  15647. * Compile Link
  15648. */
  15649. InlineLexer.prototype.outputLink = function(cap, link) {
  15650. var href = escape(link.href)
  15651. , title = link.title ? escape(link.title) : null;
  15652. return cap[0].charAt(0) !== '!'
  15653. ? this.renderer.link(href, title, this.output(cap[1]))
  15654. : this.renderer.image(href, title, escape(cap[1]));
  15655. };
  15656. /**
  15657. * Smartypants Transformations
  15658. */
  15659. InlineLexer.prototype.smartypants = function(text) {
  15660. if (!this.options.smartypants) return text;
  15661. return text
  15662. // em-dashes
  15663. .replace(/---/g, '\u2014')
  15664. // en-dashes
  15665. .replace(/--/g, '\u2013')
  15666. // opening singles
  15667. .replace(/(^|[-\u2014/(\[{"\s])'/g, '$1\u2018')
  15668. // closing singles & apostrophes
  15669. .replace(/'/g, '\u2019')
  15670. // opening doubles
  15671. .replace(/(^|[-\u2014/(\[{\u2018\s])"/g, '$1\u201c')
  15672. // closing doubles
  15673. .replace(/"/g, '\u201d')
  15674. // ellipses
  15675. .replace(/\.{3}/g, '\u2026');
  15676. };
  15677. /**
  15678. * Mangle Links
  15679. */
  15680. InlineLexer.prototype.mangle = function(text) {
  15681. if (!this.options.mangle) return text;
  15682. var out = ''
  15683. , l = text.length
  15684. , i = 0
  15685. , ch;
  15686. for (; i < l; i++) {
  15687. ch = text.charCodeAt(i);
  15688. if (Math.random() > 0.5) {
  15689. ch = 'x' + ch.toString(16);
  15690. }
  15691. out += '&#' + ch + ';';
  15692. }
  15693. return out;
  15694. };
  15695. /**
  15696. * Renderer
  15697. */
  15698. function Renderer(options) {
  15699. this.options = options || {};
  15700. }
  15701. Renderer.prototype.code = function(code, lang, escaped) {
  15702. if (this.options.highlight) {
  15703. var out = this.options.highlight(code, lang);
  15704. if (out != null && out !== code) {
  15705. escaped = true;
  15706. code = out;
  15707. }
  15708. }
  15709. if (!lang) {
  15710. return '<pre><code>'
  15711. + (escaped ? code : escape(code, true))
  15712. + '\n</code></pre>';
  15713. }
  15714. return '<pre><code class="'
  15715. + this.options.langPrefix
  15716. + escape(lang, true)
  15717. + '">'
  15718. + (escaped ? code : escape(code, true))
  15719. + '\n</code></pre>\n';
  15720. };
  15721. Renderer.prototype.blockquote = function(quote) {
  15722. return '<blockquote>\n' + quote + '</blockquote>\n';
  15723. };
  15724. Renderer.prototype.html = function(html) {
  15725. return html;
  15726. };
  15727. Renderer.prototype.heading = function(text, level, raw) {
  15728. return '<h'
  15729. + level
  15730. + ' id="'
  15731. + this.options.headerPrefix
  15732. + raw.toLowerCase().replace(/[^\w]+/g, '-')
  15733. + '">'
  15734. + text
  15735. + '</h'
  15736. + level
  15737. + '>\n';
  15738. };
  15739. Renderer.prototype.hr = function() {
  15740. return this.options.xhtml ? '<hr/>\n' : '<hr>\n';
  15741. };
  15742. Renderer.prototype.list = function(body, ordered) {
  15743. var type = ordered ? 'ol' : 'ul';
  15744. return '<' + type + '>\n' + body + '</' + type + '>\n';
  15745. };
  15746. Renderer.prototype.listitem = function(text) {
  15747. return '<li>' + text + '</li>\n';
  15748. };
  15749. Renderer.prototype.paragraph = function(text) {
  15750. return '<p>' + text + '</p>\n';
  15751. };
  15752. Renderer.prototype.table = function(header, body) {
  15753. return '<table>\n'
  15754. + '<thead>\n'
  15755. + header
  15756. + '</thead>\n'
  15757. + '<tbody>\n'
  15758. + body
  15759. + '</tbody>\n'
  15760. + '</table>\n';
  15761. };
  15762. Renderer.prototype.tablerow = function(content) {
  15763. return '<tr>\n' + content + '</tr>\n';
  15764. };
  15765. Renderer.prototype.tablecell = function(content, flags) {
  15766. var type = flags.header ? 'th' : 'td';
  15767. var tag = flags.align
  15768. ? '<' + type + ' style="text-align:' + flags.align + '">'
  15769. : '<' + type + '>';
  15770. return tag + content + '</' + type + '>\n';
  15771. };
  15772. // span level renderer
  15773. Renderer.prototype.strong = function(text) {
  15774. return '<strong>' + text + '</strong>';
  15775. };
  15776. Renderer.prototype.em = function(text) {
  15777. return '<em>' + text + '</em>';
  15778. };
  15779. Renderer.prototype.codespan = function(text) {
  15780. return '<code>' + text + '</code>';
  15781. };
  15782. Renderer.prototype.br = function() {
  15783. return this.options.xhtml ? '<br/>' : '<br>';
  15784. };
  15785. Renderer.prototype.del = function(text) {
  15786. return '<del>' + text + '</del>';
  15787. };
  15788. Renderer.prototype.link = function(href, title, text) {
  15789. if (this.options.sanitize) {
  15790. try {
  15791. var prot = decodeURIComponent(unescape(href))
  15792. .replace(/[^\w:]/g, '')
  15793. .toLowerCase();
  15794. } catch (e) {
  15795. return '';
  15796. }
  15797. if (prot.indexOf('javascript:') === 0 || prot.indexOf('vbscript:') === 0 || prot.indexOf('data:') === 0) {
  15798. return '';
  15799. }
  15800. }
  15801. var out = '<a href="' + href + '"';
  15802. if (title) {
  15803. out += ' title="' + title + '"';
  15804. }
  15805. out += '>' + text + '</a>';
  15806. return out;
  15807. };
  15808. Renderer.prototype.image = function(href, title, text) {
  15809. var out = '<img src="' + href + '" alt="' + text + '"';
  15810. if (title) {
  15811. out += ' title="' + title + '"';
  15812. }
  15813. out += this.options.xhtml ? '/>' : '>';
  15814. return out;
  15815. };
  15816. Renderer.prototype.text = function(text) {
  15817. return text;
  15818. };
  15819. /**
  15820. * Parsing & Compiling
  15821. */
  15822. function Parser(options) {
  15823. this.tokens = [];
  15824. this.token = null;
  15825. this.options = options || marked.defaults;
  15826. this.options.renderer = this.options.renderer || new Renderer;
  15827. this.renderer = this.options.renderer;
  15828. this.renderer.options = this.options;
  15829. }
  15830. /**
  15831. * Static Parse Method
  15832. */
  15833. Parser.parse = function(src, options, renderer) {
  15834. var parser = new Parser(options, renderer);
  15835. return parser.parse(src);
  15836. };
  15837. /**
  15838. * Parse Loop
  15839. */
  15840. Parser.prototype.parse = function(src) {
  15841. this.inline = new InlineLexer(src.links, this.options, this.renderer);
  15842. this.tokens = src.reverse();
  15843. var out = '';
  15844. while (this.next()) {
  15845. out += this.tok();
  15846. }
  15847. return out;
  15848. };
  15849. /**
  15850. * Next Token
  15851. */
  15852. Parser.prototype.next = function() {
  15853. return this.token = this.tokens.pop();
  15854. };
  15855. /**
  15856. * Preview Next Token
  15857. */
  15858. Parser.prototype.peek = function() {
  15859. return this.tokens[this.tokens.length - 1] || 0;
  15860. };
  15861. /**
  15862. * Parse Text Tokens
  15863. */
  15864. Parser.prototype.parseText = function() {
  15865. var body = this.token.text;
  15866. while (this.peek().type === 'text') {
  15867. body += '\n' + this.next().text;
  15868. }
  15869. return this.inline.output(body);
  15870. };
  15871. /**
  15872. * Parse Current Token
  15873. */
  15874. Parser.prototype.tok = function() {
  15875. switch (this.token.type) {
  15876. case 'space': {
  15877. return '';
  15878. }
  15879. case 'hr': {
  15880. return this.renderer.hr();
  15881. }
  15882. case 'heading': {
  15883. return this.renderer.heading(
  15884. this.inline.output(this.token.text),
  15885. this.token.depth,
  15886. this.token.text);
  15887. }
  15888. case 'code': {
  15889. return this.renderer.code(this.token.text,
  15890. this.token.lang,
  15891. this.token.escaped);
  15892. }
  15893. case 'table': {
  15894. var header = ''
  15895. , body = ''
  15896. , i
  15897. , row
  15898. , cell
  15899. , flags
  15900. , j;
  15901. // header
  15902. cell = '';
  15903. for (i = 0; i < this.token.header.length; i++) {
  15904. flags = { header: true, align: this.token.align[i] };
  15905. cell += this.renderer.tablecell(
  15906. this.inline.output(this.token.header[i]),
  15907. { header: true, align: this.token.align[i] }
  15908. );
  15909. }
  15910. header += this.renderer.tablerow(cell);
  15911. for (i = 0; i < this.token.cells.length; i++) {
  15912. row = this.token.cells[i];
  15913. cell = '';
  15914. for (j = 0; j < row.length; j++) {
  15915. cell += this.renderer.tablecell(
  15916. this.inline.output(row[j]),
  15917. { header: false, align: this.token.align[j] }
  15918. );
  15919. }
  15920. body += this.renderer.tablerow(cell);
  15921. }
  15922. return this.renderer.table(header, body);
  15923. }
  15924. case 'blockquote_start': {
  15925. var body = '';
  15926. while (this.next().type !== 'blockquote_end') {
  15927. body += this.tok();
  15928. }
  15929. return this.renderer.blockquote(body);
  15930. }
  15931. case 'list_start': {
  15932. var body = ''
  15933. , ordered = this.token.ordered;
  15934. while (this.next().type !== 'list_end') {
  15935. body += this.tok();
  15936. }
  15937. return this.renderer.list(body, ordered);
  15938. }
  15939. case 'list_item_start': {
  15940. var body = '';
  15941. while (this.next().type !== 'list_item_end') {
  15942. body += this.token.type === 'text'
  15943. ? this.parseText()
  15944. : this.tok();
  15945. }
  15946. return this.renderer.listitem(body);
  15947. }
  15948. case 'loose_item_start': {
  15949. var body = '';
  15950. while (this.next().type !== 'list_item_end') {
  15951. body += this.tok();
  15952. }
  15953. return this.renderer.listitem(body);
  15954. }
  15955. case 'html': {
  15956. var html = !this.token.pre && !this.options.pedantic
  15957. ? this.inline.output(this.token.text)
  15958. : this.token.text;
  15959. return this.renderer.html(html);
  15960. }
  15961. case 'paragraph': {
  15962. return this.renderer.paragraph(this.inline.output(this.token.text));
  15963. }
  15964. case 'text': {
  15965. return this.renderer.paragraph(this.parseText());
  15966. }
  15967. }
  15968. };
  15969. /**
  15970. * Helpers
  15971. */
  15972. function escape(html, encode) {
  15973. return html
  15974. .replace(!encode ? /&(?!#?\w+;)/g : /&/g, '&amp;')
  15975. .replace(/</g, '&lt;')
  15976. .replace(/>/g, '&gt;')
  15977. .replace(/"/g, '&quot;')
  15978. .replace(/'/g, '&#39;');
  15979. }
  15980. function unescape(html) {
  15981. // explicitly match decimal, hex, and named HTML entities
  15982. return html.replace(/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/g, function(_, n) {
  15983. n = n.toLowerCase();
  15984. if (n === 'colon') return ':';
  15985. if (n.charAt(0) === '#') {
  15986. return n.charAt(1) === 'x'
  15987. ? String.fromCharCode(parseInt(n.substring(2), 16))
  15988. : String.fromCharCode(+n.substring(1));
  15989. }
  15990. return '';
  15991. });
  15992. }
  15993. function replace(regex, opt) {
  15994. regex = regex.source;
  15995. opt = opt || '';
  15996. return function self(name, val) {
  15997. if (!name) return new RegExp(regex, opt);
  15998. val = val.source || val;
  15999. val = val.replace(/(^|[^\[])\^/g, '$1');
  16000. regex = regex.replace(name, val);
  16001. return self;
  16002. };
  16003. }
  16004. function noop() {}
  16005. noop.exec = noop;
  16006. function merge(obj) {
  16007. var i = 1
  16008. , target
  16009. , key;
  16010. for (; i < arguments.length; i++) {
  16011. target = arguments[i];
  16012. for (key in target) {
  16013. if (Object.prototype.hasOwnProperty.call(target, key)) {
  16014. obj[key] = target[key];
  16015. }
  16016. }
  16017. }
  16018. return obj;
  16019. }
  16020. /**
  16021. * Marked
  16022. */
  16023. function marked(src, opt, callback) {
  16024. if (callback || typeof opt === 'function') {
  16025. if (!callback) {
  16026. callback = opt;
  16027. opt = null;
  16028. }
  16029. opt = merge({}, marked.defaults, opt || {});
  16030. var highlight = opt.highlight
  16031. , tokens
  16032. , pending
  16033. , i = 0;
  16034. try {
  16035. tokens = Lexer.lex(src, opt)
  16036. } catch (e) {
  16037. return callback(e);
  16038. }
  16039. pending = tokens.length;
  16040. var done = function(err) {
  16041. if (err) {
  16042. opt.highlight = highlight;
  16043. return callback(err);
  16044. }
  16045. var out;
  16046. try {
  16047. out = Parser.parse(tokens, opt);
  16048. } catch (e) {
  16049. err = e;
  16050. }
  16051. opt.highlight = highlight;
  16052. return err
  16053. ? callback(err)
  16054. : callback(null, out);
  16055. };
  16056. if (!highlight || highlight.length < 3) {
  16057. return done();
  16058. }
  16059. delete opt.highlight;
  16060. if (!pending) return done();
  16061. for (; i < tokens.length; i++) {
  16062. (function(token) {
  16063. if (token.type !== 'code') {
  16064. return --pending || done();
  16065. }
  16066. return highlight(token.text, token.lang, function(err, code) {
  16067. if (err) return done(err);
  16068. if (code == null || code === token.text) {
  16069. return --pending || done();
  16070. }
  16071. token.text = code;
  16072. token.escaped = true;
  16073. --pending || done();
  16074. });
  16075. })(tokens[i]);
  16076. }
  16077. return;
  16078. }
  16079. try {
  16080. if (opt) opt = merge({}, marked.defaults, opt);
  16081. return Parser.parse(Lexer.lex(src, opt), opt);
  16082. } catch (e) {
  16083. e.message += '\nPlease report this to https://github.com/chjj/marked.';
  16084. if ((opt || marked.defaults).silent) {
  16085. return '<p>An error occured:</p><pre>'
  16086. + escape(e.message + '', true)
  16087. + '</pre>';
  16088. }
  16089. throw e;
  16090. }
  16091. }
  16092. /**
  16093. * Options
  16094. */
  16095. marked.options =
  16096. marked.setOptions = function(opt) {
  16097. merge(marked.defaults, opt);
  16098. return marked;
  16099. };
  16100. marked.defaults = {
  16101. gfm: true,
  16102. tables: true,
  16103. breaks: false,
  16104. pedantic: false,
  16105. sanitize: false,
  16106. sanitizer: null,
  16107. mangle: true,
  16108. smartLists: false,
  16109. silent: false,
  16110. highlight: null,
  16111. langPrefix: 'lang-',
  16112. smartypants: false,
  16113. headerPrefix: '',
  16114. renderer: new Renderer,
  16115. xhtml: false
  16116. };
  16117. /**
  16118. * Expose
  16119. */
  16120. marked.Parser = Parser;
  16121. marked.parser = Parser.parse;
  16122. marked.Renderer = Renderer;
  16123. marked.Lexer = Lexer;
  16124. marked.lexer = Lexer.lex;
  16125. marked.InlineLexer = InlineLexer;
  16126. marked.inlineLexer = InlineLexer.output;
  16127. marked.parse = marked;
  16128. if (true) {
  16129. module.exports = marked;
  16130. } else if (typeof define === 'function' && define.amd) {
  16131. define(function() { return marked; });
  16132. } else {
  16133. this.marked = marked;
  16134. }
  16135. }).call(function() {
  16136. return this || (typeof window !== 'undefined' ? window : global);
  16137. }());
  16138. /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }())))
  16139. /***/ })
  16140. /******/ ])
  16141. });
  16142. ;
  16143. //# sourceMappingURL=simplemde-editor.js.map