react-simplemde-editor.min.js 774 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949
  1. (function webpackUniversalModuleDefinition(root, factory) {
  2. if(typeof exports === 'object' && typeof module === 'object')
  3. module.exports = factory();
  4. else if(typeof define === 'function' && define.amd)
  5. define([], factory);
  6. else {
  7. var a = factory();
  8. for(var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i];
  9. }
  10. })(this, function() {
  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__(37);
  59. var NOOP = __webpack_require__(38);
  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__(39);
  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, __webpack_require__) {
  139. 'use strict';
  140. module.exports = __webpack_require__(2);
  141. /***/ }),
  142. /* 2 */
  143. /***/ (function(module, exports, __webpack_require__) {
  144. /* WEBPACK VAR INJECTION */(function(process) {/**
  145. * Copyright (c) 2013-present, Facebook, Inc.
  146. *
  147. * This source code is licensed under the MIT license found in the
  148. * LICENSE file in the root directory of this source tree.
  149. *
  150. */
  151. 'use strict';
  152. var _assign = __webpack_require__(4);
  153. var ReactBaseClasses = __webpack_require__(5);
  154. var ReactChildren = __webpack_require__(14);
  155. var ReactDOMFactories = __webpack_require__(22);
  156. var ReactElement = __webpack_require__(16);
  157. var ReactPropTypes = __webpack_require__(28);
  158. var ReactVersion = __webpack_require__(33);
  159. var createReactClass = __webpack_require__(34);
  160. var onlyChild = __webpack_require__(36);
  161. var createElement = ReactElement.createElement;
  162. var createFactory = ReactElement.createFactory;
  163. var cloneElement = ReactElement.cloneElement;
  164. if (process.env.NODE_ENV !== 'production') {
  165. var lowPriorityWarning = __webpack_require__(13);
  166. var canDefineProperty = __webpack_require__(10);
  167. var ReactElementValidator = __webpack_require__(23);
  168. var didWarnPropTypesDeprecated = false;
  169. createElement = ReactElementValidator.createElement;
  170. createFactory = ReactElementValidator.createFactory;
  171. cloneElement = ReactElementValidator.cloneElement;
  172. }
  173. var __spread = _assign;
  174. var createMixin = function (mixin) {
  175. return mixin;
  176. };
  177. if (process.env.NODE_ENV !== 'production') {
  178. var warnedForSpread = false;
  179. var warnedForCreateMixin = false;
  180. __spread = function () {
  181. lowPriorityWarning(warnedForSpread, 'React.__spread is deprecated and should not be used. Use ' + 'Object.assign directly or another helper function with similar ' + 'semantics. You may be seeing this warning due to your compiler. ' + 'See https://fb.me/react-spread-deprecation for more details.');
  182. warnedForSpread = true;
  183. return _assign.apply(null, arguments);
  184. };
  185. createMixin = function (mixin) {
  186. lowPriorityWarning(warnedForCreateMixin, 'React.createMixin is deprecated and should not be used. ' + 'In React v16.0, it will be removed. ' + 'You can use this mixin directly instead. ' + 'See https://fb.me/createmixin-was-never-implemented for more info.');
  187. warnedForCreateMixin = true;
  188. return mixin;
  189. };
  190. }
  191. var React = {
  192. // Modern
  193. Children: {
  194. map: ReactChildren.map,
  195. forEach: ReactChildren.forEach,
  196. count: ReactChildren.count,
  197. toArray: ReactChildren.toArray,
  198. only: onlyChild
  199. },
  200. Component: ReactBaseClasses.Component,
  201. PureComponent: ReactBaseClasses.PureComponent,
  202. createElement: createElement,
  203. cloneElement: cloneElement,
  204. isValidElement: ReactElement.isValidElement,
  205. // Classic
  206. PropTypes: ReactPropTypes,
  207. createClass: createReactClass,
  208. createFactory: createFactory,
  209. createMixin: createMixin,
  210. // This looks DOM specific but these are actually isomorphic helpers
  211. // since they are just generating DOM strings.
  212. DOM: ReactDOMFactories,
  213. version: ReactVersion,
  214. // Deprecated hook for JSX spread, don't use this for anything.
  215. __spread: __spread
  216. };
  217. if (process.env.NODE_ENV !== 'production') {
  218. var warnedForCreateClass = false;
  219. if (canDefineProperty) {
  220. Object.defineProperty(React, 'PropTypes', {
  221. get: function () {
  222. lowPriorityWarning(didWarnPropTypesDeprecated, 'Accessing PropTypes via the main React package is deprecated,' + ' and will be removed in React v16.0.' + ' Use the latest available v15.* prop-types package from npm instead.' + ' For info on usage, compatibility, migration and more, see ' + 'https://fb.me/prop-types-docs');
  223. didWarnPropTypesDeprecated = true;
  224. return ReactPropTypes;
  225. }
  226. });
  227. Object.defineProperty(React, 'createClass', {
  228. get: function () {
  229. lowPriorityWarning(warnedForCreateClass, 'Accessing createClass via the main React package is deprecated,' + ' and will be removed in React v16.0.' + " Use a plain JavaScript class instead. If you're not yet " + 'ready to migrate, create-react-class v15.* is available ' + 'on npm as a temporary, drop-in replacement. ' + 'For more info see https://fb.me/react-create-class');
  230. warnedForCreateClass = true;
  231. return createReactClass;
  232. }
  233. });
  234. }
  235. // React.DOM factories are deprecated. Wrap these methods so that
  236. // invocations of the React.DOM namespace and alert users to switch
  237. // to the `react-dom-factories` package.
  238. React.DOM = {};
  239. var warnedForFactories = false;
  240. Object.keys(ReactDOMFactories).forEach(function (factory) {
  241. React.DOM[factory] = function () {
  242. if (!warnedForFactories) {
  243. lowPriorityWarning(false, 'Accessing factories like React.DOM.%s has been deprecated ' + 'and will be removed in v16.0+. Use the ' + 'react-dom-factories package instead. ' + ' Version 1.0 provides a drop-in replacement.' + ' For more info, see https://fb.me/react-dom-factories', factory);
  244. warnedForFactories = true;
  245. }
  246. return ReactDOMFactories[factory].apply(ReactDOMFactories, arguments);
  247. };
  248. });
  249. }
  250. module.exports = React;
  251. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
  252. /***/ }),
  253. /* 3 */
  254. /***/ (function(module, exports) {
  255. // shim for using process in browser
  256. var process = module.exports = {};
  257. // cached from whatever global is present so that test runners that stub it
  258. // don't break things. But we need to wrap it in a try catch in case it is
  259. // wrapped in strict mode code which doesn't define any globals. It's inside a
  260. // function because try/catches deoptimize in certain engines.
  261. var cachedSetTimeout;
  262. var cachedClearTimeout;
  263. function defaultSetTimout() {
  264. throw new Error('setTimeout has not been defined');
  265. }
  266. function defaultClearTimeout () {
  267. throw new Error('clearTimeout has not been defined');
  268. }
  269. (function () {
  270. try {
  271. if (typeof setTimeout === 'function') {
  272. cachedSetTimeout = setTimeout;
  273. } else {
  274. cachedSetTimeout = defaultSetTimout;
  275. }
  276. } catch (e) {
  277. cachedSetTimeout = defaultSetTimout;
  278. }
  279. try {
  280. if (typeof clearTimeout === 'function') {
  281. cachedClearTimeout = clearTimeout;
  282. } else {
  283. cachedClearTimeout = defaultClearTimeout;
  284. }
  285. } catch (e) {
  286. cachedClearTimeout = defaultClearTimeout;
  287. }
  288. } ())
  289. function runTimeout(fun) {
  290. if (cachedSetTimeout === setTimeout) {
  291. //normal enviroments in sane situations
  292. return setTimeout(fun, 0);
  293. }
  294. // if setTimeout wasn't available but was latter defined
  295. if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
  296. cachedSetTimeout = setTimeout;
  297. return setTimeout(fun, 0);
  298. }
  299. try {
  300. // when when somebody has screwed with setTimeout but no I.E. maddness
  301. return cachedSetTimeout(fun, 0);
  302. } catch(e){
  303. try {
  304. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  305. return cachedSetTimeout.call(null, fun, 0);
  306. } catch(e){
  307. // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
  308. return cachedSetTimeout.call(this, fun, 0);
  309. }
  310. }
  311. }
  312. function runClearTimeout(marker) {
  313. if (cachedClearTimeout === clearTimeout) {
  314. //normal enviroments in sane situations
  315. return clearTimeout(marker);
  316. }
  317. // if clearTimeout wasn't available but was latter defined
  318. if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
  319. cachedClearTimeout = clearTimeout;
  320. return clearTimeout(marker);
  321. }
  322. try {
  323. // when when somebody has screwed with setTimeout but no I.E. maddness
  324. return cachedClearTimeout(marker);
  325. } catch (e){
  326. try {
  327. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  328. return cachedClearTimeout.call(null, marker);
  329. } catch (e){
  330. // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
  331. // Some versions of I.E. have different rules for clearTimeout vs setTimeout
  332. return cachedClearTimeout.call(this, marker);
  333. }
  334. }
  335. }
  336. var queue = [];
  337. var draining = false;
  338. var currentQueue;
  339. var queueIndex = -1;
  340. function cleanUpNextTick() {
  341. if (!draining || !currentQueue) {
  342. return;
  343. }
  344. draining = false;
  345. if (currentQueue.length) {
  346. queue = currentQueue.concat(queue);
  347. } else {
  348. queueIndex = -1;
  349. }
  350. if (queue.length) {
  351. drainQueue();
  352. }
  353. }
  354. function drainQueue() {
  355. if (draining) {
  356. return;
  357. }
  358. var timeout = runTimeout(cleanUpNextTick);
  359. draining = true;
  360. var len = queue.length;
  361. while(len) {
  362. currentQueue = queue;
  363. queue = [];
  364. while (++queueIndex < len) {
  365. if (currentQueue) {
  366. currentQueue[queueIndex].run();
  367. }
  368. }
  369. queueIndex = -1;
  370. len = queue.length;
  371. }
  372. currentQueue = null;
  373. draining = false;
  374. runClearTimeout(timeout);
  375. }
  376. process.nextTick = function (fun) {
  377. var args = new Array(arguments.length - 1);
  378. if (arguments.length > 1) {
  379. for (var i = 1; i < arguments.length; i++) {
  380. args[i - 1] = arguments[i];
  381. }
  382. }
  383. queue.push(new Item(fun, args));
  384. if (queue.length === 1 && !draining) {
  385. runTimeout(drainQueue);
  386. }
  387. };
  388. // v8 likes predictible objects
  389. function Item(fun, array) {
  390. this.fun = fun;
  391. this.array = array;
  392. }
  393. Item.prototype.run = function () {
  394. this.fun.apply(null, this.array);
  395. };
  396. process.title = 'browser';
  397. process.browser = true;
  398. process.env = {};
  399. process.argv = [];
  400. process.version = ''; // empty string to avoid regexp issues
  401. process.versions = {};
  402. function noop() {}
  403. process.on = noop;
  404. process.addListener = noop;
  405. process.once = noop;
  406. process.off = noop;
  407. process.removeListener = noop;
  408. process.removeAllListeners = noop;
  409. process.emit = noop;
  410. process.prependListener = noop;
  411. process.prependOnceListener = noop;
  412. process.listeners = function (name) { return [] }
  413. process.binding = function (name) {
  414. throw new Error('process.binding is not supported');
  415. };
  416. process.cwd = function () { return '/' };
  417. process.chdir = function (dir) {
  418. throw new Error('process.chdir is not supported');
  419. };
  420. process.umask = function() { return 0; };
  421. /***/ }),
  422. /* 4 */
  423. /***/ (function(module, exports) {
  424. /*
  425. object-assign
  426. (c) Sindre Sorhus
  427. @license MIT
  428. */
  429. 'use strict';
  430. /* eslint-disable no-unused-vars */
  431. var getOwnPropertySymbols = Object.getOwnPropertySymbols;
  432. var hasOwnProperty = Object.prototype.hasOwnProperty;
  433. var propIsEnumerable = Object.prototype.propertyIsEnumerable;
  434. function toObject(val) {
  435. if (val === null || val === undefined) {
  436. throw new TypeError('Object.assign cannot be called with null or undefined');
  437. }
  438. return Object(val);
  439. }
  440. function shouldUseNative() {
  441. try {
  442. if (!Object.assign) {
  443. return false;
  444. }
  445. // Detect buggy property enumeration order in older V8 versions.
  446. // https://bugs.chromium.org/p/v8/issues/detail?id=4118
  447. var test1 = new String('abc'); // eslint-disable-line no-new-wrappers
  448. test1[5] = 'de';
  449. if (Object.getOwnPropertyNames(test1)[0] === '5') {
  450. return false;
  451. }
  452. // https://bugs.chromium.org/p/v8/issues/detail?id=3056
  453. var test2 = {};
  454. for (var i = 0; i < 10; i++) {
  455. test2['_' + String.fromCharCode(i)] = i;
  456. }
  457. var order2 = Object.getOwnPropertyNames(test2).map(function (n) {
  458. return test2[n];
  459. });
  460. if (order2.join('') !== '0123456789') {
  461. return false;
  462. }
  463. // https://bugs.chromium.org/p/v8/issues/detail?id=3056
  464. var test3 = {};
  465. 'abcdefghijklmnopqrst'.split('').forEach(function (letter) {
  466. test3[letter] = letter;
  467. });
  468. if (Object.keys(Object.assign({}, test3)).join('') !==
  469. 'abcdefghijklmnopqrst') {
  470. return false;
  471. }
  472. return true;
  473. } catch (err) {
  474. // We don't expect any of the above to throw, but better to be safe.
  475. return false;
  476. }
  477. }
  478. module.exports = shouldUseNative() ? Object.assign : function (target, source) {
  479. var from;
  480. var to = toObject(target);
  481. var symbols;
  482. for (var s = 1; s < arguments.length; s++) {
  483. from = Object(arguments[s]);
  484. for (var key in from) {
  485. if (hasOwnProperty.call(from, key)) {
  486. to[key] = from[key];
  487. }
  488. }
  489. if (getOwnPropertySymbols) {
  490. symbols = getOwnPropertySymbols(from);
  491. for (var i = 0; i < symbols.length; i++) {
  492. if (propIsEnumerable.call(from, symbols[i])) {
  493. to[symbols[i]] = from[symbols[i]];
  494. }
  495. }
  496. }
  497. }
  498. return to;
  499. };
  500. /***/ }),
  501. /* 5 */
  502. /***/ (function(module, exports, __webpack_require__) {
  503. /* WEBPACK VAR INJECTION */(function(process) {/**
  504. * Copyright (c) 2013-present, Facebook, Inc.
  505. *
  506. * This source code is licensed under the MIT license found in the
  507. * LICENSE file in the root directory of this source tree.
  508. *
  509. */
  510. 'use strict';
  511. var _prodInvariant = __webpack_require__(6),
  512. _assign = __webpack_require__(4);
  513. var ReactNoopUpdateQueue = __webpack_require__(7);
  514. var canDefineProperty = __webpack_require__(10);
  515. var emptyObject = __webpack_require__(11);
  516. var invariant = __webpack_require__(12);
  517. var lowPriorityWarning = __webpack_require__(13);
  518. /**
  519. * Base class helpers for the updating state of a component.
  520. */
  521. function ReactComponent(props, context, updater) {
  522. this.props = props;
  523. this.context = context;
  524. this.refs = emptyObject;
  525. // We initialize the default updater but the real one gets injected by the
  526. // renderer.
  527. this.updater = updater || ReactNoopUpdateQueue;
  528. }
  529. ReactComponent.prototype.isReactComponent = {};
  530. /**
  531. * Sets a subset of the state. Always use this to mutate
  532. * state. You should treat `this.state` as immutable.
  533. *
  534. * There is no guarantee that `this.state` will be immediately updated, so
  535. * accessing `this.state` after calling this method may return the old value.
  536. *
  537. * There is no guarantee that calls to `setState` will run synchronously,
  538. * as they may eventually be batched together. You can provide an optional
  539. * callback that will be executed when the call to setState is actually
  540. * completed.
  541. *
  542. * When a function is provided to setState, it will be called at some point in
  543. * the future (not synchronously). It will be called with the up to date
  544. * component arguments (state, props, context). These values can be different
  545. * from this.* because your function may be called after receiveProps but before
  546. * shouldComponentUpdate, and this new state, props, and context will not yet be
  547. * assigned to this.
  548. *
  549. * @param {object|function} partialState Next partial state or function to
  550. * produce next partial state to be merged with current state.
  551. * @param {?function} callback Called after state is updated.
  552. * @final
  553. * @protected
  554. */
  555. ReactComponent.prototype.setState = function (partialState, callback) {
  556. !(typeof partialState === 'object' || typeof partialState === 'function' || partialState == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'setState(...): takes an object of state variables to update or a function which returns an object of state variables.') : _prodInvariant('85') : void 0;
  557. this.updater.enqueueSetState(this, partialState);
  558. if (callback) {
  559. this.updater.enqueueCallback(this, callback, 'setState');
  560. }
  561. };
  562. /**
  563. * Forces an update. This should only be invoked when it is known with
  564. * certainty that we are **not** in a DOM transaction.
  565. *
  566. * You may want to call this when you know that some deeper aspect of the
  567. * component's state has changed but `setState` was not called.
  568. *
  569. * This will not invoke `shouldComponentUpdate`, but it will invoke
  570. * `componentWillUpdate` and `componentDidUpdate`.
  571. *
  572. * @param {?function} callback Called after update is complete.
  573. * @final
  574. * @protected
  575. */
  576. ReactComponent.prototype.forceUpdate = function (callback) {
  577. this.updater.enqueueForceUpdate(this);
  578. if (callback) {
  579. this.updater.enqueueCallback(this, callback, 'forceUpdate');
  580. }
  581. };
  582. /**
  583. * Deprecated APIs. These APIs used to exist on classic React classes but since
  584. * we would like to deprecate them, we're not going to move them over to this
  585. * modern base class. Instead, we define a getter that warns if it's accessed.
  586. */
  587. if (process.env.NODE_ENV !== 'production') {
  588. var deprecatedAPIs = {
  589. isMounted: ['isMounted', 'Instead, make sure to clean up subscriptions and pending requests in ' + 'componentWillUnmount to prevent memory leaks.'],
  590. replaceState: ['replaceState', 'Refactor your code to use setState instead (see ' + 'https://github.com/facebook/react/issues/3236).']
  591. };
  592. var defineDeprecationWarning = function (methodName, info) {
  593. if (canDefineProperty) {
  594. Object.defineProperty(ReactComponent.prototype, methodName, {
  595. get: function () {
  596. lowPriorityWarning(false, '%s(...) is deprecated in plain JavaScript React classes. %s', info[0], info[1]);
  597. return undefined;
  598. }
  599. });
  600. }
  601. };
  602. for (var fnName in deprecatedAPIs) {
  603. if (deprecatedAPIs.hasOwnProperty(fnName)) {
  604. defineDeprecationWarning(fnName, deprecatedAPIs[fnName]);
  605. }
  606. }
  607. }
  608. /**
  609. * Base class helpers for the updating state of a component.
  610. */
  611. function ReactPureComponent(props, context, updater) {
  612. // Duplicated from ReactComponent.
  613. this.props = props;
  614. this.context = context;
  615. this.refs = emptyObject;
  616. // We initialize the default updater but the real one gets injected by the
  617. // renderer.
  618. this.updater = updater || ReactNoopUpdateQueue;
  619. }
  620. function ComponentDummy() {}
  621. ComponentDummy.prototype = ReactComponent.prototype;
  622. ReactPureComponent.prototype = new ComponentDummy();
  623. ReactPureComponent.prototype.constructor = ReactPureComponent;
  624. // Avoid an extra prototype jump for these methods.
  625. _assign(ReactPureComponent.prototype, ReactComponent.prototype);
  626. ReactPureComponent.prototype.isPureReactComponent = true;
  627. module.exports = {
  628. Component: ReactComponent,
  629. PureComponent: ReactPureComponent
  630. };
  631. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
  632. /***/ }),
  633. /* 6 */
  634. /***/ (function(module, exports) {
  635. /**
  636. * Copyright (c) 2013-present, Facebook, Inc.
  637. *
  638. * This source code is licensed under the MIT license found in the
  639. * LICENSE file in the root directory of this source tree.
  640. *
  641. *
  642. */
  643. 'use strict';
  644. /**
  645. * WARNING: DO NOT manually require this module.
  646. * This is a replacement for `invariant(...)` used by the error code system
  647. * and will _only_ be required by the corresponding babel pass.
  648. * It always throws.
  649. */
  650. function reactProdInvariant(code) {
  651. var argCount = arguments.length - 1;
  652. var message = 'Minified React error #' + code + '; visit ' + 'http://facebook.github.io/react/docs/error-decoder.html?invariant=' + code;
  653. for (var argIdx = 0; argIdx < argCount; argIdx++) {
  654. message += '&args[]=' + encodeURIComponent(arguments[argIdx + 1]);
  655. }
  656. message += ' for the full message or use the non-minified dev environment' + ' for full errors and additional helpful warnings.';
  657. var error = new Error(message);
  658. error.name = 'Invariant Violation';
  659. error.framesToPop = 1; // we don't care about reactProdInvariant's own frame
  660. throw error;
  661. }
  662. module.exports = reactProdInvariant;
  663. /***/ }),
  664. /* 7 */
  665. /***/ (function(module, exports, __webpack_require__) {
  666. /* WEBPACK VAR INJECTION */(function(process) {/**
  667. * Copyright (c) 2015-present, Facebook, Inc.
  668. *
  669. * This source code is licensed under the MIT license found in the
  670. * LICENSE file in the root directory of this source tree.
  671. *
  672. */
  673. 'use strict';
  674. var warning = __webpack_require__(8);
  675. function warnNoop(publicInstance, callerName) {
  676. if (process.env.NODE_ENV !== 'production') {
  677. var constructor = publicInstance.constructor;
  678. process.env.NODE_ENV !== 'production' ? warning(false, '%s(...): Can only update a mounted or mounting component. ' + 'This usually means you called %s() on an unmounted component. ' + 'This is a no-op. Please check the code for the %s component.', callerName, callerName, constructor && (constructor.displayName || constructor.name) || 'ReactClass') : void 0;
  679. }
  680. }
  681. /**
  682. * This is the abstract API for an update queue.
  683. */
  684. var ReactNoopUpdateQueue = {
  685. /**
  686. * Checks whether or not this composite component is mounted.
  687. * @param {ReactClass} publicInstance The instance we want to test.
  688. * @return {boolean} True if mounted, false otherwise.
  689. * @protected
  690. * @final
  691. */
  692. isMounted: function (publicInstance) {
  693. return false;
  694. },
  695. /**
  696. * Enqueue a callback that will be executed after all the pending updates
  697. * have processed.
  698. *
  699. * @param {ReactClass} publicInstance The instance to use as `this` context.
  700. * @param {?function} callback Called after state is updated.
  701. * @internal
  702. */
  703. enqueueCallback: function (publicInstance, callback) {},
  704. /**
  705. * Forces an update. This should only be invoked when it is known with
  706. * certainty that we are **not** in a DOM transaction.
  707. *
  708. * You may want to call this when you know that some deeper aspect of the
  709. * component's state has changed but `setState` was not called.
  710. *
  711. * This will not invoke `shouldComponentUpdate`, but it will invoke
  712. * `componentWillUpdate` and `componentDidUpdate`.
  713. *
  714. * @param {ReactClass} publicInstance The instance that should rerender.
  715. * @internal
  716. */
  717. enqueueForceUpdate: function (publicInstance) {
  718. warnNoop(publicInstance, 'forceUpdate');
  719. },
  720. /**
  721. * Replaces all of the state. Always use this or `setState` to mutate state.
  722. * You should treat `this.state` as immutable.
  723. *
  724. * There is no guarantee that `this.state` will be immediately updated, so
  725. * accessing `this.state` after calling this method may return the old value.
  726. *
  727. * @param {ReactClass} publicInstance The instance that should rerender.
  728. * @param {object} completeState Next state.
  729. * @internal
  730. */
  731. enqueueReplaceState: function (publicInstance, completeState) {
  732. warnNoop(publicInstance, 'replaceState');
  733. },
  734. /**
  735. * Sets a subset of the state. This only exists because _pendingState is
  736. * internal. This provides a merging strategy that is not available to deep
  737. * properties which is confusing. TODO: Expose pendingState or don't use it
  738. * during the merge.
  739. *
  740. * @param {ReactClass} publicInstance The instance that should rerender.
  741. * @param {object} partialState Next partial state to be merged with state.
  742. * @internal
  743. */
  744. enqueueSetState: function (publicInstance, partialState) {
  745. warnNoop(publicInstance, 'setState');
  746. }
  747. };
  748. module.exports = ReactNoopUpdateQueue;
  749. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
  750. /***/ }),
  751. /* 8 */
  752. /***/ (function(module, exports, __webpack_require__) {
  753. /* WEBPACK VAR INJECTION */(function(process) {/**
  754. * Copyright (c) 2014-present, Facebook, Inc.
  755. *
  756. * This source code is licensed under the MIT license found in the
  757. * LICENSE file in the root directory of this source tree.
  758. *
  759. */
  760. 'use strict';
  761. var emptyFunction = __webpack_require__(9);
  762. /**
  763. * Similar to invariant but only logs a warning if the condition is not met.
  764. * This can be used to log issues in development environments in critical
  765. * paths. Removing the logging code for production environments will keep the
  766. * same logic and follow the same code paths.
  767. */
  768. var warning = emptyFunction;
  769. if (process.env.NODE_ENV !== 'production') {
  770. var printWarning = function printWarning(format) {
  771. for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  772. args[_key - 1] = arguments[_key];
  773. }
  774. var argIndex = 0;
  775. var message = 'Warning: ' + format.replace(/%s/g, function () {
  776. return args[argIndex++];
  777. });
  778. if (typeof console !== 'undefined') {
  779. console.error(message);
  780. }
  781. try {
  782. // --- Welcome to debugging React ---
  783. // This error was thrown as a convenience so that you can use this stack
  784. // to find the callsite that caused this warning to fire.
  785. throw new Error(message);
  786. } catch (x) {}
  787. };
  788. warning = function warning(condition, format) {
  789. if (format === undefined) {
  790. throw new Error('`warning(condition, format, ...args)` requires a warning ' + 'message argument');
  791. }
  792. if (format.indexOf('Failed Composite propType: ') === 0) {
  793. return; // Ignore CompositeComponent proptype check.
  794. }
  795. if (!condition) {
  796. for (var _len2 = arguments.length, args = Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) {
  797. args[_key2 - 2] = arguments[_key2];
  798. }
  799. printWarning.apply(undefined, [format].concat(args));
  800. }
  801. };
  802. }
  803. module.exports = warning;
  804. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
  805. /***/ }),
  806. /* 9 */
  807. /***/ (function(module, exports) {
  808. "use strict";
  809. /**
  810. * Copyright (c) 2013-present, Facebook, Inc.
  811. *
  812. * This source code is licensed under the MIT license found in the
  813. * LICENSE file in the root directory of this source tree.
  814. *
  815. *
  816. */
  817. function makeEmptyFunction(arg) {
  818. return function () {
  819. return arg;
  820. };
  821. }
  822. /**
  823. * This function accepts and discards inputs; it has no side effects. This is
  824. * primarily useful idiomatically for overridable function endpoints which
  825. * always need to be callable, since JS lacks a null-call idiom ala Cocoa.
  826. */
  827. var emptyFunction = function emptyFunction() {};
  828. emptyFunction.thatReturns = makeEmptyFunction;
  829. emptyFunction.thatReturnsFalse = makeEmptyFunction(false);
  830. emptyFunction.thatReturnsTrue = makeEmptyFunction(true);
  831. emptyFunction.thatReturnsNull = makeEmptyFunction(null);
  832. emptyFunction.thatReturnsThis = function () {
  833. return this;
  834. };
  835. emptyFunction.thatReturnsArgument = function (arg) {
  836. return arg;
  837. };
  838. module.exports = emptyFunction;
  839. /***/ }),
  840. /* 10 */
  841. /***/ (function(module, exports, __webpack_require__) {
  842. /* WEBPACK VAR INJECTION */(function(process) {/**
  843. * Copyright (c) 2013-present, Facebook, Inc.
  844. *
  845. * This source code is licensed under the MIT license found in the
  846. * LICENSE file in the root directory of this source tree.
  847. *
  848. *
  849. */
  850. 'use strict';
  851. var canDefineProperty = false;
  852. if (process.env.NODE_ENV !== 'production') {
  853. try {
  854. // $FlowFixMe https://github.com/facebook/flow/issues/285
  855. Object.defineProperty({}, 'x', { get: function () {} });
  856. canDefineProperty = true;
  857. } catch (x) {
  858. // IE will fail on defineProperty
  859. }
  860. }
  861. module.exports = canDefineProperty;
  862. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
  863. /***/ }),
  864. /* 11 */
  865. /***/ (function(module, exports, __webpack_require__) {
  866. /* WEBPACK VAR INJECTION */(function(process) {/**
  867. * Copyright (c) 2013-present, Facebook, Inc.
  868. *
  869. * This source code is licensed under the MIT license found in the
  870. * LICENSE file in the root directory of this source tree.
  871. *
  872. */
  873. 'use strict';
  874. var emptyObject = {};
  875. if (process.env.NODE_ENV !== 'production') {
  876. Object.freeze(emptyObject);
  877. }
  878. module.exports = emptyObject;
  879. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
  880. /***/ }),
  881. /* 12 */
  882. /***/ (function(module, exports, __webpack_require__) {
  883. /* WEBPACK VAR INJECTION */(function(process) {/**
  884. * Copyright (c) 2013-present, Facebook, Inc.
  885. *
  886. * This source code is licensed under the MIT license found in the
  887. * LICENSE file in the root directory of this source tree.
  888. *
  889. */
  890. 'use strict';
  891. /**
  892. * Use invariant() to assert state which your program assumes to be true.
  893. *
  894. * Provide sprintf-style format (only %s is supported) and arguments
  895. * to provide information about what broke and what you were
  896. * expecting.
  897. *
  898. * The invariant message will be stripped in production, but the invariant
  899. * will remain to ensure logic does not differ in production.
  900. */
  901. var validateFormat = function validateFormat(format) {};
  902. if (process.env.NODE_ENV !== 'production') {
  903. validateFormat = function validateFormat(format) {
  904. if (format === undefined) {
  905. throw new Error('invariant requires an error message argument');
  906. }
  907. };
  908. }
  909. function invariant(condition, format, a, b, c, d, e, f) {
  910. validateFormat(format);
  911. if (!condition) {
  912. var error;
  913. if (format === undefined) {
  914. error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.');
  915. } else {
  916. var args = [a, b, c, d, e, f];
  917. var argIndex = 0;
  918. error = new Error(format.replace(/%s/g, function () {
  919. return args[argIndex++];
  920. }));
  921. error.name = 'Invariant Violation';
  922. }
  923. error.framesToPop = 1; // we don't care about invariant's own frame
  924. throw error;
  925. }
  926. }
  927. module.exports = invariant;
  928. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
  929. /***/ }),
  930. /* 13 */
  931. /***/ (function(module, exports, __webpack_require__) {
  932. /* WEBPACK VAR INJECTION */(function(process) {/**
  933. * Copyright (c) 2014-present, Facebook, Inc.
  934. *
  935. * This source code is licensed under the MIT license found in the
  936. * LICENSE file in the root directory of this source tree.
  937. *
  938. */
  939. 'use strict';
  940. /**
  941. * Forked from fbjs/warning:
  942. * https://github.com/facebook/fbjs/blob/e66ba20ad5be433eb54423f2b097d829324d9de6/packages/fbjs/src/__forks__/warning.js
  943. *
  944. * Only change is we use console.warn instead of console.error,
  945. * and do nothing when 'console' is not supported.
  946. * This really simplifies the code.
  947. * ---
  948. * Similar to invariant but only logs a warning if the condition is not met.
  949. * This can be used to log issues in development environments in critical
  950. * paths. Removing the logging code for production environments will keep the
  951. * same logic and follow the same code paths.
  952. */
  953. var lowPriorityWarning = function () {};
  954. if (process.env.NODE_ENV !== 'production') {
  955. var printWarning = function (format) {
  956. for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  957. args[_key - 1] = arguments[_key];
  958. }
  959. var argIndex = 0;
  960. var message = 'Warning: ' + format.replace(/%s/g, function () {
  961. return args[argIndex++];
  962. });
  963. if (typeof console !== 'undefined') {
  964. console.warn(message);
  965. }
  966. try {
  967. // --- Welcome to debugging React ---
  968. // This error was thrown as a convenience so that you can use this stack
  969. // to find the callsite that caused this warning to fire.
  970. throw new Error(message);
  971. } catch (x) {}
  972. };
  973. lowPriorityWarning = function (condition, format) {
  974. if (format === undefined) {
  975. throw new Error('`warning(condition, format, ...args)` requires a warning ' + 'message argument');
  976. }
  977. if (!condition) {
  978. for (var _len2 = arguments.length, args = Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) {
  979. args[_key2 - 2] = arguments[_key2];
  980. }
  981. printWarning.apply(undefined, [format].concat(args));
  982. }
  983. };
  984. }
  985. module.exports = lowPriorityWarning;
  986. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
  987. /***/ }),
  988. /* 14 */
  989. /***/ (function(module, exports, __webpack_require__) {
  990. /**
  991. * Copyright (c) 2013-present, Facebook, Inc.
  992. *
  993. * This source code is licensed under the MIT license found in the
  994. * LICENSE file in the root directory of this source tree.
  995. *
  996. */
  997. 'use strict';
  998. var PooledClass = __webpack_require__(15);
  999. var ReactElement = __webpack_require__(16);
  1000. var emptyFunction = __webpack_require__(9);
  1001. var traverseAllChildren = __webpack_require__(19);
  1002. var twoArgumentPooler = PooledClass.twoArgumentPooler;
  1003. var fourArgumentPooler = PooledClass.fourArgumentPooler;
  1004. var userProvidedKeyEscapeRegex = /\/+/g;
  1005. function escapeUserProvidedKey(text) {
  1006. return ('' + text).replace(userProvidedKeyEscapeRegex, '$&/');
  1007. }
  1008. /**
  1009. * PooledClass representing the bookkeeping associated with performing a child
  1010. * traversal. Allows avoiding binding callbacks.
  1011. *
  1012. * @constructor ForEachBookKeeping
  1013. * @param {!function} forEachFunction Function to perform traversal with.
  1014. * @param {?*} forEachContext Context to perform context with.
  1015. */
  1016. function ForEachBookKeeping(forEachFunction, forEachContext) {
  1017. this.func = forEachFunction;
  1018. this.context = forEachContext;
  1019. this.count = 0;
  1020. }
  1021. ForEachBookKeeping.prototype.destructor = function () {
  1022. this.func = null;
  1023. this.context = null;
  1024. this.count = 0;
  1025. };
  1026. PooledClass.addPoolingTo(ForEachBookKeeping, twoArgumentPooler);
  1027. function forEachSingleChild(bookKeeping, child, name) {
  1028. var func = bookKeeping.func,
  1029. context = bookKeeping.context;
  1030. func.call(context, child, bookKeeping.count++);
  1031. }
  1032. /**
  1033. * Iterates through children that are typically specified as `props.children`.
  1034. *
  1035. * See https://facebook.github.io/react/docs/top-level-api.html#react.children.foreach
  1036. *
  1037. * The provided forEachFunc(child, index) will be called for each
  1038. * leaf child.
  1039. *
  1040. * @param {?*} children Children tree container.
  1041. * @param {function(*, int)} forEachFunc
  1042. * @param {*} forEachContext Context for forEachContext.
  1043. */
  1044. function forEachChildren(children, forEachFunc, forEachContext) {
  1045. if (children == null) {
  1046. return children;
  1047. }
  1048. var traverseContext = ForEachBookKeeping.getPooled(forEachFunc, forEachContext);
  1049. traverseAllChildren(children, forEachSingleChild, traverseContext);
  1050. ForEachBookKeeping.release(traverseContext);
  1051. }
  1052. /**
  1053. * PooledClass representing the bookkeeping associated with performing a child
  1054. * mapping. Allows avoiding binding callbacks.
  1055. *
  1056. * @constructor MapBookKeeping
  1057. * @param {!*} mapResult Object containing the ordered map of results.
  1058. * @param {!function} mapFunction Function to perform mapping with.
  1059. * @param {?*} mapContext Context to perform mapping with.
  1060. */
  1061. function MapBookKeeping(mapResult, keyPrefix, mapFunction, mapContext) {
  1062. this.result = mapResult;
  1063. this.keyPrefix = keyPrefix;
  1064. this.func = mapFunction;
  1065. this.context = mapContext;
  1066. this.count = 0;
  1067. }
  1068. MapBookKeeping.prototype.destructor = function () {
  1069. this.result = null;
  1070. this.keyPrefix = null;
  1071. this.func = null;
  1072. this.context = null;
  1073. this.count = 0;
  1074. };
  1075. PooledClass.addPoolingTo(MapBookKeeping, fourArgumentPooler);
  1076. function mapSingleChildIntoContext(bookKeeping, child, childKey) {
  1077. var result = bookKeeping.result,
  1078. keyPrefix = bookKeeping.keyPrefix,
  1079. func = bookKeeping.func,
  1080. context = bookKeeping.context;
  1081. var mappedChild = func.call(context, child, bookKeeping.count++);
  1082. if (Array.isArray(mappedChild)) {
  1083. mapIntoWithKeyPrefixInternal(mappedChild, result, childKey, emptyFunction.thatReturnsArgument);
  1084. } else if (mappedChild != null) {
  1085. if (ReactElement.isValidElement(mappedChild)) {
  1086. mappedChild = ReactElement.cloneAndReplaceKey(mappedChild,
  1087. // Keep both the (mapped) and old keys if they differ, just as
  1088. // traverseAllChildren used to do for objects as children
  1089. keyPrefix + (mappedChild.key && (!child || child.key !== mappedChild.key) ? escapeUserProvidedKey(mappedChild.key) + '/' : '') + childKey);
  1090. }
  1091. result.push(mappedChild);
  1092. }
  1093. }
  1094. function mapIntoWithKeyPrefixInternal(children, array, prefix, func, context) {
  1095. var escapedPrefix = '';
  1096. if (prefix != null) {
  1097. escapedPrefix = escapeUserProvidedKey(prefix) + '/';
  1098. }
  1099. var traverseContext = MapBookKeeping.getPooled(array, escapedPrefix, func, context);
  1100. traverseAllChildren(children, mapSingleChildIntoContext, traverseContext);
  1101. MapBookKeeping.release(traverseContext);
  1102. }
  1103. /**
  1104. * Maps children that are typically specified as `props.children`.
  1105. *
  1106. * See https://facebook.github.io/react/docs/top-level-api.html#react.children.map
  1107. *
  1108. * The provided mapFunction(child, key, index) will be called for each
  1109. * leaf child.
  1110. *
  1111. * @param {?*} children Children tree container.
  1112. * @param {function(*, int)} func The map function.
  1113. * @param {*} context Context for mapFunction.
  1114. * @return {object} Object containing the ordered map of results.
  1115. */
  1116. function mapChildren(children, func, context) {
  1117. if (children == null) {
  1118. return children;
  1119. }
  1120. var result = [];
  1121. mapIntoWithKeyPrefixInternal(children, result, null, func, context);
  1122. return result;
  1123. }
  1124. function forEachSingleChildDummy(traverseContext, child, name) {
  1125. return null;
  1126. }
  1127. /**
  1128. * Count the number of children that are typically specified as
  1129. * `props.children`.
  1130. *
  1131. * See https://facebook.github.io/react/docs/top-level-api.html#react.children.count
  1132. *
  1133. * @param {?*} children Children tree container.
  1134. * @return {number} The number of children.
  1135. */
  1136. function countChildren(children, context) {
  1137. return traverseAllChildren(children, forEachSingleChildDummy, null);
  1138. }
  1139. /**
  1140. * Flatten a children object (typically specified as `props.children`) and
  1141. * return an array with appropriately re-keyed children.
  1142. *
  1143. * See https://facebook.github.io/react/docs/top-level-api.html#react.children.toarray
  1144. */
  1145. function toArray(children) {
  1146. var result = [];
  1147. mapIntoWithKeyPrefixInternal(children, result, null, emptyFunction.thatReturnsArgument);
  1148. return result;
  1149. }
  1150. var ReactChildren = {
  1151. forEach: forEachChildren,
  1152. map: mapChildren,
  1153. mapIntoWithKeyPrefixInternal: mapIntoWithKeyPrefixInternal,
  1154. count: countChildren,
  1155. toArray: toArray
  1156. };
  1157. module.exports = ReactChildren;
  1158. /***/ }),
  1159. /* 15 */
  1160. /***/ (function(module, exports, __webpack_require__) {
  1161. /* WEBPACK VAR INJECTION */(function(process) {/**
  1162. * Copyright (c) 2013-present, Facebook, Inc.
  1163. *
  1164. * This source code is licensed under the MIT license found in the
  1165. * LICENSE file in the root directory of this source tree.
  1166. *
  1167. *
  1168. */
  1169. 'use strict';
  1170. var _prodInvariant = __webpack_require__(6);
  1171. var invariant = __webpack_require__(12);
  1172. /**
  1173. * Static poolers. Several custom versions for each potential number of
  1174. * arguments. A completely generic pooler is easy to implement, but would
  1175. * require accessing the `arguments` object. In each of these, `this` refers to
  1176. * the Class itself, not an instance. If any others are needed, simply add them
  1177. * here, or in their own files.
  1178. */
  1179. var oneArgumentPooler = function (copyFieldsFrom) {
  1180. var Klass = this;
  1181. if (Klass.instancePool.length) {
  1182. var instance = Klass.instancePool.pop();
  1183. Klass.call(instance, copyFieldsFrom);
  1184. return instance;
  1185. } else {
  1186. return new Klass(copyFieldsFrom);
  1187. }
  1188. };
  1189. var twoArgumentPooler = function (a1, a2) {
  1190. var Klass = this;
  1191. if (Klass.instancePool.length) {
  1192. var instance = Klass.instancePool.pop();
  1193. Klass.call(instance, a1, a2);
  1194. return instance;
  1195. } else {
  1196. return new Klass(a1, a2);
  1197. }
  1198. };
  1199. var threeArgumentPooler = function (a1, a2, a3) {
  1200. var Klass = this;
  1201. if (Klass.instancePool.length) {
  1202. var instance = Klass.instancePool.pop();
  1203. Klass.call(instance, a1, a2, a3);
  1204. return instance;
  1205. } else {
  1206. return new Klass(a1, a2, a3);
  1207. }
  1208. };
  1209. var fourArgumentPooler = function (a1, a2, a3, a4) {
  1210. var Klass = this;
  1211. if (Klass.instancePool.length) {
  1212. var instance = Klass.instancePool.pop();
  1213. Klass.call(instance, a1, a2, a3, a4);
  1214. return instance;
  1215. } else {
  1216. return new Klass(a1, a2, a3, a4);
  1217. }
  1218. };
  1219. var standardReleaser = function (instance) {
  1220. var Klass = this;
  1221. !(instance instanceof Klass) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Trying to release an instance into a pool of a different type.') : _prodInvariant('25') : void 0;
  1222. instance.destructor();
  1223. if (Klass.instancePool.length < Klass.poolSize) {
  1224. Klass.instancePool.push(instance);
  1225. }
  1226. };
  1227. var DEFAULT_POOL_SIZE = 10;
  1228. var DEFAULT_POOLER = oneArgumentPooler;
  1229. /**
  1230. * Augments `CopyConstructor` to be a poolable class, augmenting only the class
  1231. * itself (statically) not adding any prototypical fields. Any CopyConstructor
  1232. * you give this may have a `poolSize` property, and will look for a
  1233. * prototypical `destructor` on instances.
  1234. *
  1235. * @param {Function} CopyConstructor Constructor that can be used to reset.
  1236. * @param {Function} pooler Customizable pooler.
  1237. */
  1238. var addPoolingTo = function (CopyConstructor, pooler) {
  1239. // Casting as any so that flow ignores the actual implementation and trusts
  1240. // it to match the type we declared
  1241. var NewKlass = CopyConstructor;
  1242. NewKlass.instancePool = [];
  1243. NewKlass.getPooled = pooler || DEFAULT_POOLER;
  1244. if (!NewKlass.poolSize) {
  1245. NewKlass.poolSize = DEFAULT_POOL_SIZE;
  1246. }
  1247. NewKlass.release = standardReleaser;
  1248. return NewKlass;
  1249. };
  1250. var PooledClass = {
  1251. addPoolingTo: addPoolingTo,
  1252. oneArgumentPooler: oneArgumentPooler,
  1253. twoArgumentPooler: twoArgumentPooler,
  1254. threeArgumentPooler: threeArgumentPooler,
  1255. fourArgumentPooler: fourArgumentPooler
  1256. };
  1257. module.exports = PooledClass;
  1258. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
  1259. /***/ }),
  1260. /* 16 */
  1261. /***/ (function(module, exports, __webpack_require__) {
  1262. /* WEBPACK VAR INJECTION */(function(process) {/**
  1263. * Copyright (c) 2014-present, Facebook, Inc.
  1264. *
  1265. * This source code is licensed under the MIT license found in the
  1266. * LICENSE file in the root directory of this source tree.
  1267. *
  1268. */
  1269. 'use strict';
  1270. var _assign = __webpack_require__(4);
  1271. var ReactCurrentOwner = __webpack_require__(17);
  1272. var warning = __webpack_require__(8);
  1273. var canDefineProperty = __webpack_require__(10);
  1274. var hasOwnProperty = Object.prototype.hasOwnProperty;
  1275. var REACT_ELEMENT_TYPE = __webpack_require__(18);
  1276. var RESERVED_PROPS = {
  1277. key: true,
  1278. ref: true,
  1279. __self: true,
  1280. __source: true
  1281. };
  1282. var specialPropKeyWarningShown, specialPropRefWarningShown;
  1283. function hasValidRef(config) {
  1284. if (process.env.NODE_ENV !== 'production') {
  1285. if (hasOwnProperty.call(config, 'ref')) {
  1286. var getter = Object.getOwnPropertyDescriptor(config, 'ref').get;
  1287. if (getter && getter.isReactWarning) {
  1288. return false;
  1289. }
  1290. }
  1291. }
  1292. return config.ref !== undefined;
  1293. }
  1294. function hasValidKey(config) {
  1295. if (process.env.NODE_ENV !== 'production') {
  1296. if (hasOwnProperty.call(config, 'key')) {
  1297. var getter = Object.getOwnPropertyDescriptor(config, 'key').get;
  1298. if (getter && getter.isReactWarning) {
  1299. return false;
  1300. }
  1301. }
  1302. }
  1303. return config.key !== undefined;
  1304. }
  1305. function defineKeyPropWarningGetter(props, displayName) {
  1306. var warnAboutAccessingKey = function () {
  1307. if (!specialPropKeyWarningShown) {
  1308. specialPropKeyWarningShown = true;
  1309. process.env.NODE_ENV !== 'production' ? warning(false, '%s: `key` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://fb.me/react-special-props)', displayName) : void 0;
  1310. }
  1311. };
  1312. warnAboutAccessingKey.isReactWarning = true;
  1313. Object.defineProperty(props, 'key', {
  1314. get: warnAboutAccessingKey,
  1315. configurable: true
  1316. });
  1317. }
  1318. function defineRefPropWarningGetter(props, displayName) {
  1319. var warnAboutAccessingRef = function () {
  1320. if (!specialPropRefWarningShown) {
  1321. specialPropRefWarningShown = true;
  1322. process.env.NODE_ENV !== 'production' ? warning(false, '%s: `ref` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://fb.me/react-special-props)', displayName) : void 0;
  1323. }
  1324. };
  1325. warnAboutAccessingRef.isReactWarning = true;
  1326. Object.defineProperty(props, 'ref', {
  1327. get: warnAboutAccessingRef,
  1328. configurable: true
  1329. });
  1330. }
  1331. /**
  1332. * Factory method to create a new React element. This no longer adheres to
  1333. * the class pattern, so do not use new to call it. Also, no instanceof check
  1334. * will work. Instead test $$typeof field against Symbol.for('react.element') to check
  1335. * if something is a React Element.
  1336. *
  1337. * @param {*} type
  1338. * @param {*} key
  1339. * @param {string|object} ref
  1340. * @param {*} self A *temporary* helper to detect places where `this` is
  1341. * different from the `owner` when React.createElement is called, so that we
  1342. * can warn. We want to get rid of owner and replace string `ref`s with arrow
  1343. * functions, and as long as `this` and owner are the same, there will be no
  1344. * change in behavior.
  1345. * @param {*} source An annotation object (added by a transpiler or otherwise)
  1346. * indicating filename, line number, and/or other information.
  1347. * @param {*} owner
  1348. * @param {*} props
  1349. * @internal
  1350. */
  1351. var ReactElement = function (type, key, ref, self, source, owner, props) {
  1352. var element = {
  1353. // This tag allow us to uniquely identify this as a React Element
  1354. $$typeof: REACT_ELEMENT_TYPE,
  1355. // Built-in properties that belong on the element
  1356. type: type,
  1357. key: key,
  1358. ref: ref,
  1359. props: props,
  1360. // Record the component responsible for creating this element.
  1361. _owner: owner
  1362. };
  1363. if (process.env.NODE_ENV !== 'production') {
  1364. // The validation flag is currently mutative. We put it on
  1365. // an external backing store so that we can freeze the whole object.
  1366. // This can be replaced with a WeakMap once they are implemented in
  1367. // commonly used development environments.
  1368. element._store = {};
  1369. // To make comparing ReactElements easier for testing purposes, we make
  1370. // the validation flag non-enumerable (where possible, which should
  1371. // include every environment we run tests in), so the test framework
  1372. // ignores it.
  1373. if (canDefineProperty) {
  1374. Object.defineProperty(element._store, 'validated', {
  1375. configurable: false,
  1376. enumerable: false,
  1377. writable: true,
  1378. value: false
  1379. });
  1380. // self and source are DEV only properties.
  1381. Object.defineProperty(element, '_self', {
  1382. configurable: false,
  1383. enumerable: false,
  1384. writable: false,
  1385. value: self
  1386. });
  1387. // Two elements created in two different places should be considered
  1388. // equal for testing purposes and therefore we hide it from enumeration.
  1389. Object.defineProperty(element, '_source', {
  1390. configurable: false,
  1391. enumerable: false,
  1392. writable: false,
  1393. value: source
  1394. });
  1395. } else {
  1396. element._store.validated = false;
  1397. element._self = self;
  1398. element._source = source;
  1399. }
  1400. if (Object.freeze) {
  1401. Object.freeze(element.props);
  1402. Object.freeze(element);
  1403. }
  1404. }
  1405. return element;
  1406. };
  1407. /**
  1408. * Create and return a new ReactElement of the given type.
  1409. * See https://facebook.github.io/react/docs/top-level-api.html#react.createelement
  1410. */
  1411. ReactElement.createElement = function (type, config, children) {
  1412. var propName;
  1413. // Reserved names are extracted
  1414. var props = {};
  1415. var key = null;
  1416. var ref = null;
  1417. var self = null;
  1418. var source = null;
  1419. if (config != null) {
  1420. if (hasValidRef(config)) {
  1421. ref = config.ref;
  1422. }
  1423. if (hasValidKey(config)) {
  1424. key = '' + config.key;
  1425. }
  1426. self = config.__self === undefined ? null : config.__self;
  1427. source = config.__source === undefined ? null : config.__source;
  1428. // Remaining properties are added to a new props object
  1429. for (propName in config) {
  1430. if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) {
  1431. props[propName] = config[propName];
  1432. }
  1433. }
  1434. }
  1435. // Children can be more than one argument, and those are transferred onto
  1436. // the newly allocated props object.
  1437. var childrenLength = arguments.length - 2;
  1438. if (childrenLength === 1) {
  1439. props.children = children;
  1440. } else if (childrenLength > 1) {
  1441. var childArray = Array(childrenLength);
  1442. for (var i = 0; i < childrenLength; i++) {
  1443. childArray[i] = arguments[i + 2];
  1444. }
  1445. if (process.env.NODE_ENV !== 'production') {
  1446. if (Object.freeze) {
  1447. Object.freeze(childArray);
  1448. }
  1449. }
  1450. props.children = childArray;
  1451. }
  1452. // Resolve default props
  1453. if (type && type.defaultProps) {
  1454. var defaultProps = type.defaultProps;
  1455. for (propName in defaultProps) {
  1456. if (props[propName] === undefined) {
  1457. props[propName] = defaultProps[propName];
  1458. }
  1459. }
  1460. }
  1461. if (process.env.NODE_ENV !== 'production') {
  1462. if (key || ref) {
  1463. if (typeof props.$$typeof === 'undefined' || props.$$typeof !== REACT_ELEMENT_TYPE) {
  1464. var displayName = typeof type === 'function' ? type.displayName || type.name || 'Unknown' : type;
  1465. if (key) {
  1466. defineKeyPropWarningGetter(props, displayName);
  1467. }
  1468. if (ref) {
  1469. defineRefPropWarningGetter(props, displayName);
  1470. }
  1471. }
  1472. }
  1473. }
  1474. return ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props);
  1475. };
  1476. /**
  1477. * Return a function that produces ReactElements of a given type.
  1478. * See https://facebook.github.io/react/docs/top-level-api.html#react.createfactory
  1479. */
  1480. ReactElement.createFactory = function (type) {
  1481. var factory = ReactElement.createElement.bind(null, type);
  1482. // Expose the type on the factory and the prototype so that it can be
  1483. // easily accessed on elements. E.g. `<Foo />.type === Foo`.
  1484. // This should not be named `constructor` since this may not be the function
  1485. // that created the element, and it may not even be a constructor.
  1486. // Legacy hook TODO: Warn if this is accessed
  1487. factory.type = type;
  1488. return factory;
  1489. };
  1490. ReactElement.cloneAndReplaceKey = function (oldElement, newKey) {
  1491. var newElement = ReactElement(oldElement.type, newKey, oldElement.ref, oldElement._self, oldElement._source, oldElement._owner, oldElement.props);
  1492. return newElement;
  1493. };
  1494. /**
  1495. * Clone and return a new ReactElement using element as the starting point.
  1496. * See https://facebook.github.io/react/docs/top-level-api.html#react.cloneelement
  1497. */
  1498. ReactElement.cloneElement = function (element, config, children) {
  1499. var propName;
  1500. // Original props are copied
  1501. var props = _assign({}, element.props);
  1502. // Reserved names are extracted
  1503. var key = element.key;
  1504. var ref = element.ref;
  1505. // Self is preserved since the owner is preserved.
  1506. var self = element._self;
  1507. // Source is preserved since cloneElement is unlikely to be targeted by a
  1508. // transpiler, and the original source is probably a better indicator of the
  1509. // true owner.
  1510. var source = element._source;
  1511. // Owner will be preserved, unless ref is overridden
  1512. var owner = element._owner;
  1513. if (config != null) {
  1514. if (hasValidRef(config)) {
  1515. // Silently steal the ref from the parent.
  1516. ref = config.ref;
  1517. owner = ReactCurrentOwner.current;
  1518. }
  1519. if (hasValidKey(config)) {
  1520. key = '' + config.key;
  1521. }
  1522. // Remaining properties override existing props
  1523. var defaultProps;
  1524. if (element.type && element.type.defaultProps) {
  1525. defaultProps = element.type.defaultProps;
  1526. }
  1527. for (propName in config) {
  1528. if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) {
  1529. if (config[propName] === undefined && defaultProps !== undefined) {
  1530. // Resolve default props
  1531. props[propName] = defaultProps[propName];
  1532. } else {
  1533. props[propName] = config[propName];
  1534. }
  1535. }
  1536. }
  1537. }
  1538. // Children can be more than one argument, and those are transferred onto
  1539. // the newly allocated props object.
  1540. var childrenLength = arguments.length - 2;
  1541. if (childrenLength === 1) {
  1542. props.children = children;
  1543. } else if (childrenLength > 1) {
  1544. var childArray = Array(childrenLength);
  1545. for (var i = 0; i < childrenLength; i++) {
  1546. childArray[i] = arguments[i + 2];
  1547. }
  1548. props.children = childArray;
  1549. }
  1550. return ReactElement(element.type, key, ref, self, source, owner, props);
  1551. };
  1552. /**
  1553. * Verifies the object is a ReactElement.
  1554. * See https://facebook.github.io/react/docs/top-level-api.html#react.isvalidelement
  1555. * @param {?object} object
  1556. * @return {boolean} True if `object` is a valid component.
  1557. * @final
  1558. */
  1559. ReactElement.isValidElement = function (object) {
  1560. return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE;
  1561. };
  1562. module.exports = ReactElement;
  1563. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
  1564. /***/ }),
  1565. /* 17 */
  1566. /***/ (function(module, exports) {
  1567. /**
  1568. * Copyright (c) 2013-present, Facebook, Inc.
  1569. *
  1570. * This source code is licensed under the MIT license found in the
  1571. * LICENSE file in the root directory of this source tree.
  1572. *
  1573. *
  1574. */
  1575. 'use strict';
  1576. /**
  1577. * Keeps track of the current owner.
  1578. *
  1579. * The current owner is the component who should own any components that are
  1580. * currently being constructed.
  1581. */
  1582. var ReactCurrentOwner = {
  1583. /**
  1584. * @internal
  1585. * @type {ReactComponent}
  1586. */
  1587. current: null
  1588. };
  1589. module.exports = ReactCurrentOwner;
  1590. /***/ }),
  1591. /* 18 */
  1592. /***/ (function(module, exports) {
  1593. /**
  1594. * Copyright (c) 2014-present, Facebook, Inc.
  1595. *
  1596. * This source code is licensed under the MIT license found in the
  1597. * LICENSE file in the root directory of this source tree.
  1598. *
  1599. *
  1600. */
  1601. 'use strict';
  1602. // The Symbol used to tag the ReactElement type. If there is no native Symbol
  1603. // nor polyfill, then a plain number is used for performance.
  1604. var REACT_ELEMENT_TYPE = typeof Symbol === 'function' && Symbol['for'] && Symbol['for']('react.element') || 0xeac7;
  1605. module.exports = REACT_ELEMENT_TYPE;
  1606. /***/ }),
  1607. /* 19 */
  1608. /***/ (function(module, exports, __webpack_require__) {
  1609. /* WEBPACK VAR INJECTION */(function(process) {/**
  1610. * Copyright (c) 2013-present, Facebook, Inc.
  1611. *
  1612. * This source code is licensed under the MIT license found in the
  1613. * LICENSE file in the root directory of this source tree.
  1614. *
  1615. */
  1616. 'use strict';
  1617. var _prodInvariant = __webpack_require__(6);
  1618. var ReactCurrentOwner = __webpack_require__(17);
  1619. var REACT_ELEMENT_TYPE = __webpack_require__(18);
  1620. var getIteratorFn = __webpack_require__(20);
  1621. var invariant = __webpack_require__(12);
  1622. var KeyEscapeUtils = __webpack_require__(21);
  1623. var warning = __webpack_require__(8);
  1624. var SEPARATOR = '.';
  1625. var SUBSEPARATOR = ':';
  1626. /**
  1627. * This is inlined from ReactElement since this file is shared between
  1628. * isomorphic and renderers. We could extract this to a
  1629. *
  1630. */
  1631. /**
  1632. * TODO: Test that a single child and an array with one item have the same key
  1633. * pattern.
  1634. */
  1635. var didWarnAboutMaps = false;
  1636. /**
  1637. * Generate a key string that identifies a component within a set.
  1638. *
  1639. * @param {*} component A component that could contain a manual key.
  1640. * @param {number} index Index that is used if a manual key is not provided.
  1641. * @return {string}
  1642. */
  1643. function getComponentKey(component, index) {
  1644. // Do some typechecking here since we call this blindly. We want to ensure
  1645. // that we don't block potential future ES APIs.
  1646. if (component && typeof component === 'object' && component.key != null) {
  1647. // Explicit key
  1648. return KeyEscapeUtils.escape(component.key);
  1649. }
  1650. // Implicit key determined by the index in the set
  1651. return index.toString(36);
  1652. }
  1653. /**
  1654. * @param {?*} children Children tree container.
  1655. * @param {!string} nameSoFar Name of the key path so far.
  1656. * @param {!function} callback Callback to invoke with each child found.
  1657. * @param {?*} traverseContext Used to pass information throughout the traversal
  1658. * process.
  1659. * @return {!number} The number of children in this subtree.
  1660. */
  1661. function traverseAllChildrenImpl(children, nameSoFar, callback, traverseContext) {
  1662. var type = typeof children;
  1663. if (type === 'undefined' || type === 'boolean') {
  1664. // All of the above are perceived as null.
  1665. children = null;
  1666. }
  1667. if (children === null || type === 'string' || type === 'number' ||
  1668. // The following is inlined from ReactElement. This means we can optimize
  1669. // some checks. React Fiber also inlines this logic for similar purposes.
  1670. type === 'object' && children.$$typeof === REACT_ELEMENT_TYPE) {
  1671. callback(traverseContext, children,
  1672. // If it's the only child, treat the name as if it was wrapped in an array
  1673. // so that it's consistent if the number of children grows.
  1674. nameSoFar === '' ? SEPARATOR + getComponentKey(children, 0) : nameSoFar);
  1675. return 1;
  1676. }
  1677. var child;
  1678. var nextName;
  1679. var subtreeCount = 0; // Count of children found in the current subtree.
  1680. var nextNamePrefix = nameSoFar === '' ? SEPARATOR : nameSoFar + SUBSEPARATOR;
  1681. if (Array.isArray(children)) {
  1682. for (var i = 0; i < children.length; i++) {
  1683. child = children[i];
  1684. nextName = nextNamePrefix + getComponentKey(child, i);
  1685. subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext);
  1686. }
  1687. } else {
  1688. var iteratorFn = getIteratorFn(children);
  1689. if (iteratorFn) {
  1690. var iterator = iteratorFn.call(children);
  1691. var step;
  1692. if (iteratorFn !== children.entries) {
  1693. var ii = 0;
  1694. while (!(step = iterator.next()).done) {
  1695. child = step.value;
  1696. nextName = nextNamePrefix + getComponentKey(child, ii++);
  1697. subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext);
  1698. }
  1699. } else {
  1700. if (process.env.NODE_ENV !== 'production') {
  1701. var mapsAsChildrenAddendum = '';
  1702. if (ReactCurrentOwner.current) {
  1703. var mapsAsChildrenOwnerName = ReactCurrentOwner.current.getName();
  1704. if (mapsAsChildrenOwnerName) {
  1705. mapsAsChildrenAddendum = ' Check the render method of `' + mapsAsChildrenOwnerName + '`.';
  1706. }
  1707. }
  1708. process.env.NODE_ENV !== 'production' ? warning(didWarnAboutMaps, 'Using Maps as children is not yet fully supported. It is an ' + 'experimental feature that might be removed. Convert it to a ' + 'sequence / iterable of keyed ReactElements instead.%s', mapsAsChildrenAddendum) : void 0;
  1709. didWarnAboutMaps = true;
  1710. }
  1711. // Iterator will provide entry [k,v] tuples rather than values.
  1712. while (!(step = iterator.next()).done) {
  1713. var entry = step.value;
  1714. if (entry) {
  1715. child = entry[1];
  1716. nextName = nextNamePrefix + KeyEscapeUtils.escape(entry[0]) + SUBSEPARATOR + getComponentKey(child, 0);
  1717. subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext);
  1718. }
  1719. }
  1720. }
  1721. } else if (type === 'object') {
  1722. var addendum = '';
  1723. if (process.env.NODE_ENV !== 'production') {
  1724. addendum = ' If you meant to render a collection of children, use an array ' + 'instead or wrap the object using createFragment(object) from the ' + 'React add-ons.';
  1725. if (children._isReactElement) {
  1726. addendum = " It looks like you're using an element created by a different " + 'version of React. Make sure to use only one copy of React.';
  1727. }
  1728. if (ReactCurrentOwner.current) {
  1729. var name = ReactCurrentOwner.current.getName();
  1730. if (name) {
  1731. addendum += ' Check the render method of `' + name + '`.';
  1732. }
  1733. }
  1734. }
  1735. var childrenString = String(children);
  1736. true ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Objects are not valid as a React child (found: %s).%s', childrenString === '[object Object]' ? 'object with keys {' + Object.keys(children).join(', ') + '}' : childrenString, addendum) : _prodInvariant('31', childrenString === '[object Object]' ? 'object with keys {' + Object.keys(children).join(', ') + '}' : childrenString, addendum) : void 0;
  1737. }
  1738. }
  1739. return subtreeCount;
  1740. }
  1741. /**
  1742. * Traverses children that are typically specified as `props.children`, but
  1743. * might also be specified through attributes:
  1744. *
  1745. * - `traverseAllChildren(this.props.children, ...)`
  1746. * - `traverseAllChildren(this.props.leftPanelChildren, ...)`
  1747. *
  1748. * The `traverseContext` is an optional argument that is passed through the
  1749. * entire traversal. It can be used to store accumulations or anything else that
  1750. * the callback might find relevant.
  1751. *
  1752. * @param {?*} children Children tree object.
  1753. * @param {!function} callback To invoke upon traversing each child.
  1754. * @param {?*} traverseContext Context for traversal.
  1755. * @return {!number} The number of children in this subtree.
  1756. */
  1757. function traverseAllChildren(children, callback, traverseContext) {
  1758. if (children == null) {
  1759. return 0;
  1760. }
  1761. return traverseAllChildrenImpl(children, '', callback, traverseContext);
  1762. }
  1763. module.exports = traverseAllChildren;
  1764. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
  1765. /***/ }),
  1766. /* 20 */
  1767. /***/ (function(module, exports) {
  1768. /**
  1769. * Copyright (c) 2013-present, Facebook, Inc.
  1770. *
  1771. * This source code is licensed under the MIT license found in the
  1772. * LICENSE file in the root directory of this source tree.
  1773. *
  1774. *
  1775. */
  1776. 'use strict';
  1777. /* global Symbol */
  1778. var ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator;
  1779. var FAUX_ITERATOR_SYMBOL = '@@iterator'; // Before Symbol spec.
  1780. /**
  1781. * Returns the iterator method function contained on the iterable object.
  1782. *
  1783. * Be sure to invoke the function with the iterable as context:
  1784. *
  1785. * var iteratorFn = getIteratorFn(myIterable);
  1786. * if (iteratorFn) {
  1787. * var iterator = iteratorFn.call(myIterable);
  1788. * ...
  1789. * }
  1790. *
  1791. * @param {?object} maybeIterable
  1792. * @return {?function}
  1793. */
  1794. function getIteratorFn(maybeIterable) {
  1795. var iteratorFn = maybeIterable && (ITERATOR_SYMBOL && maybeIterable[ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]);
  1796. if (typeof iteratorFn === 'function') {
  1797. return iteratorFn;
  1798. }
  1799. }
  1800. module.exports = getIteratorFn;
  1801. /***/ }),
  1802. /* 21 */
  1803. /***/ (function(module, exports) {
  1804. /**
  1805. * Copyright (c) 2013-present, Facebook, Inc.
  1806. *
  1807. * This source code is licensed under the MIT license found in the
  1808. * LICENSE file in the root directory of this source tree.
  1809. *
  1810. *
  1811. */
  1812. 'use strict';
  1813. /**
  1814. * Escape and wrap key so it is safe to use as a reactid
  1815. *
  1816. * @param {string} key to be escaped.
  1817. * @return {string} the escaped key.
  1818. */
  1819. function escape(key) {
  1820. var escapeRegex = /[=:]/g;
  1821. var escaperLookup = {
  1822. '=': '=0',
  1823. ':': '=2'
  1824. };
  1825. var escapedString = ('' + key).replace(escapeRegex, function (match) {
  1826. return escaperLookup[match];
  1827. });
  1828. return '$' + escapedString;
  1829. }
  1830. /**
  1831. * Unescape and unwrap key for human-readable display
  1832. *
  1833. * @param {string} key to unescape.
  1834. * @return {string} the unescaped key.
  1835. */
  1836. function unescape(key) {
  1837. var unescapeRegex = /(=0|=2)/g;
  1838. var unescaperLookup = {
  1839. '=0': '=',
  1840. '=2': ':'
  1841. };
  1842. var keySubstring = key[0] === '.' && key[1] === '$' ? key.substring(2) : key.substring(1);
  1843. return ('' + keySubstring).replace(unescapeRegex, function (match) {
  1844. return unescaperLookup[match];
  1845. });
  1846. }
  1847. var KeyEscapeUtils = {
  1848. escape: escape,
  1849. unescape: unescape
  1850. };
  1851. module.exports = KeyEscapeUtils;
  1852. /***/ }),
  1853. /* 22 */
  1854. /***/ (function(module, exports, __webpack_require__) {
  1855. /* WEBPACK VAR INJECTION */(function(process) {/**
  1856. * Copyright (c) 2013-present, Facebook, Inc.
  1857. *
  1858. * This source code is licensed under the MIT license found in the
  1859. * LICENSE file in the root directory of this source tree.
  1860. *
  1861. */
  1862. 'use strict';
  1863. var ReactElement = __webpack_require__(16);
  1864. /**
  1865. * Create a factory that creates HTML tag elements.
  1866. *
  1867. * @private
  1868. */
  1869. var createDOMFactory = ReactElement.createFactory;
  1870. if (process.env.NODE_ENV !== 'production') {
  1871. var ReactElementValidator = __webpack_require__(23);
  1872. createDOMFactory = ReactElementValidator.createFactory;
  1873. }
  1874. /**
  1875. * Creates a mapping from supported HTML tags to `ReactDOMComponent` classes.
  1876. *
  1877. * @public
  1878. */
  1879. var ReactDOMFactories = {
  1880. a: createDOMFactory('a'),
  1881. abbr: createDOMFactory('abbr'),
  1882. address: createDOMFactory('address'),
  1883. area: createDOMFactory('area'),
  1884. article: createDOMFactory('article'),
  1885. aside: createDOMFactory('aside'),
  1886. audio: createDOMFactory('audio'),
  1887. b: createDOMFactory('b'),
  1888. base: createDOMFactory('base'),
  1889. bdi: createDOMFactory('bdi'),
  1890. bdo: createDOMFactory('bdo'),
  1891. big: createDOMFactory('big'),
  1892. blockquote: createDOMFactory('blockquote'),
  1893. body: createDOMFactory('body'),
  1894. br: createDOMFactory('br'),
  1895. button: createDOMFactory('button'),
  1896. canvas: createDOMFactory('canvas'),
  1897. caption: createDOMFactory('caption'),
  1898. cite: createDOMFactory('cite'),
  1899. code: createDOMFactory('code'),
  1900. col: createDOMFactory('col'),
  1901. colgroup: createDOMFactory('colgroup'),
  1902. data: createDOMFactory('data'),
  1903. datalist: createDOMFactory('datalist'),
  1904. dd: createDOMFactory('dd'),
  1905. del: createDOMFactory('del'),
  1906. details: createDOMFactory('details'),
  1907. dfn: createDOMFactory('dfn'),
  1908. dialog: createDOMFactory('dialog'),
  1909. div: createDOMFactory('div'),
  1910. dl: createDOMFactory('dl'),
  1911. dt: createDOMFactory('dt'),
  1912. em: createDOMFactory('em'),
  1913. embed: createDOMFactory('embed'),
  1914. fieldset: createDOMFactory('fieldset'),
  1915. figcaption: createDOMFactory('figcaption'),
  1916. figure: createDOMFactory('figure'),
  1917. footer: createDOMFactory('footer'),
  1918. form: createDOMFactory('form'),
  1919. h1: createDOMFactory('h1'),
  1920. h2: createDOMFactory('h2'),
  1921. h3: createDOMFactory('h3'),
  1922. h4: createDOMFactory('h4'),
  1923. h5: createDOMFactory('h5'),
  1924. h6: createDOMFactory('h6'),
  1925. head: createDOMFactory('head'),
  1926. header: createDOMFactory('header'),
  1927. hgroup: createDOMFactory('hgroup'),
  1928. hr: createDOMFactory('hr'),
  1929. html: createDOMFactory('html'),
  1930. i: createDOMFactory('i'),
  1931. iframe: createDOMFactory('iframe'),
  1932. img: createDOMFactory('img'),
  1933. input: createDOMFactory('input'),
  1934. ins: createDOMFactory('ins'),
  1935. kbd: createDOMFactory('kbd'),
  1936. keygen: createDOMFactory('keygen'),
  1937. label: createDOMFactory('label'),
  1938. legend: createDOMFactory('legend'),
  1939. li: createDOMFactory('li'),
  1940. link: createDOMFactory('link'),
  1941. main: createDOMFactory('main'),
  1942. map: createDOMFactory('map'),
  1943. mark: createDOMFactory('mark'),
  1944. menu: createDOMFactory('menu'),
  1945. menuitem: createDOMFactory('menuitem'),
  1946. meta: createDOMFactory('meta'),
  1947. meter: createDOMFactory('meter'),
  1948. nav: createDOMFactory('nav'),
  1949. noscript: createDOMFactory('noscript'),
  1950. object: createDOMFactory('object'),
  1951. ol: createDOMFactory('ol'),
  1952. optgroup: createDOMFactory('optgroup'),
  1953. option: createDOMFactory('option'),
  1954. output: createDOMFactory('output'),
  1955. p: createDOMFactory('p'),
  1956. param: createDOMFactory('param'),
  1957. picture: createDOMFactory('picture'),
  1958. pre: createDOMFactory('pre'),
  1959. progress: createDOMFactory('progress'),
  1960. q: createDOMFactory('q'),
  1961. rp: createDOMFactory('rp'),
  1962. rt: createDOMFactory('rt'),
  1963. ruby: createDOMFactory('ruby'),
  1964. s: createDOMFactory('s'),
  1965. samp: createDOMFactory('samp'),
  1966. script: createDOMFactory('script'),
  1967. section: createDOMFactory('section'),
  1968. select: createDOMFactory('select'),
  1969. small: createDOMFactory('small'),
  1970. source: createDOMFactory('source'),
  1971. span: createDOMFactory('span'),
  1972. strong: createDOMFactory('strong'),
  1973. style: createDOMFactory('style'),
  1974. sub: createDOMFactory('sub'),
  1975. summary: createDOMFactory('summary'),
  1976. sup: createDOMFactory('sup'),
  1977. table: createDOMFactory('table'),
  1978. tbody: createDOMFactory('tbody'),
  1979. td: createDOMFactory('td'),
  1980. textarea: createDOMFactory('textarea'),
  1981. tfoot: createDOMFactory('tfoot'),
  1982. th: createDOMFactory('th'),
  1983. thead: createDOMFactory('thead'),
  1984. time: createDOMFactory('time'),
  1985. title: createDOMFactory('title'),
  1986. tr: createDOMFactory('tr'),
  1987. track: createDOMFactory('track'),
  1988. u: createDOMFactory('u'),
  1989. ul: createDOMFactory('ul'),
  1990. 'var': createDOMFactory('var'),
  1991. video: createDOMFactory('video'),
  1992. wbr: createDOMFactory('wbr'),
  1993. // SVG
  1994. circle: createDOMFactory('circle'),
  1995. clipPath: createDOMFactory('clipPath'),
  1996. defs: createDOMFactory('defs'),
  1997. ellipse: createDOMFactory('ellipse'),
  1998. g: createDOMFactory('g'),
  1999. image: createDOMFactory('image'),
  2000. line: createDOMFactory('line'),
  2001. linearGradient: createDOMFactory('linearGradient'),
  2002. mask: createDOMFactory('mask'),
  2003. path: createDOMFactory('path'),
  2004. pattern: createDOMFactory('pattern'),
  2005. polygon: createDOMFactory('polygon'),
  2006. polyline: createDOMFactory('polyline'),
  2007. radialGradient: createDOMFactory('radialGradient'),
  2008. rect: createDOMFactory('rect'),
  2009. stop: createDOMFactory('stop'),
  2010. svg: createDOMFactory('svg'),
  2011. text: createDOMFactory('text'),
  2012. tspan: createDOMFactory('tspan')
  2013. };
  2014. module.exports = ReactDOMFactories;
  2015. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
  2016. /***/ }),
  2017. /* 23 */
  2018. /***/ (function(module, exports, __webpack_require__) {
  2019. /* WEBPACK VAR INJECTION */(function(process) {/**
  2020. * Copyright (c) 2014-present, Facebook, Inc.
  2021. *
  2022. * This source code is licensed under the MIT license found in the
  2023. * LICENSE file in the root directory of this source tree.
  2024. *
  2025. */
  2026. /**
  2027. * ReactElementValidator provides a wrapper around a element factory
  2028. * which validates the props passed to the element. This is intended to be
  2029. * used only in DEV and could be replaced by a static type checker for languages
  2030. * that support it.
  2031. */
  2032. 'use strict';
  2033. var ReactCurrentOwner = __webpack_require__(17);
  2034. var ReactComponentTreeHook = __webpack_require__(24);
  2035. var ReactElement = __webpack_require__(16);
  2036. var checkReactTypeSpec = __webpack_require__(25);
  2037. var canDefineProperty = __webpack_require__(10);
  2038. var getIteratorFn = __webpack_require__(20);
  2039. var warning = __webpack_require__(8);
  2040. var lowPriorityWarning = __webpack_require__(13);
  2041. function getDeclarationErrorAddendum() {
  2042. if (ReactCurrentOwner.current) {
  2043. var name = ReactCurrentOwner.current.getName();
  2044. if (name) {
  2045. return ' Check the render method of `' + name + '`.';
  2046. }
  2047. }
  2048. return '';
  2049. }
  2050. function getSourceInfoErrorAddendum(elementProps) {
  2051. if (elementProps !== null && elementProps !== undefined && elementProps.__source !== undefined) {
  2052. var source = elementProps.__source;
  2053. var fileName = source.fileName.replace(/^.*[\\\/]/, '');
  2054. var lineNumber = source.lineNumber;
  2055. return ' Check your code at ' + fileName + ':' + lineNumber + '.';
  2056. }
  2057. return '';
  2058. }
  2059. /**
  2060. * Warn if there's no key explicitly set on dynamic arrays of children or
  2061. * object keys are not valid. This allows us to keep track of children between
  2062. * updates.
  2063. */
  2064. var ownerHasKeyUseWarning = {};
  2065. function getCurrentComponentErrorInfo(parentType) {
  2066. var info = getDeclarationErrorAddendum();
  2067. if (!info) {
  2068. var parentName = typeof parentType === 'string' ? parentType : parentType.displayName || parentType.name;
  2069. if (parentName) {
  2070. info = ' Check the top-level render call using <' + parentName + '>.';
  2071. }
  2072. }
  2073. return info;
  2074. }
  2075. /**
  2076. * Warn if the element doesn't have an explicit key assigned to it.
  2077. * This element is in an array. The array could grow and shrink or be
  2078. * reordered. All children that haven't already been validated are required to
  2079. * have a "key" property assigned to it. Error statuses are cached so a warning
  2080. * will only be shown once.
  2081. *
  2082. * @internal
  2083. * @param {ReactElement} element Element that requires a key.
  2084. * @param {*} parentType element's parent's type.
  2085. */
  2086. function validateExplicitKey(element, parentType) {
  2087. if (!element._store || element._store.validated || element.key != null) {
  2088. return;
  2089. }
  2090. element._store.validated = true;
  2091. var memoizer = ownerHasKeyUseWarning.uniqueKey || (ownerHasKeyUseWarning.uniqueKey = {});
  2092. var currentComponentErrorInfo = getCurrentComponentErrorInfo(parentType);
  2093. if (memoizer[currentComponentErrorInfo]) {
  2094. return;
  2095. }
  2096. memoizer[currentComponentErrorInfo] = true;
  2097. // Usually the current owner is the offender, but if it accepts children as a
  2098. // property, it may be the creator of the child that's responsible for
  2099. // assigning it a key.
  2100. var childOwner = '';
  2101. if (element && element._owner && element._owner !== ReactCurrentOwner.current) {
  2102. // Give the component that originally created this child.
  2103. childOwner = ' It was passed a child from ' + element._owner.getName() + '.';
  2104. }
  2105. process.env.NODE_ENV !== 'production' ? warning(false, 'Each child in an array or iterator should have a unique "key" prop.' + '%s%s See https://fb.me/react-warning-keys for more information.%s', currentComponentErrorInfo, childOwner, ReactComponentTreeHook.getCurrentStackAddendum(element)) : void 0;
  2106. }
  2107. /**
  2108. * Ensure that every element either is passed in a static location, in an
  2109. * array with an explicit keys property defined, or in an object literal
  2110. * with valid key property.
  2111. *
  2112. * @internal
  2113. * @param {ReactNode} node Statically passed child of any type.
  2114. * @param {*} parentType node's parent's type.
  2115. */
  2116. function validateChildKeys(node, parentType) {
  2117. if (typeof node !== 'object') {
  2118. return;
  2119. }
  2120. if (Array.isArray(node)) {
  2121. for (var i = 0; i < node.length; i++) {
  2122. var child = node[i];
  2123. if (ReactElement.isValidElement(child)) {
  2124. validateExplicitKey(child, parentType);
  2125. }
  2126. }
  2127. } else if (ReactElement.isValidElement(node)) {
  2128. // This element was passed in a valid location.
  2129. if (node._store) {
  2130. node._store.validated = true;
  2131. }
  2132. } else if (node) {
  2133. var iteratorFn = getIteratorFn(node);
  2134. // Entry iterators provide implicit keys.
  2135. if (iteratorFn) {
  2136. if (iteratorFn !== node.entries) {
  2137. var iterator = iteratorFn.call(node);
  2138. var step;
  2139. while (!(step = iterator.next()).done) {
  2140. if (ReactElement.isValidElement(step.value)) {
  2141. validateExplicitKey(step.value, parentType);
  2142. }
  2143. }
  2144. }
  2145. }
  2146. }
  2147. }
  2148. /**
  2149. * Given an element, validate that its props follow the propTypes definition,
  2150. * provided by the type.
  2151. *
  2152. * @param {ReactElement} element
  2153. */
  2154. function validatePropTypes(element) {
  2155. var componentClass = element.type;
  2156. if (typeof componentClass !== 'function') {
  2157. return;
  2158. }
  2159. var name = componentClass.displayName || componentClass.name;
  2160. if (componentClass.propTypes) {
  2161. checkReactTypeSpec(componentClass.propTypes, element.props, 'prop', name, element, null);
  2162. }
  2163. if (typeof componentClass.getDefaultProps === 'function') {
  2164. process.env.NODE_ENV !== 'production' ? warning(componentClass.getDefaultProps.isReactClassApproved, 'getDefaultProps is only used on classic React.createClass ' + 'definitions. Use a static property named `defaultProps` instead.') : void 0;
  2165. }
  2166. }
  2167. var ReactElementValidator = {
  2168. createElement: function (type, props, children) {
  2169. var validType = typeof type === 'string' || typeof type === 'function';
  2170. // We warn in this case but don't throw. We expect the element creation to
  2171. // succeed and there will likely be errors in render.
  2172. if (!validType) {
  2173. if (typeof type !== 'function' && typeof type !== 'string') {
  2174. var info = '';
  2175. if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) {
  2176. info += ' You likely forgot to export your component from the file ' + "it's defined in.";
  2177. }
  2178. var sourceInfo = getSourceInfoErrorAddendum(props);
  2179. if (sourceInfo) {
  2180. info += sourceInfo;
  2181. } else {
  2182. info += getDeclarationErrorAddendum();
  2183. }
  2184. info += ReactComponentTreeHook.getCurrentStackAddendum();
  2185. var currentSource = props !== null && props !== undefined && props.__source !== undefined ? props.__source : null;
  2186. ReactComponentTreeHook.pushNonStandardWarningStack(true, currentSource);
  2187. process.env.NODE_ENV !== 'production' ? warning(false, 'React.createElement: type is invalid -- expected a string (for ' + 'built-in components) or a class/function (for composite ' + 'components) but got: %s.%s', type == null ? type : typeof type, info) : void 0;
  2188. ReactComponentTreeHook.popNonStandardWarningStack();
  2189. }
  2190. }
  2191. var element = ReactElement.createElement.apply(this, arguments);
  2192. // The result can be nullish if a mock or a custom function is used.
  2193. // TODO: Drop this when these are no longer allowed as the type argument.
  2194. if (element == null) {
  2195. return element;
  2196. }
  2197. // Skip key warning if the type isn't valid since our key validation logic
  2198. // doesn't expect a non-string/function type and can throw confusing errors.
  2199. // We don't want exception behavior to differ between dev and prod.
  2200. // (Rendering will throw with a helpful message and as soon as the type is
  2201. // fixed, the key warnings will appear.)
  2202. if (validType) {
  2203. for (var i = 2; i < arguments.length; i++) {
  2204. validateChildKeys(arguments[i], type);
  2205. }
  2206. }
  2207. validatePropTypes(element);
  2208. return element;
  2209. },
  2210. createFactory: function (type) {
  2211. var validatedFactory = ReactElementValidator.createElement.bind(null, type);
  2212. // Legacy hook TODO: Warn if this is accessed
  2213. validatedFactory.type = type;
  2214. if (process.env.NODE_ENV !== 'production') {
  2215. if (canDefineProperty) {
  2216. Object.defineProperty(validatedFactory, 'type', {
  2217. enumerable: false,
  2218. get: function () {
  2219. lowPriorityWarning(false, 'Factory.type is deprecated. Access the class directly ' + 'before passing it to createFactory.');
  2220. Object.defineProperty(this, 'type', {
  2221. value: type
  2222. });
  2223. return type;
  2224. }
  2225. });
  2226. }
  2227. }
  2228. return validatedFactory;
  2229. },
  2230. cloneElement: function (element, props, children) {
  2231. var newElement = ReactElement.cloneElement.apply(this, arguments);
  2232. for (var i = 2; i < arguments.length; i++) {
  2233. validateChildKeys(arguments[i], newElement.type);
  2234. }
  2235. validatePropTypes(newElement);
  2236. return newElement;
  2237. }
  2238. };
  2239. module.exports = ReactElementValidator;
  2240. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
  2241. /***/ }),
  2242. /* 24 */
  2243. /***/ (function(module, exports, __webpack_require__) {
  2244. /* WEBPACK VAR INJECTION */(function(process) {/**
  2245. * Copyright (c) 2016-present, Facebook, Inc.
  2246. *
  2247. * This source code is licensed under the MIT license found in the
  2248. * LICENSE file in the root directory of this source tree.
  2249. *
  2250. *
  2251. */
  2252. 'use strict';
  2253. var _prodInvariant = __webpack_require__(6);
  2254. var ReactCurrentOwner = __webpack_require__(17);
  2255. var invariant = __webpack_require__(12);
  2256. var warning = __webpack_require__(8);
  2257. function isNative(fn) {
  2258. // Based on isNative() from Lodash
  2259. var funcToString = Function.prototype.toString;
  2260. var hasOwnProperty = Object.prototype.hasOwnProperty;
  2261. var reIsNative = RegExp('^' + funcToString
  2262. // Take an example native function source for comparison
  2263. .call(hasOwnProperty
  2264. // Strip regex characters so we can use it for regex
  2265. ).replace(/[\\^$.*+?()[\]{}|]/g, '\\$&'
  2266. // Remove hasOwnProperty from the template to make it generic
  2267. ).replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$');
  2268. try {
  2269. var source = funcToString.call(fn);
  2270. return reIsNative.test(source);
  2271. } catch (err) {
  2272. return false;
  2273. }
  2274. }
  2275. var canUseCollections =
  2276. // Array.from
  2277. typeof Array.from === 'function' &&
  2278. // Map
  2279. typeof Map === 'function' && isNative(Map) &&
  2280. // Map.prototype.keys
  2281. Map.prototype != null && typeof Map.prototype.keys === 'function' && isNative(Map.prototype.keys) &&
  2282. // Set
  2283. typeof Set === 'function' && isNative(Set) &&
  2284. // Set.prototype.keys
  2285. Set.prototype != null && typeof Set.prototype.keys === 'function' && isNative(Set.prototype.keys);
  2286. var setItem;
  2287. var getItem;
  2288. var removeItem;
  2289. var getItemIDs;
  2290. var addRoot;
  2291. var removeRoot;
  2292. var getRootIDs;
  2293. if (canUseCollections) {
  2294. var itemMap = new Map();
  2295. var rootIDSet = new Set();
  2296. setItem = function (id, item) {
  2297. itemMap.set(id, item);
  2298. };
  2299. getItem = function (id) {
  2300. return itemMap.get(id);
  2301. };
  2302. removeItem = function (id) {
  2303. itemMap['delete'](id);
  2304. };
  2305. getItemIDs = function () {
  2306. return Array.from(itemMap.keys());
  2307. };
  2308. addRoot = function (id) {
  2309. rootIDSet.add(id);
  2310. };
  2311. removeRoot = function (id) {
  2312. rootIDSet['delete'](id);
  2313. };
  2314. getRootIDs = function () {
  2315. return Array.from(rootIDSet.keys());
  2316. };
  2317. } else {
  2318. var itemByKey = {};
  2319. var rootByKey = {};
  2320. // Use non-numeric keys to prevent V8 performance issues:
  2321. // https://github.com/facebook/react/pull/7232
  2322. var getKeyFromID = function (id) {
  2323. return '.' + id;
  2324. };
  2325. var getIDFromKey = function (key) {
  2326. return parseInt(key.substr(1), 10);
  2327. };
  2328. setItem = function (id, item) {
  2329. var key = getKeyFromID(id);
  2330. itemByKey[key] = item;
  2331. };
  2332. getItem = function (id) {
  2333. var key = getKeyFromID(id);
  2334. return itemByKey[key];
  2335. };
  2336. removeItem = function (id) {
  2337. var key = getKeyFromID(id);
  2338. delete itemByKey[key];
  2339. };
  2340. getItemIDs = function () {
  2341. return Object.keys(itemByKey).map(getIDFromKey);
  2342. };
  2343. addRoot = function (id) {
  2344. var key = getKeyFromID(id);
  2345. rootByKey[key] = true;
  2346. };
  2347. removeRoot = function (id) {
  2348. var key = getKeyFromID(id);
  2349. delete rootByKey[key];
  2350. };
  2351. getRootIDs = function () {
  2352. return Object.keys(rootByKey).map(getIDFromKey);
  2353. };
  2354. }
  2355. var unmountedIDs = [];
  2356. function purgeDeep(id) {
  2357. var item = getItem(id);
  2358. if (item) {
  2359. var childIDs = item.childIDs;
  2360. removeItem(id);
  2361. childIDs.forEach(purgeDeep);
  2362. }
  2363. }
  2364. function describeComponentFrame(name, source, ownerName) {
  2365. return '\n in ' + (name || 'Unknown') + (source ? ' (at ' + source.fileName.replace(/^.*[\\\/]/, '') + ':' + source.lineNumber + ')' : ownerName ? ' (created by ' + ownerName + ')' : '');
  2366. }
  2367. function getDisplayName(element) {
  2368. if (element == null) {
  2369. return '#empty';
  2370. } else if (typeof element === 'string' || typeof element === 'number') {
  2371. return '#text';
  2372. } else if (typeof element.type === 'string') {
  2373. return element.type;
  2374. } else {
  2375. return element.type.displayName || element.type.name || 'Unknown';
  2376. }
  2377. }
  2378. function describeID(id) {
  2379. var name = ReactComponentTreeHook.getDisplayName(id);
  2380. var element = ReactComponentTreeHook.getElement(id);
  2381. var ownerID = ReactComponentTreeHook.getOwnerID(id);
  2382. var ownerName;
  2383. if (ownerID) {
  2384. ownerName = ReactComponentTreeHook.getDisplayName(ownerID);
  2385. }
  2386. process.env.NODE_ENV !== 'production' ? warning(element, 'ReactComponentTreeHook: Missing React element for debugID %s when ' + 'building stack', id) : void 0;
  2387. return describeComponentFrame(name, element && element._source, ownerName);
  2388. }
  2389. var ReactComponentTreeHook = {
  2390. onSetChildren: function (id, nextChildIDs) {
  2391. var item = getItem(id);
  2392. !item ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Item must have been set') : _prodInvariant('144') : void 0;
  2393. item.childIDs = nextChildIDs;
  2394. for (var i = 0; i < nextChildIDs.length; i++) {
  2395. var nextChildID = nextChildIDs[i];
  2396. var nextChild = getItem(nextChildID);
  2397. !nextChild ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Expected hook events to fire for the child before its parent includes it in onSetChildren().') : _prodInvariant('140') : void 0;
  2398. !(nextChild.childIDs != null || typeof nextChild.element !== 'object' || nextChild.element == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Expected onSetChildren() to fire for a container child before its parent includes it in onSetChildren().') : _prodInvariant('141') : void 0;
  2399. !nextChild.isMounted ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Expected onMountComponent() to fire for the child before its parent includes it in onSetChildren().') : _prodInvariant('71') : void 0;
  2400. if (nextChild.parentID == null) {
  2401. nextChild.parentID = id;
  2402. // TODO: This shouldn't be necessary but mounting a new root during in
  2403. // componentWillMount currently causes not-yet-mounted components to
  2404. // be purged from our tree data so their parent id is missing.
  2405. }
  2406. !(nextChild.parentID === id) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Expected onBeforeMountComponent() parent and onSetChildren() to be consistent (%s has parents %s and %s).', nextChildID, nextChild.parentID, id) : _prodInvariant('142', nextChildID, nextChild.parentID, id) : void 0;
  2407. }
  2408. },
  2409. onBeforeMountComponent: function (id, element, parentID) {
  2410. var item = {
  2411. element: element,
  2412. parentID: parentID,
  2413. text: null,
  2414. childIDs: [],
  2415. isMounted: false,
  2416. updateCount: 0
  2417. };
  2418. setItem(id, item);
  2419. },
  2420. onBeforeUpdateComponent: function (id, element) {
  2421. var item = getItem(id);
  2422. if (!item || !item.isMounted) {
  2423. // We may end up here as a result of setState() in componentWillUnmount().
  2424. // In this case, ignore the element.
  2425. return;
  2426. }
  2427. item.element = element;
  2428. },
  2429. onMountComponent: function (id) {
  2430. var item = getItem(id);
  2431. !item ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Item must have been set') : _prodInvariant('144') : void 0;
  2432. item.isMounted = true;
  2433. var isRoot = item.parentID === 0;
  2434. if (isRoot) {
  2435. addRoot(id);
  2436. }
  2437. },
  2438. onUpdateComponent: function (id) {
  2439. var item = getItem(id);
  2440. if (!item || !item.isMounted) {
  2441. // We may end up here as a result of setState() in componentWillUnmount().
  2442. // In this case, ignore the element.
  2443. return;
  2444. }
  2445. item.updateCount++;
  2446. },
  2447. onUnmountComponent: function (id) {
  2448. var item = getItem(id);
  2449. if (item) {
  2450. // We need to check if it exists.
  2451. // `item` might not exist if it is inside an error boundary, and a sibling
  2452. // error boundary child threw while mounting. Then this instance never
  2453. // got a chance to mount, but it still gets an unmounting event during
  2454. // the error boundary cleanup.
  2455. item.isMounted = false;
  2456. var isRoot = item.parentID === 0;
  2457. if (isRoot) {
  2458. removeRoot(id);
  2459. }
  2460. }
  2461. unmountedIDs.push(id);
  2462. },
  2463. purgeUnmountedComponents: function () {
  2464. if (ReactComponentTreeHook._preventPurging) {
  2465. // Should only be used for testing.
  2466. return;
  2467. }
  2468. for (var i = 0; i < unmountedIDs.length; i++) {
  2469. var id = unmountedIDs[i];
  2470. purgeDeep(id);
  2471. }
  2472. unmountedIDs.length = 0;
  2473. },
  2474. isMounted: function (id) {
  2475. var item = getItem(id);
  2476. return item ? item.isMounted : false;
  2477. },
  2478. getCurrentStackAddendum: function (topElement) {
  2479. var info = '';
  2480. if (topElement) {
  2481. var name = getDisplayName(topElement);
  2482. var owner = topElement._owner;
  2483. info += describeComponentFrame(name, topElement._source, owner && owner.getName());
  2484. }
  2485. var currentOwner = ReactCurrentOwner.current;
  2486. var id = currentOwner && currentOwner._debugID;
  2487. info += ReactComponentTreeHook.getStackAddendumByID(id);
  2488. return info;
  2489. },
  2490. getStackAddendumByID: function (id) {
  2491. var info = '';
  2492. while (id) {
  2493. info += describeID(id);
  2494. id = ReactComponentTreeHook.getParentID(id);
  2495. }
  2496. return info;
  2497. },
  2498. getChildIDs: function (id) {
  2499. var item = getItem(id);
  2500. return item ? item.childIDs : [];
  2501. },
  2502. getDisplayName: function (id) {
  2503. var element = ReactComponentTreeHook.getElement(id);
  2504. if (!element) {
  2505. return null;
  2506. }
  2507. return getDisplayName(element);
  2508. },
  2509. getElement: function (id) {
  2510. var item = getItem(id);
  2511. return item ? item.element : null;
  2512. },
  2513. getOwnerID: function (id) {
  2514. var element = ReactComponentTreeHook.getElement(id);
  2515. if (!element || !element._owner) {
  2516. return null;
  2517. }
  2518. return element._owner._debugID;
  2519. },
  2520. getParentID: function (id) {
  2521. var item = getItem(id);
  2522. return item ? item.parentID : null;
  2523. },
  2524. getSource: function (id) {
  2525. var item = getItem(id);
  2526. var element = item ? item.element : null;
  2527. var source = element != null ? element._source : null;
  2528. return source;
  2529. },
  2530. getText: function (id) {
  2531. var element = ReactComponentTreeHook.getElement(id);
  2532. if (typeof element === 'string') {
  2533. return element;
  2534. } else if (typeof element === 'number') {
  2535. return '' + element;
  2536. } else {
  2537. return null;
  2538. }
  2539. },
  2540. getUpdateCount: function (id) {
  2541. var item = getItem(id);
  2542. return item ? item.updateCount : 0;
  2543. },
  2544. getRootIDs: getRootIDs,
  2545. getRegisteredIDs: getItemIDs,
  2546. pushNonStandardWarningStack: function (isCreatingElement, currentSource) {
  2547. if (typeof console.reactStack !== 'function') {
  2548. return;
  2549. }
  2550. var stack = [];
  2551. var currentOwner = ReactCurrentOwner.current;
  2552. var id = currentOwner && currentOwner._debugID;
  2553. try {
  2554. if (isCreatingElement) {
  2555. stack.push({
  2556. name: id ? ReactComponentTreeHook.getDisplayName(id) : null,
  2557. fileName: currentSource ? currentSource.fileName : null,
  2558. lineNumber: currentSource ? currentSource.lineNumber : null
  2559. });
  2560. }
  2561. while (id) {
  2562. var element = ReactComponentTreeHook.getElement(id);
  2563. var parentID = ReactComponentTreeHook.getParentID(id);
  2564. var ownerID = ReactComponentTreeHook.getOwnerID(id);
  2565. var ownerName = ownerID ? ReactComponentTreeHook.getDisplayName(ownerID) : null;
  2566. var source = element && element._source;
  2567. stack.push({
  2568. name: ownerName,
  2569. fileName: source ? source.fileName : null,
  2570. lineNumber: source ? source.lineNumber : null
  2571. });
  2572. id = parentID;
  2573. }
  2574. } catch (err) {
  2575. // Internal state is messed up.
  2576. // Stop building the stack (it's just a nice to have).
  2577. }
  2578. console.reactStack(stack);
  2579. },
  2580. popNonStandardWarningStack: function () {
  2581. if (typeof console.reactStackEnd !== 'function') {
  2582. return;
  2583. }
  2584. console.reactStackEnd();
  2585. }
  2586. };
  2587. module.exports = ReactComponentTreeHook;
  2588. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
  2589. /***/ }),
  2590. /* 25 */
  2591. /***/ (function(module, exports, __webpack_require__) {
  2592. /* WEBPACK VAR INJECTION */(function(process) {/**
  2593. * Copyright (c) 2013-present, Facebook, Inc.
  2594. *
  2595. * This source code is licensed under the MIT license found in the
  2596. * LICENSE file in the root directory of this source tree.
  2597. *
  2598. */
  2599. 'use strict';
  2600. var _prodInvariant = __webpack_require__(6);
  2601. var ReactPropTypeLocationNames = __webpack_require__(26);
  2602. var ReactPropTypesSecret = __webpack_require__(27);
  2603. var invariant = __webpack_require__(12);
  2604. var warning = __webpack_require__(8);
  2605. var ReactComponentTreeHook;
  2606. if (typeof process !== 'undefined' && process.env && process.env.NODE_ENV === 'test') {
  2607. // Temporary hack.
  2608. // Inline requires don't work well with Jest:
  2609. // https://github.com/facebook/react/issues/7240
  2610. // Remove the inline requires when we don't need them anymore:
  2611. // https://github.com/facebook/react/pull/7178
  2612. ReactComponentTreeHook = __webpack_require__(24);
  2613. }
  2614. var loggedTypeFailures = {};
  2615. /**
  2616. * Assert that the values match with the type specs.
  2617. * Error messages are memorized and will only be shown once.
  2618. *
  2619. * @param {object} typeSpecs Map of name to a ReactPropType
  2620. * @param {object} values Runtime values that need to be type-checked
  2621. * @param {string} location e.g. "prop", "context", "child context"
  2622. * @param {string} componentName Name of the component for error messages.
  2623. * @param {?object} element The React element that is being type-checked
  2624. * @param {?number} debugID The React component instance that is being type-checked
  2625. * @private
  2626. */
  2627. function checkReactTypeSpec(typeSpecs, values, location, componentName, element, debugID) {
  2628. for (var typeSpecName in typeSpecs) {
  2629. if (typeSpecs.hasOwnProperty(typeSpecName)) {
  2630. var error;
  2631. // Prop type validation may throw. In case they do, we don't want to
  2632. // fail the render phase where it didn't fail before. So we log it.
  2633. // After these have been cleaned up, we'll let them throw.
  2634. try {
  2635. // This is intentionally an invariant that gets caught. It's the same
  2636. // behavior as without this statement except with a better message.
  2637. !(typeof typeSpecs[typeSpecName] === 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s: %s type `%s` is invalid; it must be a function, usually from React.PropTypes.', componentName || 'React class', ReactPropTypeLocationNames[location], typeSpecName) : _prodInvariant('84', componentName || 'React class', ReactPropTypeLocationNames[location], typeSpecName) : void 0;
  2638. error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, ReactPropTypesSecret);
  2639. } catch (ex) {
  2640. error = ex;
  2641. }
  2642. process.env.NODE_ENV !== 'production' ? warning(!error || error instanceof Error, '%s: type specification of %s `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', ReactPropTypeLocationNames[location], typeSpecName, typeof error) : void 0;
  2643. if (error instanceof Error && !(error.message in loggedTypeFailures)) {
  2644. // Only monitor this failure once because there tends to be a lot of the
  2645. // same error.
  2646. loggedTypeFailures[error.message] = true;
  2647. var componentStackInfo = '';
  2648. if (process.env.NODE_ENV !== 'production') {
  2649. if (!ReactComponentTreeHook) {
  2650. ReactComponentTreeHook = __webpack_require__(24);
  2651. }
  2652. if (debugID !== null) {
  2653. componentStackInfo = ReactComponentTreeHook.getStackAddendumByID(debugID);
  2654. } else if (element !== null) {
  2655. componentStackInfo = ReactComponentTreeHook.getCurrentStackAddendum(element);
  2656. }
  2657. }
  2658. process.env.NODE_ENV !== 'production' ? warning(false, 'Failed %s type: %s%s', location, error.message, componentStackInfo) : void 0;
  2659. }
  2660. }
  2661. }
  2662. }
  2663. module.exports = checkReactTypeSpec;
  2664. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
  2665. /***/ }),
  2666. /* 26 */
  2667. /***/ (function(module, exports, __webpack_require__) {
  2668. /* WEBPACK VAR INJECTION */(function(process) {/**
  2669. * Copyright (c) 2013-present, Facebook, Inc.
  2670. *
  2671. * This source code is licensed under the MIT license found in the
  2672. * LICENSE file in the root directory of this source tree.
  2673. *
  2674. *
  2675. */
  2676. 'use strict';
  2677. var ReactPropTypeLocationNames = {};
  2678. if (process.env.NODE_ENV !== 'production') {
  2679. ReactPropTypeLocationNames = {
  2680. prop: 'prop',
  2681. context: 'context',
  2682. childContext: 'child context'
  2683. };
  2684. }
  2685. module.exports = ReactPropTypeLocationNames;
  2686. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
  2687. /***/ }),
  2688. /* 27 */
  2689. /***/ (function(module, exports) {
  2690. /**
  2691. * Copyright (c) 2013-present, Facebook, Inc.
  2692. *
  2693. * This source code is licensed under the MIT license found in the
  2694. * LICENSE file in the root directory of this source tree.
  2695. *
  2696. *
  2697. */
  2698. 'use strict';
  2699. var ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED';
  2700. module.exports = ReactPropTypesSecret;
  2701. /***/ }),
  2702. /* 28 */
  2703. /***/ (function(module, exports, __webpack_require__) {
  2704. /**
  2705. * Copyright (c) 2013-present, Facebook, Inc.
  2706. *
  2707. * This source code is licensed under the MIT license found in the
  2708. * LICENSE file in the root directory of this source tree.
  2709. *
  2710. */
  2711. 'use strict';
  2712. var _require = __webpack_require__(16),
  2713. isValidElement = _require.isValidElement;
  2714. var factory = __webpack_require__(29);
  2715. module.exports = factory(isValidElement);
  2716. /***/ }),
  2717. /* 29 */
  2718. /***/ (function(module, exports, __webpack_require__) {
  2719. /**
  2720. * Copyright (c) 2013-present, Facebook, Inc.
  2721. *
  2722. * This source code is licensed under the MIT license found in the
  2723. * LICENSE file in the root directory of this source tree.
  2724. */
  2725. 'use strict';
  2726. // React 15.5 references this module, and assumes PropTypes are still callable in production.
  2727. // Therefore we re-export development-only version with all the PropTypes checks here.
  2728. // However if one is migrating to the `prop-types` npm library, they will go through the
  2729. // `index.js` entry point, and it will branch depending on the environment.
  2730. var factory = __webpack_require__(30);
  2731. module.exports = function(isValidElement) {
  2732. // It is still allowed in 15.5.
  2733. var throwOnDirectAccess = false;
  2734. return factory(isValidElement, throwOnDirectAccess);
  2735. };
  2736. /***/ }),
  2737. /* 30 */
  2738. /***/ (function(module, exports, __webpack_require__) {
  2739. /* WEBPACK VAR INJECTION */(function(process) {/**
  2740. * Copyright (c) 2013-present, Facebook, Inc.
  2741. *
  2742. * This source code is licensed under the MIT license found in the
  2743. * LICENSE file in the root directory of this source tree.
  2744. */
  2745. 'use strict';
  2746. var emptyFunction = __webpack_require__(9);
  2747. var invariant = __webpack_require__(12);
  2748. var warning = __webpack_require__(8);
  2749. var assign = __webpack_require__(4);
  2750. var ReactPropTypesSecret = __webpack_require__(31);
  2751. var checkPropTypes = __webpack_require__(32);
  2752. module.exports = function(isValidElement, throwOnDirectAccess) {
  2753. /* global Symbol */
  2754. var ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator;
  2755. var FAUX_ITERATOR_SYMBOL = '@@iterator'; // Before Symbol spec.
  2756. /**
  2757. * Returns the iterator method function contained on the iterable object.
  2758. *
  2759. * Be sure to invoke the function with the iterable as context:
  2760. *
  2761. * var iteratorFn = getIteratorFn(myIterable);
  2762. * if (iteratorFn) {
  2763. * var iterator = iteratorFn.call(myIterable);
  2764. * ...
  2765. * }
  2766. *
  2767. * @param {?object} maybeIterable
  2768. * @return {?function}
  2769. */
  2770. function getIteratorFn(maybeIterable) {
  2771. var iteratorFn = maybeIterable && (ITERATOR_SYMBOL && maybeIterable[ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]);
  2772. if (typeof iteratorFn === 'function') {
  2773. return iteratorFn;
  2774. }
  2775. }
  2776. /**
  2777. * Collection of methods that allow declaration and validation of props that are
  2778. * supplied to React components. Example usage:
  2779. *
  2780. * var Props = require('ReactPropTypes');
  2781. * var MyArticle = React.createClass({
  2782. * propTypes: {
  2783. * // An optional string prop named "description".
  2784. * description: Props.string,
  2785. *
  2786. * // A required enum prop named "category".
  2787. * category: Props.oneOf(['News','Photos']).isRequired,
  2788. *
  2789. * // A prop named "dialog" that requires an instance of Dialog.
  2790. * dialog: Props.instanceOf(Dialog).isRequired
  2791. * },
  2792. * render: function() { ... }
  2793. * });
  2794. *
  2795. * A more formal specification of how these methods are used:
  2796. *
  2797. * type := array|bool|func|object|number|string|oneOf([...])|instanceOf(...)
  2798. * decl := ReactPropTypes.{type}(.isRequired)?
  2799. *
  2800. * Each and every declaration produces a function with the same signature. This
  2801. * allows the creation of custom validation functions. For example:
  2802. *
  2803. * var MyLink = React.createClass({
  2804. * propTypes: {
  2805. * // An optional string or URI prop named "href".
  2806. * href: function(props, propName, componentName) {
  2807. * var propValue = props[propName];
  2808. * if (propValue != null && typeof propValue !== 'string' &&
  2809. * !(propValue instanceof URI)) {
  2810. * return new Error(
  2811. * 'Expected a string or an URI for ' + propName + ' in ' +
  2812. * componentName
  2813. * );
  2814. * }
  2815. * }
  2816. * },
  2817. * render: function() {...}
  2818. * });
  2819. *
  2820. * @internal
  2821. */
  2822. var ANONYMOUS = '<<anonymous>>';
  2823. // Important!
  2824. // Keep this list in sync with production version in `./factoryWithThrowingShims.js`.
  2825. var ReactPropTypes = {
  2826. array: createPrimitiveTypeChecker('array'),
  2827. bool: createPrimitiveTypeChecker('boolean'),
  2828. func: createPrimitiveTypeChecker('function'),
  2829. number: createPrimitiveTypeChecker('number'),
  2830. object: createPrimitiveTypeChecker('object'),
  2831. string: createPrimitiveTypeChecker('string'),
  2832. symbol: createPrimitiveTypeChecker('symbol'),
  2833. any: createAnyTypeChecker(),
  2834. arrayOf: createArrayOfTypeChecker,
  2835. element: createElementTypeChecker(),
  2836. instanceOf: createInstanceTypeChecker,
  2837. node: createNodeChecker(),
  2838. objectOf: createObjectOfTypeChecker,
  2839. oneOf: createEnumTypeChecker,
  2840. oneOfType: createUnionTypeChecker,
  2841. shape: createShapeTypeChecker,
  2842. exact: createStrictShapeTypeChecker,
  2843. };
  2844. /**
  2845. * inlined Object.is polyfill to avoid requiring consumers ship their own
  2846. * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
  2847. */
  2848. /*eslint-disable no-self-compare*/
  2849. function is(x, y) {
  2850. // SameValue algorithm
  2851. if (x === y) {
  2852. // Steps 1-5, 7-10
  2853. // Steps 6.b-6.e: +0 != -0
  2854. return x !== 0 || 1 / x === 1 / y;
  2855. } else {
  2856. // Step 6.a: NaN == NaN
  2857. return x !== x && y !== y;
  2858. }
  2859. }
  2860. /*eslint-enable no-self-compare*/
  2861. /**
  2862. * We use an Error-like object for backward compatibility as people may call
  2863. * PropTypes directly and inspect their output. However, we don't use real
  2864. * Errors anymore. We don't inspect their stack anyway, and creating them
  2865. * is prohibitively expensive if they are created too often, such as what
  2866. * happens in oneOfType() for any type before the one that matched.
  2867. */
  2868. function PropTypeError(message) {
  2869. this.message = message;
  2870. this.stack = '';
  2871. }
  2872. // Make `instanceof Error` still work for returned errors.
  2873. PropTypeError.prototype = Error.prototype;
  2874. function createChainableTypeChecker(validate) {
  2875. if (process.env.NODE_ENV !== 'production') {
  2876. var manualPropTypeCallCache = {};
  2877. var manualPropTypeWarningCount = 0;
  2878. }
  2879. function checkType(isRequired, props, propName, componentName, location, propFullName, secret) {
  2880. componentName = componentName || ANONYMOUS;
  2881. propFullName = propFullName || propName;
  2882. if (secret !== ReactPropTypesSecret) {
  2883. if (throwOnDirectAccess) {
  2884. // New behavior only for users of `prop-types` package
  2885. invariant(
  2886. false,
  2887. 'Calling PropTypes validators directly is not supported by the `prop-types` package. ' +
  2888. 'Use `PropTypes.checkPropTypes()` to call them. ' +
  2889. 'Read more at http://fb.me/use-check-prop-types'
  2890. );
  2891. } else if (process.env.NODE_ENV !== 'production' && typeof console !== 'undefined') {
  2892. // Old behavior for people using React.PropTypes
  2893. var cacheKey = componentName + ':' + propName;
  2894. if (
  2895. !manualPropTypeCallCache[cacheKey] &&
  2896. // Avoid spamming the console because they are often not actionable except for lib authors
  2897. manualPropTypeWarningCount < 3
  2898. ) {
  2899. warning(
  2900. false,
  2901. 'You are manually calling a React.PropTypes validation ' +
  2902. 'function for the `%s` prop on `%s`. This is deprecated ' +
  2903. 'and will throw in the standalone `prop-types` package. ' +
  2904. 'You may be seeing this warning due to a third-party PropTypes ' +
  2905. 'library. See https://fb.me/react-warning-dont-call-proptypes ' + 'for details.',
  2906. propFullName,
  2907. componentName
  2908. );
  2909. manualPropTypeCallCache[cacheKey] = true;
  2910. manualPropTypeWarningCount++;
  2911. }
  2912. }
  2913. }
  2914. if (props[propName] == null) {
  2915. if (isRequired) {
  2916. if (props[propName] === null) {
  2917. return new PropTypeError('The ' + location + ' `' + propFullName + '` is marked as required ' + ('in `' + componentName + '`, but its value is `null`.'));
  2918. }
  2919. return new PropTypeError('The ' + location + ' `' + propFullName + '` is marked as required in ' + ('`' + componentName + '`, but its value is `undefined`.'));
  2920. }
  2921. return null;
  2922. } else {
  2923. return validate(props, propName, componentName, location, propFullName);
  2924. }
  2925. }
  2926. var chainedCheckType = checkType.bind(null, false);
  2927. chainedCheckType.isRequired = checkType.bind(null, true);
  2928. return chainedCheckType;
  2929. }
  2930. function createPrimitiveTypeChecker(expectedType) {
  2931. function validate(props, propName, componentName, location, propFullName, secret) {
  2932. var propValue = props[propName];
  2933. var propType = getPropType(propValue);
  2934. if (propType !== expectedType) {
  2935. // `propValue` being instance of, say, date/regexp, pass the 'object'
  2936. // check, but we can offer a more precise error message here rather than
  2937. // 'of type `object`'.
  2938. var preciseType = getPreciseType(propValue);
  2939. return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + preciseType + '` supplied to `' + componentName + '`, expected ') + ('`' + expectedType + '`.'));
  2940. }
  2941. return null;
  2942. }
  2943. return createChainableTypeChecker(validate);
  2944. }
  2945. function createAnyTypeChecker() {
  2946. return createChainableTypeChecker(emptyFunction.thatReturnsNull);
  2947. }
  2948. function createArrayOfTypeChecker(typeChecker) {
  2949. function validate(props, propName, componentName, location, propFullName) {
  2950. if (typeof typeChecker !== 'function') {
  2951. return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside arrayOf.');
  2952. }
  2953. var propValue = props[propName];
  2954. if (!Array.isArray(propValue)) {
  2955. var propType = getPropType(propValue);
  2956. return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an array.'));
  2957. }
  2958. for (var i = 0; i < propValue.length; i++) {
  2959. var error = typeChecker(propValue, i, componentName, location, propFullName + '[' + i + ']', ReactPropTypesSecret);
  2960. if (error instanceof Error) {
  2961. return error;
  2962. }
  2963. }
  2964. return null;
  2965. }
  2966. return createChainableTypeChecker(validate);
  2967. }
  2968. function createElementTypeChecker() {
  2969. function validate(props, propName, componentName, location, propFullName) {
  2970. var propValue = props[propName];
  2971. if (!isValidElement(propValue)) {
  2972. var propType = getPropType(propValue);
  2973. return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected a single ReactElement.'));
  2974. }
  2975. return null;
  2976. }
  2977. return createChainableTypeChecker(validate);
  2978. }
  2979. function createInstanceTypeChecker(expectedClass) {
  2980. function validate(props, propName, componentName, location, propFullName) {
  2981. if (!(props[propName] instanceof expectedClass)) {
  2982. var expectedClassName = expectedClass.name || ANONYMOUS;
  2983. var actualClassName = getClassName(props[propName]);
  2984. return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + actualClassName + '` supplied to `' + componentName + '`, expected ') + ('instance of `' + expectedClassName + '`.'));
  2985. }
  2986. return null;
  2987. }
  2988. return createChainableTypeChecker(validate);
  2989. }
  2990. function createEnumTypeChecker(expectedValues) {
  2991. if (!Array.isArray(expectedValues)) {
  2992. process.env.NODE_ENV !== 'production' ? warning(false, 'Invalid argument supplied to oneOf, expected an instance of array.') : void 0;
  2993. return emptyFunction.thatReturnsNull;
  2994. }
  2995. function validate(props, propName, componentName, location, propFullName) {
  2996. var propValue = props[propName];
  2997. for (var i = 0; i < expectedValues.length; i++) {
  2998. if (is(propValue, expectedValues[i])) {
  2999. return null;
  3000. }
  3001. }
  3002. var valuesString = JSON.stringify(expectedValues);
  3003. return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of value `' + propValue + '` ' + ('supplied to `' + componentName + '`, expected one of ' + valuesString + '.'));
  3004. }
  3005. return createChainableTypeChecker(validate);
  3006. }
  3007. function createObjectOfTypeChecker(typeChecker) {
  3008. function validate(props, propName, componentName, location, propFullName) {
  3009. if (typeof typeChecker !== 'function') {
  3010. return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside objectOf.');
  3011. }
  3012. var propValue = props[propName];
  3013. var propType = getPropType(propValue);
  3014. if (propType !== 'object') {
  3015. return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an object.'));
  3016. }
  3017. for (var key in propValue) {
  3018. if (propValue.hasOwnProperty(key)) {
  3019. var error = typeChecker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret);
  3020. if (error instanceof Error) {
  3021. return error;
  3022. }
  3023. }
  3024. }
  3025. return null;
  3026. }
  3027. return createChainableTypeChecker(validate);
  3028. }
  3029. function createUnionTypeChecker(arrayOfTypeCheckers) {
  3030. if (!Array.isArray(arrayOfTypeCheckers)) {
  3031. process.env.NODE_ENV !== 'production' ? warning(false, 'Invalid argument supplied to oneOfType, expected an instance of array.') : void 0;
  3032. return emptyFunction.thatReturnsNull;
  3033. }
  3034. for (var i = 0; i < arrayOfTypeCheckers.length; i++) {
  3035. var checker = arrayOfTypeCheckers[i];
  3036. if (typeof checker !== 'function') {
  3037. warning(
  3038. false,
  3039. 'Invalid argument supplied to oneOfType. Expected an array of check functions, but ' +
  3040. 'received %s at index %s.',
  3041. getPostfixForTypeWarning(checker),
  3042. i
  3043. );
  3044. return emptyFunction.thatReturnsNull;
  3045. }
  3046. }
  3047. function validate(props, propName, componentName, location, propFullName) {
  3048. for (var i = 0; i < arrayOfTypeCheckers.length; i++) {
  3049. var checker = arrayOfTypeCheckers[i];
  3050. if (checker(props, propName, componentName, location, propFullName, ReactPropTypesSecret) == null) {
  3051. return null;
  3052. }
  3053. }
  3054. return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`.'));
  3055. }
  3056. return createChainableTypeChecker(validate);
  3057. }
  3058. function createNodeChecker() {
  3059. function validate(props, propName, componentName, location, propFullName) {
  3060. if (!isNode(props[propName])) {
  3061. return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`, expected a ReactNode.'));
  3062. }
  3063. return null;
  3064. }
  3065. return createChainableTypeChecker(validate);
  3066. }
  3067. function createShapeTypeChecker(shapeTypes) {
  3068. function validate(props, propName, componentName, location, propFullName) {
  3069. var propValue = props[propName];
  3070. var propType = getPropType(propValue);
  3071. if (propType !== 'object') {
  3072. return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.'));
  3073. }
  3074. for (var key in shapeTypes) {
  3075. var checker = shapeTypes[key];
  3076. if (!checker) {
  3077. continue;
  3078. }
  3079. var error = checker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret);
  3080. if (error) {
  3081. return error;
  3082. }
  3083. }
  3084. return null;
  3085. }
  3086. return createChainableTypeChecker(validate);
  3087. }
  3088. function createStrictShapeTypeChecker(shapeTypes) {
  3089. function validate(props, propName, componentName, location, propFullName) {
  3090. var propValue = props[propName];
  3091. var propType = getPropType(propValue);
  3092. if (propType !== 'object') {
  3093. return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.'));
  3094. }
  3095. // We need to check all keys in case some are required but missing from
  3096. // props.
  3097. var allKeys = assign({}, props[propName], shapeTypes);
  3098. for (var key in allKeys) {
  3099. var checker = shapeTypes[key];
  3100. if (!checker) {
  3101. return new PropTypeError(
  3102. 'Invalid ' + location + ' `' + propFullName + '` key `' + key + '` supplied to `' + componentName + '`.' +
  3103. '\nBad object: ' + JSON.stringify(props[propName], null, ' ') +
  3104. '\nValid keys: ' + JSON.stringify(Object.keys(shapeTypes), null, ' ')
  3105. );
  3106. }
  3107. var error = checker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret);
  3108. if (error) {
  3109. return error;
  3110. }
  3111. }
  3112. return null;
  3113. }
  3114. return createChainableTypeChecker(validate);
  3115. }
  3116. function isNode(propValue) {
  3117. switch (typeof propValue) {
  3118. case 'number':
  3119. case 'string':
  3120. case 'undefined':
  3121. return true;
  3122. case 'boolean':
  3123. return !propValue;
  3124. case 'object':
  3125. if (Array.isArray(propValue)) {
  3126. return propValue.every(isNode);
  3127. }
  3128. if (propValue === null || isValidElement(propValue)) {
  3129. return true;
  3130. }
  3131. var iteratorFn = getIteratorFn(propValue);
  3132. if (iteratorFn) {
  3133. var iterator = iteratorFn.call(propValue);
  3134. var step;
  3135. if (iteratorFn !== propValue.entries) {
  3136. while (!(step = iterator.next()).done) {
  3137. if (!isNode(step.value)) {
  3138. return false;
  3139. }
  3140. }
  3141. } else {
  3142. // Iterator will provide entry [k,v] tuples rather than values.
  3143. while (!(step = iterator.next()).done) {
  3144. var entry = step.value;
  3145. if (entry) {
  3146. if (!isNode(entry[1])) {
  3147. return false;
  3148. }
  3149. }
  3150. }
  3151. }
  3152. } else {
  3153. return false;
  3154. }
  3155. return true;
  3156. default:
  3157. return false;
  3158. }
  3159. }
  3160. function isSymbol(propType, propValue) {
  3161. // Native Symbol.
  3162. if (propType === 'symbol') {
  3163. return true;
  3164. }
  3165. // 19.4.3.5 Symbol.prototype[@@toStringTag] === 'Symbol'
  3166. if (propValue['@@toStringTag'] === 'Symbol') {
  3167. return true;
  3168. }
  3169. // Fallback for non-spec compliant Symbols which are polyfilled.
  3170. if (typeof Symbol === 'function' && propValue instanceof Symbol) {
  3171. return true;
  3172. }
  3173. return false;
  3174. }
  3175. // Equivalent of `typeof` but with special handling for array and regexp.
  3176. function getPropType(propValue) {
  3177. var propType = typeof propValue;
  3178. if (Array.isArray(propValue)) {
  3179. return 'array';
  3180. }
  3181. if (propValue instanceof RegExp) {
  3182. // Old webkits (at least until Android 4.0) return 'function' rather than
  3183. // 'object' for typeof a RegExp. We'll normalize this here so that /bla/
  3184. // passes PropTypes.object.
  3185. return 'object';
  3186. }
  3187. if (isSymbol(propType, propValue)) {
  3188. return 'symbol';
  3189. }
  3190. return propType;
  3191. }
  3192. // This handles more types than `getPropType`. Only used for error messages.
  3193. // See `createPrimitiveTypeChecker`.
  3194. function getPreciseType(propValue) {
  3195. if (typeof propValue === 'undefined' || propValue === null) {
  3196. return '' + propValue;
  3197. }
  3198. var propType = getPropType(propValue);
  3199. if (propType === 'object') {
  3200. if (propValue instanceof Date) {
  3201. return 'date';
  3202. } else if (propValue instanceof RegExp) {
  3203. return 'regexp';
  3204. }
  3205. }
  3206. return propType;
  3207. }
  3208. // Returns a string that is postfixed to a warning about an invalid type.
  3209. // For example, "undefined" or "of type array"
  3210. function getPostfixForTypeWarning(value) {
  3211. var type = getPreciseType(value);
  3212. switch (type) {
  3213. case 'array':
  3214. case 'object':
  3215. return 'an ' + type;
  3216. case 'boolean':
  3217. case 'date':
  3218. case 'regexp':
  3219. return 'a ' + type;
  3220. default:
  3221. return type;
  3222. }
  3223. }
  3224. // Returns class name of the object, if any.
  3225. function getClassName(propValue) {
  3226. if (!propValue.constructor || !propValue.constructor.name) {
  3227. return ANONYMOUS;
  3228. }
  3229. return propValue.constructor.name;
  3230. }
  3231. ReactPropTypes.checkPropTypes = checkPropTypes;
  3232. ReactPropTypes.PropTypes = ReactPropTypes;
  3233. return ReactPropTypes;
  3234. };
  3235. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
  3236. /***/ }),
  3237. /* 31 */
  3238. /***/ (function(module, exports) {
  3239. /**
  3240. * Copyright (c) 2013-present, Facebook, Inc.
  3241. *
  3242. * This source code is licensed under the MIT license found in the
  3243. * LICENSE file in the root directory of this source tree.
  3244. */
  3245. 'use strict';
  3246. var ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED';
  3247. module.exports = ReactPropTypesSecret;
  3248. /***/ }),
  3249. /* 32 */
  3250. /***/ (function(module, exports, __webpack_require__) {
  3251. /* WEBPACK VAR INJECTION */(function(process) {/**
  3252. * Copyright (c) 2013-present, Facebook, Inc.
  3253. *
  3254. * This source code is licensed under the MIT license found in the
  3255. * LICENSE file in the root directory of this source tree.
  3256. */
  3257. 'use strict';
  3258. if (process.env.NODE_ENV !== 'production') {
  3259. var invariant = __webpack_require__(12);
  3260. var warning = __webpack_require__(8);
  3261. var ReactPropTypesSecret = __webpack_require__(31);
  3262. var loggedTypeFailures = {};
  3263. }
  3264. /**
  3265. * Assert that the values match with the type specs.
  3266. * Error messages are memorized and will only be shown once.
  3267. *
  3268. * @param {object} typeSpecs Map of name to a ReactPropType
  3269. * @param {object} values Runtime values that need to be type-checked
  3270. * @param {string} location e.g. "prop", "context", "child context"
  3271. * @param {string} componentName Name of the component for error messages.
  3272. * @param {?Function} getStack Returns the component stack.
  3273. * @private
  3274. */
  3275. function checkPropTypes(typeSpecs, values, location, componentName, getStack) {
  3276. if (process.env.NODE_ENV !== 'production') {
  3277. for (var typeSpecName in typeSpecs) {
  3278. if (typeSpecs.hasOwnProperty(typeSpecName)) {
  3279. var error;
  3280. // Prop type validation may throw. In case they do, we don't want to
  3281. // fail the render phase where it didn't fail before. So we log it.
  3282. // After these have been cleaned up, we'll let them throw.
  3283. try {
  3284. // This is intentionally an invariant that gets caught. It's the same
  3285. // behavior as without this statement except with a better message.
  3286. invariant(typeof typeSpecs[typeSpecName] === 'function', '%s: %s type `%s` is invalid; it must be a function, usually from ' + 'the `prop-types` package, but received `%s`.', componentName || 'React class', location, typeSpecName, typeof typeSpecs[typeSpecName]);
  3287. error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, ReactPropTypesSecret);
  3288. } catch (ex) {
  3289. error = ex;
  3290. }
  3291. warning(!error || error instanceof Error, '%s: type specification of %s `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', location, typeSpecName, typeof error);
  3292. if (error instanceof Error && !(error.message in loggedTypeFailures)) {
  3293. // Only monitor this failure once because there tends to be a lot of the
  3294. // same error.
  3295. loggedTypeFailures[error.message] = true;
  3296. var stack = getStack ? getStack() : '';
  3297. warning(false, 'Failed %s type: %s%s', location, error.message, stack != null ? stack : '');
  3298. }
  3299. }
  3300. }
  3301. }
  3302. }
  3303. module.exports = checkPropTypes;
  3304. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
  3305. /***/ }),
  3306. /* 33 */
  3307. /***/ (function(module, exports) {
  3308. /**
  3309. * Copyright (c) 2013-present, Facebook, Inc.
  3310. *
  3311. * This source code is licensed under the MIT license found in the
  3312. * LICENSE file in the root directory of this source tree.
  3313. *
  3314. */
  3315. 'use strict';
  3316. module.exports = '15.6.2';
  3317. /***/ }),
  3318. /* 34 */
  3319. /***/ (function(module, exports, __webpack_require__) {
  3320. /**
  3321. * Copyright (c) 2013-present, Facebook, Inc.
  3322. *
  3323. * This source code is licensed under the MIT license found in the
  3324. * LICENSE file in the root directory of this source tree.
  3325. *
  3326. */
  3327. 'use strict';
  3328. var _require = __webpack_require__(5),
  3329. Component = _require.Component;
  3330. var _require2 = __webpack_require__(16),
  3331. isValidElement = _require2.isValidElement;
  3332. var ReactNoopUpdateQueue = __webpack_require__(7);
  3333. var factory = __webpack_require__(35);
  3334. module.exports = factory(Component, isValidElement, ReactNoopUpdateQueue);
  3335. /***/ }),
  3336. /* 35 */
  3337. /***/ (function(module, exports, __webpack_require__) {
  3338. /* WEBPACK VAR INJECTION */(function(process) {/**
  3339. * Copyright (c) 2013-present, Facebook, Inc.
  3340. *
  3341. * This source code is licensed under the MIT license found in the
  3342. * LICENSE file in the root directory of this source tree.
  3343. *
  3344. */
  3345. 'use strict';
  3346. var _assign = __webpack_require__(4);
  3347. var emptyObject = __webpack_require__(11);
  3348. var _invariant = __webpack_require__(12);
  3349. if (process.env.NODE_ENV !== 'production') {
  3350. var warning = __webpack_require__(8);
  3351. }
  3352. var MIXINS_KEY = 'mixins';
  3353. // Helper function to allow the creation of anonymous functions which do not
  3354. // have .name set to the name of the variable being assigned to.
  3355. function identity(fn) {
  3356. return fn;
  3357. }
  3358. var ReactPropTypeLocationNames;
  3359. if (process.env.NODE_ENV !== 'production') {
  3360. ReactPropTypeLocationNames = {
  3361. prop: 'prop',
  3362. context: 'context',
  3363. childContext: 'child context'
  3364. };
  3365. } else {
  3366. ReactPropTypeLocationNames = {};
  3367. }
  3368. function factory(ReactComponent, isValidElement, ReactNoopUpdateQueue) {
  3369. /**
  3370. * Policies that describe methods in `ReactClassInterface`.
  3371. */
  3372. var injectedMixins = [];
  3373. /**
  3374. * Composite components are higher-level components that compose other composite
  3375. * or host components.
  3376. *
  3377. * To create a new type of `ReactClass`, pass a specification of
  3378. * your new class to `React.createClass`. The only requirement of your class
  3379. * specification is that you implement a `render` method.
  3380. *
  3381. * var MyComponent = React.createClass({
  3382. * render: function() {
  3383. * return <div>Hello World</div>;
  3384. * }
  3385. * });
  3386. *
  3387. * The class specification supports a specific protocol of methods that have
  3388. * special meaning (e.g. `render`). See `ReactClassInterface` for
  3389. * more the comprehensive protocol. Any other properties and methods in the
  3390. * class specification will be available on the prototype.
  3391. *
  3392. * @interface ReactClassInterface
  3393. * @internal
  3394. */
  3395. var ReactClassInterface = {
  3396. /**
  3397. * An array of Mixin objects to include when defining your component.
  3398. *
  3399. * @type {array}
  3400. * @optional
  3401. */
  3402. mixins: 'DEFINE_MANY',
  3403. /**
  3404. * An object containing properties and methods that should be defined on
  3405. * the component's constructor instead of its prototype (static methods).
  3406. *
  3407. * @type {object}
  3408. * @optional
  3409. */
  3410. statics: 'DEFINE_MANY',
  3411. /**
  3412. * Definition of prop types for this component.
  3413. *
  3414. * @type {object}
  3415. * @optional
  3416. */
  3417. propTypes: 'DEFINE_MANY',
  3418. /**
  3419. * Definition of context types for this component.
  3420. *
  3421. * @type {object}
  3422. * @optional
  3423. */
  3424. contextTypes: 'DEFINE_MANY',
  3425. /**
  3426. * Definition of context types this component sets for its children.
  3427. *
  3428. * @type {object}
  3429. * @optional
  3430. */
  3431. childContextTypes: 'DEFINE_MANY',
  3432. // ==== Definition methods ====
  3433. /**
  3434. * Invoked when the component is mounted. Values in the mapping will be set on
  3435. * `this.props` if that prop is not specified (i.e. using an `in` check).
  3436. *
  3437. * This method is invoked before `getInitialState` and therefore cannot rely
  3438. * on `this.state` or use `this.setState`.
  3439. *
  3440. * @return {object}
  3441. * @optional
  3442. */
  3443. getDefaultProps: 'DEFINE_MANY_MERGED',
  3444. /**
  3445. * Invoked once before the component is mounted. The return value will be used
  3446. * as the initial value of `this.state`.
  3447. *
  3448. * getInitialState: function() {
  3449. * return {
  3450. * isOn: false,
  3451. * fooBaz: new BazFoo()
  3452. * }
  3453. * }
  3454. *
  3455. * @return {object}
  3456. * @optional
  3457. */
  3458. getInitialState: 'DEFINE_MANY_MERGED',
  3459. /**
  3460. * @return {object}
  3461. * @optional
  3462. */
  3463. getChildContext: 'DEFINE_MANY_MERGED',
  3464. /**
  3465. * Uses props from `this.props` and state from `this.state` to render the
  3466. * structure of the component.
  3467. *
  3468. * No guarantees are made about when or how often this method is invoked, so
  3469. * it must not have side effects.
  3470. *
  3471. * render: function() {
  3472. * var name = this.props.name;
  3473. * return <div>Hello, {name}!</div>;
  3474. * }
  3475. *
  3476. * @return {ReactComponent}
  3477. * @required
  3478. */
  3479. render: 'DEFINE_ONCE',
  3480. // ==== Delegate methods ====
  3481. /**
  3482. * Invoked when the component is initially created and about to be mounted.
  3483. * This may have side effects, but any external subscriptions or data created
  3484. * by this method must be cleaned up in `componentWillUnmount`.
  3485. *
  3486. * @optional
  3487. */
  3488. componentWillMount: 'DEFINE_MANY',
  3489. /**
  3490. * Invoked when the component has been mounted and has a DOM representation.
  3491. * However, there is no guarantee that the DOM node is in the document.
  3492. *
  3493. * Use this as an opportunity to operate on the DOM when the component has
  3494. * been mounted (initialized and rendered) for the first time.
  3495. *
  3496. * @param {DOMElement} rootNode DOM element representing the component.
  3497. * @optional
  3498. */
  3499. componentDidMount: 'DEFINE_MANY',
  3500. /**
  3501. * Invoked before the component receives new props.
  3502. *
  3503. * Use this as an opportunity to react to a prop transition by updating the
  3504. * state using `this.setState`. Current props are accessed via `this.props`.
  3505. *
  3506. * componentWillReceiveProps: function(nextProps, nextContext) {
  3507. * this.setState({
  3508. * likesIncreasing: nextProps.likeCount > this.props.likeCount
  3509. * });
  3510. * }
  3511. *
  3512. * NOTE: There is no equivalent `componentWillReceiveState`. An incoming prop
  3513. * transition may cause a state change, but the opposite is not true. If you
  3514. * need it, you are probably looking for `componentWillUpdate`.
  3515. *
  3516. * @param {object} nextProps
  3517. * @optional
  3518. */
  3519. componentWillReceiveProps: 'DEFINE_MANY',
  3520. /**
  3521. * Invoked while deciding if the component should be updated as a result of
  3522. * receiving new props, state and/or context.
  3523. *
  3524. * Use this as an opportunity to `return false` when you're certain that the
  3525. * transition to the new props/state/context will not require a component
  3526. * update.
  3527. *
  3528. * shouldComponentUpdate: function(nextProps, nextState, nextContext) {
  3529. * return !equal(nextProps, this.props) ||
  3530. * !equal(nextState, this.state) ||
  3531. * !equal(nextContext, this.context);
  3532. * }
  3533. *
  3534. * @param {object} nextProps
  3535. * @param {?object} nextState
  3536. * @param {?object} nextContext
  3537. * @return {boolean} True if the component should update.
  3538. * @optional
  3539. */
  3540. shouldComponentUpdate: 'DEFINE_ONCE',
  3541. /**
  3542. * Invoked when the component is about to update due to a transition from
  3543. * `this.props`, `this.state` and `this.context` to `nextProps`, `nextState`
  3544. * and `nextContext`.
  3545. *
  3546. * Use this as an opportunity to perform preparation before an update occurs.
  3547. *
  3548. * NOTE: You **cannot** use `this.setState()` in this method.
  3549. *
  3550. * @param {object} nextProps
  3551. * @param {?object} nextState
  3552. * @param {?object} nextContext
  3553. * @param {ReactReconcileTransaction} transaction
  3554. * @optional
  3555. */
  3556. componentWillUpdate: 'DEFINE_MANY',
  3557. /**
  3558. * Invoked when the component's DOM representation has been updated.
  3559. *
  3560. * Use this as an opportunity to operate on the DOM when the component has
  3561. * been updated.
  3562. *
  3563. * @param {object} prevProps
  3564. * @param {?object} prevState
  3565. * @param {?object} prevContext
  3566. * @param {DOMElement} rootNode DOM element representing the component.
  3567. * @optional
  3568. */
  3569. componentDidUpdate: 'DEFINE_MANY',
  3570. /**
  3571. * Invoked when the component is about to be removed from its parent and have
  3572. * its DOM representation destroyed.
  3573. *
  3574. * Use this as an opportunity to deallocate any external resources.
  3575. *
  3576. * NOTE: There is no `componentDidUnmount` since your component will have been
  3577. * destroyed by that point.
  3578. *
  3579. * @optional
  3580. */
  3581. componentWillUnmount: 'DEFINE_MANY',
  3582. // ==== Advanced methods ====
  3583. /**
  3584. * Updates the component's currently mounted DOM representation.
  3585. *
  3586. * By default, this implements React's rendering and reconciliation algorithm.
  3587. * Sophisticated clients may wish to override this.
  3588. *
  3589. * @param {ReactReconcileTransaction} transaction
  3590. * @internal
  3591. * @overridable
  3592. */
  3593. updateComponent: 'OVERRIDE_BASE'
  3594. };
  3595. /**
  3596. * Mapping from class specification keys to special processing functions.
  3597. *
  3598. * Although these are declared like instance properties in the specification
  3599. * when defining classes using `React.createClass`, they are actually static
  3600. * and are accessible on the constructor instead of the prototype. Despite
  3601. * being static, they must be defined outside of the "statics" key under
  3602. * which all other static methods are defined.
  3603. */
  3604. var RESERVED_SPEC_KEYS = {
  3605. displayName: function(Constructor, displayName) {
  3606. Constructor.displayName = displayName;
  3607. },
  3608. mixins: function(Constructor, mixins) {
  3609. if (mixins) {
  3610. for (var i = 0; i < mixins.length; i++) {
  3611. mixSpecIntoComponent(Constructor, mixins[i]);
  3612. }
  3613. }
  3614. },
  3615. childContextTypes: function(Constructor, childContextTypes) {
  3616. if (process.env.NODE_ENV !== 'production') {
  3617. validateTypeDef(Constructor, childContextTypes, 'childContext');
  3618. }
  3619. Constructor.childContextTypes = _assign(
  3620. {},
  3621. Constructor.childContextTypes,
  3622. childContextTypes
  3623. );
  3624. },
  3625. contextTypes: function(Constructor, contextTypes) {
  3626. if (process.env.NODE_ENV !== 'production') {
  3627. validateTypeDef(Constructor, contextTypes, 'context');
  3628. }
  3629. Constructor.contextTypes = _assign(
  3630. {},
  3631. Constructor.contextTypes,
  3632. contextTypes
  3633. );
  3634. },
  3635. /**
  3636. * Special case getDefaultProps which should move into statics but requires
  3637. * automatic merging.
  3638. */
  3639. getDefaultProps: function(Constructor, getDefaultProps) {
  3640. if (Constructor.getDefaultProps) {
  3641. Constructor.getDefaultProps = createMergedResultFunction(
  3642. Constructor.getDefaultProps,
  3643. getDefaultProps
  3644. );
  3645. } else {
  3646. Constructor.getDefaultProps = getDefaultProps;
  3647. }
  3648. },
  3649. propTypes: function(Constructor, propTypes) {
  3650. if (process.env.NODE_ENV !== 'production') {
  3651. validateTypeDef(Constructor, propTypes, 'prop');
  3652. }
  3653. Constructor.propTypes = _assign({}, Constructor.propTypes, propTypes);
  3654. },
  3655. statics: function(Constructor, statics) {
  3656. mixStaticSpecIntoComponent(Constructor, statics);
  3657. },
  3658. autobind: function() {}
  3659. };
  3660. function validateTypeDef(Constructor, typeDef, location) {
  3661. for (var propName in typeDef) {
  3662. if (typeDef.hasOwnProperty(propName)) {
  3663. // use a warning instead of an _invariant so components
  3664. // don't show up in prod but only in __DEV__
  3665. if (process.env.NODE_ENV !== 'production') {
  3666. warning(
  3667. typeof typeDef[propName] === 'function',
  3668. '%s: %s type `%s` is invalid; it must be a function, usually from ' +
  3669. 'React.PropTypes.',
  3670. Constructor.displayName || 'ReactClass',
  3671. ReactPropTypeLocationNames[location],
  3672. propName
  3673. );
  3674. }
  3675. }
  3676. }
  3677. }
  3678. function validateMethodOverride(isAlreadyDefined, name) {
  3679. var specPolicy = ReactClassInterface.hasOwnProperty(name)
  3680. ? ReactClassInterface[name]
  3681. : null;
  3682. // Disallow overriding of base class methods unless explicitly allowed.
  3683. if (ReactClassMixin.hasOwnProperty(name)) {
  3684. _invariant(
  3685. specPolicy === 'OVERRIDE_BASE',
  3686. 'ReactClassInterface: You are attempting to override ' +
  3687. '`%s` from your class specification. Ensure that your method names ' +
  3688. 'do not overlap with React methods.',
  3689. name
  3690. );
  3691. }
  3692. // Disallow defining methods more than once unless explicitly allowed.
  3693. if (isAlreadyDefined) {
  3694. _invariant(
  3695. specPolicy === 'DEFINE_MANY' || specPolicy === 'DEFINE_MANY_MERGED',
  3696. 'ReactClassInterface: You are attempting to define ' +
  3697. '`%s` on your component more than once. This conflict may be due ' +
  3698. 'to a mixin.',
  3699. name
  3700. );
  3701. }
  3702. }
  3703. /**
  3704. * Mixin helper which handles policy validation and reserved
  3705. * specification keys when building React classes.
  3706. */
  3707. function mixSpecIntoComponent(Constructor, spec) {
  3708. if (!spec) {
  3709. if (process.env.NODE_ENV !== 'production') {
  3710. var typeofSpec = typeof spec;
  3711. var isMixinValid = typeofSpec === 'object' && spec !== null;
  3712. if (process.env.NODE_ENV !== 'production') {
  3713. warning(
  3714. isMixinValid,
  3715. "%s: You're attempting to include a mixin that is either null " +
  3716. 'or not an object. Check the mixins included by the component, ' +
  3717. 'as well as any mixins they include themselves. ' +
  3718. 'Expected object but got %s.',
  3719. Constructor.displayName || 'ReactClass',
  3720. spec === null ? null : typeofSpec
  3721. );
  3722. }
  3723. }
  3724. return;
  3725. }
  3726. _invariant(
  3727. typeof spec !== 'function',
  3728. "ReactClass: You're attempting to " +
  3729. 'use a component class or function as a mixin. Instead, just use a ' +
  3730. 'regular object.'
  3731. );
  3732. _invariant(
  3733. !isValidElement(spec),
  3734. "ReactClass: You're attempting to " +
  3735. 'use a component as a mixin. Instead, just use a regular object.'
  3736. );
  3737. var proto = Constructor.prototype;
  3738. var autoBindPairs = proto.__reactAutoBindPairs;
  3739. // By handling mixins before any other properties, we ensure the same
  3740. // chaining order is applied to methods with DEFINE_MANY policy, whether
  3741. // mixins are listed before or after these methods in the spec.
  3742. if (spec.hasOwnProperty(MIXINS_KEY)) {
  3743. RESERVED_SPEC_KEYS.mixins(Constructor, spec.mixins);
  3744. }
  3745. for (var name in spec) {
  3746. if (!spec.hasOwnProperty(name)) {
  3747. continue;
  3748. }
  3749. if (name === MIXINS_KEY) {
  3750. // We have already handled mixins in a special case above.
  3751. continue;
  3752. }
  3753. var property = spec[name];
  3754. var isAlreadyDefined = proto.hasOwnProperty(name);
  3755. validateMethodOverride(isAlreadyDefined, name);
  3756. if (RESERVED_SPEC_KEYS.hasOwnProperty(name)) {
  3757. RESERVED_SPEC_KEYS[name](Constructor, property);
  3758. } else {
  3759. // Setup methods on prototype:
  3760. // The following member methods should not be automatically bound:
  3761. // 1. Expected ReactClass methods (in the "interface").
  3762. // 2. Overridden methods (that were mixed in).
  3763. var isReactClassMethod = ReactClassInterface.hasOwnProperty(name);
  3764. var isFunction = typeof property === 'function';
  3765. var shouldAutoBind =
  3766. isFunction &&
  3767. !isReactClassMethod &&
  3768. !isAlreadyDefined &&
  3769. spec.autobind !== false;
  3770. if (shouldAutoBind) {
  3771. autoBindPairs.push(name, property);
  3772. proto[name] = property;
  3773. } else {
  3774. if (isAlreadyDefined) {
  3775. var specPolicy = ReactClassInterface[name];
  3776. // These cases should already be caught by validateMethodOverride.
  3777. _invariant(
  3778. isReactClassMethod &&
  3779. (specPolicy === 'DEFINE_MANY_MERGED' ||
  3780. specPolicy === 'DEFINE_MANY'),
  3781. 'ReactClass: Unexpected spec policy %s for key %s ' +
  3782. 'when mixing in component specs.',
  3783. specPolicy,
  3784. name
  3785. );
  3786. // For methods which are defined more than once, call the existing
  3787. // methods before calling the new property, merging if appropriate.
  3788. if (specPolicy === 'DEFINE_MANY_MERGED') {
  3789. proto[name] = createMergedResultFunction(proto[name], property);
  3790. } else if (specPolicy === 'DEFINE_MANY') {
  3791. proto[name] = createChainedFunction(proto[name], property);
  3792. }
  3793. } else {
  3794. proto[name] = property;
  3795. if (process.env.NODE_ENV !== 'production') {
  3796. // Add verbose displayName to the function, which helps when looking
  3797. // at profiling tools.
  3798. if (typeof property === 'function' && spec.displayName) {
  3799. proto[name].displayName = spec.displayName + '_' + name;
  3800. }
  3801. }
  3802. }
  3803. }
  3804. }
  3805. }
  3806. }
  3807. function mixStaticSpecIntoComponent(Constructor, statics) {
  3808. if (!statics) {
  3809. return;
  3810. }
  3811. for (var name in statics) {
  3812. var property = statics[name];
  3813. if (!statics.hasOwnProperty(name)) {
  3814. continue;
  3815. }
  3816. var isReserved = name in RESERVED_SPEC_KEYS;
  3817. _invariant(
  3818. !isReserved,
  3819. 'ReactClass: You are attempting to define a reserved ' +
  3820. 'property, `%s`, that shouldn\'t be on the "statics" key. Define it ' +
  3821. 'as an instance property instead; it will still be accessible on the ' +
  3822. 'constructor.',
  3823. name
  3824. );
  3825. var isInherited = name in Constructor;
  3826. _invariant(
  3827. !isInherited,
  3828. 'ReactClass: You are attempting to define ' +
  3829. '`%s` on your component more than once. This conflict may be ' +
  3830. 'due to a mixin.',
  3831. name
  3832. );
  3833. Constructor[name] = property;
  3834. }
  3835. }
  3836. /**
  3837. * Merge two objects, but throw if both contain the same key.
  3838. *
  3839. * @param {object} one The first object, which is mutated.
  3840. * @param {object} two The second object
  3841. * @return {object} one after it has been mutated to contain everything in two.
  3842. */
  3843. function mergeIntoWithNoDuplicateKeys(one, two) {
  3844. _invariant(
  3845. one && two && typeof one === 'object' && typeof two === 'object',
  3846. 'mergeIntoWithNoDuplicateKeys(): Cannot merge non-objects.'
  3847. );
  3848. for (var key in two) {
  3849. if (two.hasOwnProperty(key)) {
  3850. _invariant(
  3851. one[key] === undefined,
  3852. 'mergeIntoWithNoDuplicateKeys(): ' +
  3853. 'Tried to merge two objects with the same key: `%s`. This conflict ' +
  3854. 'may be due to a mixin; in particular, this may be caused by two ' +
  3855. 'getInitialState() or getDefaultProps() methods returning objects ' +
  3856. 'with clashing keys.',
  3857. key
  3858. );
  3859. one[key] = two[key];
  3860. }
  3861. }
  3862. return one;
  3863. }
  3864. /**
  3865. * Creates a function that invokes two functions and merges their return values.
  3866. *
  3867. * @param {function} one Function to invoke first.
  3868. * @param {function} two Function to invoke second.
  3869. * @return {function} Function that invokes the two argument functions.
  3870. * @private
  3871. */
  3872. function createMergedResultFunction(one, two) {
  3873. return function mergedResult() {
  3874. var a = one.apply(this, arguments);
  3875. var b = two.apply(this, arguments);
  3876. if (a == null) {
  3877. return b;
  3878. } else if (b == null) {
  3879. return a;
  3880. }
  3881. var c = {};
  3882. mergeIntoWithNoDuplicateKeys(c, a);
  3883. mergeIntoWithNoDuplicateKeys(c, b);
  3884. return c;
  3885. };
  3886. }
  3887. /**
  3888. * Creates a function that invokes two functions and ignores their return vales.
  3889. *
  3890. * @param {function} one Function to invoke first.
  3891. * @param {function} two Function to invoke second.
  3892. * @return {function} Function that invokes the two argument functions.
  3893. * @private
  3894. */
  3895. function createChainedFunction(one, two) {
  3896. return function chainedFunction() {
  3897. one.apply(this, arguments);
  3898. two.apply(this, arguments);
  3899. };
  3900. }
  3901. /**
  3902. * Binds a method to the component.
  3903. *
  3904. * @param {object} component Component whose method is going to be bound.
  3905. * @param {function} method Method to be bound.
  3906. * @return {function} The bound method.
  3907. */
  3908. function bindAutoBindMethod(component, method) {
  3909. var boundMethod = method.bind(component);
  3910. if (process.env.NODE_ENV !== 'production') {
  3911. boundMethod.__reactBoundContext = component;
  3912. boundMethod.__reactBoundMethod = method;
  3913. boundMethod.__reactBoundArguments = null;
  3914. var componentName = component.constructor.displayName;
  3915. var _bind = boundMethod.bind;
  3916. boundMethod.bind = function(newThis) {
  3917. for (
  3918. var _len = arguments.length,
  3919. args = Array(_len > 1 ? _len - 1 : 0),
  3920. _key = 1;
  3921. _key < _len;
  3922. _key++
  3923. ) {
  3924. args[_key - 1] = arguments[_key];
  3925. }
  3926. // User is trying to bind() an autobound method; we effectively will
  3927. // ignore the value of "this" that the user is trying to use, so
  3928. // let's warn.
  3929. if (newThis !== component && newThis !== null) {
  3930. if (process.env.NODE_ENV !== 'production') {
  3931. warning(
  3932. false,
  3933. 'bind(): React component methods may only be bound to the ' +
  3934. 'component instance. See %s',
  3935. componentName
  3936. );
  3937. }
  3938. } else if (!args.length) {
  3939. if (process.env.NODE_ENV !== 'production') {
  3940. warning(
  3941. false,
  3942. 'bind(): You are binding a component method to the component. ' +
  3943. 'React does this for you automatically in a high-performance ' +
  3944. 'way, so you can safely remove this call. See %s',
  3945. componentName
  3946. );
  3947. }
  3948. return boundMethod;
  3949. }
  3950. var reboundMethod = _bind.apply(boundMethod, arguments);
  3951. reboundMethod.__reactBoundContext = component;
  3952. reboundMethod.__reactBoundMethod = method;
  3953. reboundMethod.__reactBoundArguments = args;
  3954. return reboundMethod;
  3955. };
  3956. }
  3957. return boundMethod;
  3958. }
  3959. /**
  3960. * Binds all auto-bound methods in a component.
  3961. *
  3962. * @param {object} component Component whose method is going to be bound.
  3963. */
  3964. function bindAutoBindMethods(component) {
  3965. var pairs = component.__reactAutoBindPairs;
  3966. for (var i = 0; i < pairs.length; i += 2) {
  3967. var autoBindKey = pairs[i];
  3968. var method = pairs[i + 1];
  3969. component[autoBindKey] = bindAutoBindMethod(component, method);
  3970. }
  3971. }
  3972. var IsMountedPreMixin = {
  3973. componentDidMount: function() {
  3974. this.__isMounted = true;
  3975. }
  3976. };
  3977. var IsMountedPostMixin = {
  3978. componentWillUnmount: function() {
  3979. this.__isMounted = false;
  3980. }
  3981. };
  3982. /**
  3983. * Add more to the ReactClass base class. These are all legacy features and
  3984. * therefore not already part of the modern ReactComponent.
  3985. */
  3986. var ReactClassMixin = {
  3987. /**
  3988. * TODO: This will be deprecated because state should always keep a consistent
  3989. * type signature and the only use case for this, is to avoid that.
  3990. */
  3991. replaceState: function(newState, callback) {
  3992. this.updater.enqueueReplaceState(this, newState, callback);
  3993. },
  3994. /**
  3995. * Checks whether or not this composite component is mounted.
  3996. * @return {boolean} True if mounted, false otherwise.
  3997. * @protected
  3998. * @final
  3999. */
  4000. isMounted: function() {
  4001. if (process.env.NODE_ENV !== 'production') {
  4002. warning(
  4003. this.__didWarnIsMounted,
  4004. '%s: isMounted is deprecated. Instead, make sure to clean up ' +
  4005. 'subscriptions and pending requests in componentWillUnmount to ' +
  4006. 'prevent memory leaks.',
  4007. (this.constructor && this.constructor.displayName) ||
  4008. this.name ||
  4009. 'Component'
  4010. );
  4011. this.__didWarnIsMounted = true;
  4012. }
  4013. return !!this.__isMounted;
  4014. }
  4015. };
  4016. var ReactClassComponent = function() {};
  4017. _assign(
  4018. ReactClassComponent.prototype,
  4019. ReactComponent.prototype,
  4020. ReactClassMixin
  4021. );
  4022. /**
  4023. * Creates a composite component class given a class specification.
  4024. * See https://facebook.github.io/react/docs/top-level-api.html#react.createclass
  4025. *
  4026. * @param {object} spec Class specification (which must define `render`).
  4027. * @return {function} Component constructor function.
  4028. * @public
  4029. */
  4030. function createClass(spec) {
  4031. // To keep our warnings more understandable, we'll use a little hack here to
  4032. // ensure that Constructor.name !== 'Constructor'. This makes sure we don't
  4033. // unnecessarily identify a class without displayName as 'Constructor'.
  4034. var Constructor = identity(function(props, context, updater) {
  4035. // This constructor gets overridden by mocks. The argument is used
  4036. // by mocks to assert on what gets mounted.
  4037. if (process.env.NODE_ENV !== 'production') {
  4038. warning(
  4039. this instanceof Constructor,
  4040. 'Something is calling a React component directly. Use a factory or ' +
  4041. 'JSX instead. See: https://fb.me/react-legacyfactory'
  4042. );
  4043. }
  4044. // Wire up auto-binding
  4045. if (this.__reactAutoBindPairs.length) {
  4046. bindAutoBindMethods(this);
  4047. }
  4048. this.props = props;
  4049. this.context = context;
  4050. this.refs = emptyObject;
  4051. this.updater = updater || ReactNoopUpdateQueue;
  4052. this.state = null;
  4053. // ReactClasses doesn't have constructors. Instead, they use the
  4054. // getInitialState and componentWillMount methods for initialization.
  4055. var initialState = this.getInitialState ? this.getInitialState() : null;
  4056. if (process.env.NODE_ENV !== 'production') {
  4057. // We allow auto-mocks to proceed as if they're returning null.
  4058. if (
  4059. initialState === undefined &&
  4060. this.getInitialState._isMockFunction
  4061. ) {
  4062. // This is probably bad practice. Consider warning here and
  4063. // deprecating this convenience.
  4064. initialState = null;
  4065. }
  4066. }
  4067. _invariant(
  4068. typeof initialState === 'object' && !Array.isArray(initialState),
  4069. '%s.getInitialState(): must return an object or null',
  4070. Constructor.displayName || 'ReactCompositeComponent'
  4071. );
  4072. this.state = initialState;
  4073. });
  4074. Constructor.prototype = new ReactClassComponent();
  4075. Constructor.prototype.constructor = Constructor;
  4076. Constructor.prototype.__reactAutoBindPairs = [];
  4077. injectedMixins.forEach(mixSpecIntoComponent.bind(null, Constructor));
  4078. mixSpecIntoComponent(Constructor, IsMountedPreMixin);
  4079. mixSpecIntoComponent(Constructor, spec);
  4080. mixSpecIntoComponent(Constructor, IsMountedPostMixin);
  4081. // Initialize the defaultProps property after all mixins have been merged.
  4082. if (Constructor.getDefaultProps) {
  4083. Constructor.defaultProps = Constructor.getDefaultProps();
  4084. }
  4085. if (process.env.NODE_ENV !== 'production') {
  4086. // This is a tag to indicate that the use of these method names is ok,
  4087. // since it's used with createClass. If it's not, then it's likely a
  4088. // mistake so we'll warn you to use the static property, property
  4089. // initializer or constructor respectively.
  4090. if (Constructor.getDefaultProps) {
  4091. Constructor.getDefaultProps.isReactClassApproved = {};
  4092. }
  4093. if (Constructor.prototype.getInitialState) {
  4094. Constructor.prototype.getInitialState.isReactClassApproved = {};
  4095. }
  4096. }
  4097. _invariant(
  4098. Constructor.prototype.render,
  4099. 'createClass(...): Class specification must implement a `render` method.'
  4100. );
  4101. if (process.env.NODE_ENV !== 'production') {
  4102. warning(
  4103. !Constructor.prototype.componentShouldUpdate,
  4104. '%s has a method called ' +
  4105. 'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' +
  4106. 'The name is phrased as a question because the function is ' +
  4107. 'expected to return a value.',
  4108. spec.displayName || 'A component'
  4109. );
  4110. warning(
  4111. !Constructor.prototype.componentWillRecieveProps,
  4112. '%s has a method called ' +
  4113. 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?',
  4114. spec.displayName || 'A component'
  4115. );
  4116. }
  4117. // Reduce time spent doing lookups by setting these on the prototype.
  4118. for (var methodName in ReactClassInterface) {
  4119. if (!Constructor.prototype[methodName]) {
  4120. Constructor.prototype[methodName] = null;
  4121. }
  4122. }
  4123. return Constructor;
  4124. }
  4125. return createClass;
  4126. }
  4127. module.exports = factory;
  4128. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
  4129. /***/ }),
  4130. /* 36 */
  4131. /***/ (function(module, exports, __webpack_require__) {
  4132. /* WEBPACK VAR INJECTION */(function(process) {/**
  4133. * Copyright (c) 2013-present, Facebook, Inc.
  4134. *
  4135. * This source code is licensed under the MIT license found in the
  4136. * LICENSE file in the root directory of this source tree.
  4137. *
  4138. */
  4139. 'use strict';
  4140. var _prodInvariant = __webpack_require__(6);
  4141. var ReactElement = __webpack_require__(16);
  4142. var invariant = __webpack_require__(12);
  4143. /**
  4144. * Returns the first child in a collection of children and verifies that there
  4145. * is only one child in the collection.
  4146. *
  4147. * See https://facebook.github.io/react/docs/top-level-api.html#react.children.only
  4148. *
  4149. * The current implementation of this function assumes that a single child gets
  4150. * passed without a wrapper, but the purpose of this helper function is to
  4151. * abstract away the particular structure of children.
  4152. *
  4153. * @param {?object} children Child collection structure.
  4154. * @return {ReactElement} The first and only `ReactElement` contained in the
  4155. * structure.
  4156. */
  4157. function onlyChild(children) {
  4158. !ReactElement.isValidElement(children) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'React.Children.only expected to receive a single React element child.') : _prodInvariant('143') : void 0;
  4159. return children;
  4160. }
  4161. module.exports = onlyChild;
  4162. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
  4163. /***/ }),
  4164. /* 37 */
  4165. /***/ (function(module, exports) {
  4166. "use strict";
  4167. var _id = 0;
  4168. module.exports = function generateId() {
  4169. return "simplepostmd-editor-" + ++_id;
  4170. };
  4171. /***/ }),
  4172. /* 38 */
  4173. /***/ (function(module, exports) {
  4174. "use strict";
  4175. module.exports = function () {};
  4176. /***/ }),
  4177. /* 39 */
  4178. /***/ (function(module, exports, __webpack_require__) {
  4179. /*global require,module*/
  4180. "use strict";
  4181. var CodeMirror = __webpack_require__(40);
  4182. __webpack_require__(41);
  4183. __webpack_require__(42);
  4184. __webpack_require__(43);
  4185. __webpack_require__(44);
  4186. __webpack_require__(47);
  4187. __webpack_require__(48);
  4188. __webpack_require__(49);
  4189. __webpack_require__(50);
  4190. __webpack_require__(45);
  4191. var CodeMirrorSpellChecker = __webpack_require__(51);
  4192. var marked = __webpack_require__(58);
  4193. // Some variables
  4194. var isMac = /Mac/.test(navigator.platform);
  4195. // Mapping of actions that can be bound to keyboard shortcuts or toolbar buttons
  4196. var bindings = {
  4197. "toggleBold": toggleBold,
  4198. "toggleItalic": toggleItalic,
  4199. "drawLink": drawLink,
  4200. "toggleHeadingSmaller": toggleHeadingSmaller,
  4201. "toggleHeadingBigger": toggleHeadingBigger,
  4202. "drawImage": drawImage,
  4203. "toggleBlockquote": toggleBlockquote,
  4204. "toggleOrderedList": toggleOrderedList,
  4205. "toggleUnorderedList": toggleUnorderedList,
  4206. "toggleCodeBlock": toggleCodeBlock,
  4207. "togglePreview": togglePreview,
  4208. "toggleStrikethrough": toggleStrikethrough,
  4209. "toggleHeading1": toggleHeading1,
  4210. "toggleHeading2": toggleHeading2,
  4211. "toggleHeading3": toggleHeading3,
  4212. "cleanBlock": cleanBlock,
  4213. "drawTable": drawTable,
  4214. "drawHorizontalRule": drawHorizontalRule,
  4215. "undo": undo,
  4216. "redo": redo,
  4217. "toggleSideBySide": toggleSideBySide,
  4218. "toggleFullScreen": toggleFullScreen
  4219. };
  4220. var shortcuts = {
  4221. "toggleBold": "Cmd-B",
  4222. "toggleItalic": "Cmd-I",
  4223. "drawLink": "Cmd-K",
  4224. "toggleHeadingSmaller": "Cmd-H",
  4225. "toggleHeadingBigger": "Shift-Cmd-H",
  4226. "cleanBlock": "Cmd-E",
  4227. "drawImage": "Cmd-Alt-I",
  4228. "toggleBlockquote": "Cmd-'",
  4229. "toggleOrderedList": "Cmd-Alt-L",
  4230. "toggleUnorderedList": "Cmd-L",
  4231. "toggleCodeBlock": "Cmd-Alt-C",
  4232. "togglePreview": "Cmd-P",
  4233. "toggleSideBySide": "F9",
  4234. "toggleFullScreen": "F11"
  4235. };
  4236. var getBindingName = function(f) {
  4237. for(var key in bindings) {
  4238. if(bindings[key] === f) {
  4239. return key;
  4240. }
  4241. }
  4242. return null;
  4243. };
  4244. var isMobile = function() {
  4245. var check = false;
  4246. (function(a) {
  4247. 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;
  4248. })(navigator.userAgent || navigator.vendor || window.opera);
  4249. return check;
  4250. };
  4251. /**
  4252. * Fix shortcut. Mac use Command, others use Ctrl.
  4253. */
  4254. function fixShortcut(name) {
  4255. if(isMac) {
  4256. name = name.replace("Ctrl", "Cmd");
  4257. } else {
  4258. name = name.replace("Cmd", "Ctrl");
  4259. }
  4260. return name;
  4261. }
  4262. /**
  4263. * Create icon element for toolbar.
  4264. */
  4265. function createIcon(options, enableTooltips, shortcuts) {
  4266. options = options || {};
  4267. var el = document.createElement("a");
  4268. enableTooltips = (enableTooltips == undefined) ? true : enableTooltips;
  4269. if(options.title && enableTooltips) {
  4270. el.title = createTootlip(options.title, options.action, shortcuts);
  4271. if(isMac) {
  4272. el.title = el.title.replace("Ctrl", "⌘");
  4273. el.title = el.title.replace("Alt", "⌥");
  4274. }
  4275. }
  4276. el.tabIndex = -1;
  4277. el.className = options.className;
  4278. return el;
  4279. }
  4280. function createSep() {
  4281. var el = document.createElement("i");
  4282. el.className = "separator";
  4283. el.innerHTML = "|";
  4284. return el;
  4285. }
  4286. function createTootlip(title, action, shortcuts) {
  4287. var actionName;
  4288. var tooltip = title;
  4289. if(action) {
  4290. actionName = getBindingName(action);
  4291. if(shortcuts[actionName]) {
  4292. tooltip += " (" + fixShortcut(shortcuts[actionName]) + ")";
  4293. }
  4294. }
  4295. return tooltip;
  4296. }
  4297. /**
  4298. * The state of CodeMirror at the given position.
  4299. */
  4300. function getState(cm, pos) {
  4301. pos = pos || cm.getCursor("start");
  4302. var stat = cm.getTokenAt(pos);
  4303. if(!stat.type) return {};
  4304. var types = stat.type.split(" ");
  4305. var ret = {},
  4306. data, text;
  4307. for(var i = 0; i < types.length; i++) {
  4308. data = types[i];
  4309. if(data === "strong") {
  4310. ret.bold = true;
  4311. } else if(data === "variable-2") {
  4312. text = cm.getLine(pos.line);
  4313. if(/^\s*\d+\.\s/.test(text)) {
  4314. ret["ordered-list"] = true;
  4315. } else {
  4316. ret["unordered-list"] = true;
  4317. }
  4318. } else if(data === "atom") {
  4319. ret.quote = true;
  4320. } else if(data === "em") {
  4321. ret.italic = true;
  4322. } else if(data === "quote") {
  4323. ret.quote = true;
  4324. } else if(data === "strikethrough") {
  4325. ret.strikethrough = true;
  4326. } else if(data === "comment") {
  4327. ret.code = true;
  4328. } else if(data === "link") {
  4329. ret.link = true;
  4330. } else if(data === "tag") {
  4331. ret.image = true;
  4332. } else if(data.match(/^header(\-[1-6])?$/)) {
  4333. ret[data.replace("header", "heading")] = true;
  4334. }
  4335. }
  4336. return ret;
  4337. }
  4338. // Saved overflow setting
  4339. var saved_overflow = "";
  4340. /**
  4341. * Toggle full screen of the editor.
  4342. */
  4343. function toggleFullScreen(editor) {
  4344. // Set fullscreen
  4345. var cm = editor.codemirror;
  4346. cm.setOption("fullScreen", !cm.getOption("fullScreen"));
  4347. // Prevent scrolling on body during fullscreen active
  4348. if(cm.getOption("fullScreen")) {
  4349. saved_overflow = document.body.style.overflow;
  4350. document.body.style.overflow = "hidden";
  4351. } else {
  4352. document.body.style.overflow = saved_overflow;
  4353. }
  4354. // Update toolbar class
  4355. var wrap = cm.getWrapperElement();
  4356. if(!/fullscreen/.test(wrap.previousSibling.className)) {
  4357. wrap.previousSibling.className += " fullscreen";
  4358. } else {
  4359. wrap.previousSibling.className = wrap.previousSibling.className.replace(/\s*fullscreen\b/, "");
  4360. }
  4361. // Update toolbar button
  4362. var toolbarButton = editor.toolbarElements.fullscreen;
  4363. if(!/active/.test(toolbarButton.className)) {
  4364. toolbarButton.className += " active";
  4365. } else {
  4366. toolbarButton.className = toolbarButton.className.replace(/\s*active\s*/g, "");
  4367. }
  4368. // Hide side by side if needed
  4369. var sidebyside = cm.getWrapperElement().nextSibling;
  4370. if(/editor-preview-active-side/.test(sidebyside.className))
  4371. toggleSideBySide(editor);
  4372. }
  4373. /**
  4374. * Action for toggling bold.
  4375. */
  4376. function toggleBold(editor) {
  4377. _toggleBlock(editor, "bold", editor.options.blockStyles.bold);
  4378. }
  4379. /**
  4380. * Action for toggling italic.
  4381. */
  4382. function toggleItalic(editor) {
  4383. _toggleBlock(editor, "italic", editor.options.blockStyles.italic);
  4384. }
  4385. /**
  4386. * Action for toggling strikethrough.
  4387. */
  4388. function toggleStrikethrough(editor) {
  4389. _toggleBlock(editor, "strikethrough", "~~");
  4390. }
  4391. /**
  4392. * Action for toggling code block.
  4393. */
  4394. function toggleCodeBlock(editor) {
  4395. var fenceCharsToInsert = editor.options.blockStyles.code;
  4396. function fencing_line(line) {
  4397. /* return true, if this is a ``` or ~~~ line */
  4398. if(typeof line !== "object") {
  4399. throw "fencing_line() takes a 'line' object (not a line number, or line text). Got: " + typeof line + ": " + line;
  4400. }
  4401. return line.styles && line.styles[2] && line.styles[2].indexOf("formatting-code-block") !== -1;
  4402. }
  4403. function token_state(token) {
  4404. // base goes an extra level deep when mode backdrops are used, e.g. spellchecker on
  4405. return token.state.base.base || token.state.base;
  4406. }
  4407. function code_type(cm, line_num, line, firstTok, lastTok) {
  4408. /*
  4409. * Return "single", "indented", "fenced" or false
  4410. *
  4411. * cm and line_num are required. Others are optional for efficiency
  4412. * To check in the middle of a line, pass in firstTok yourself.
  4413. */
  4414. line = line || cm.getLineHandle(line_num);
  4415. firstTok = firstTok || cm.getTokenAt({
  4416. line: line_num,
  4417. ch: 1
  4418. });
  4419. lastTok = lastTok || (!!line.text && cm.getTokenAt({
  4420. line: line_num,
  4421. ch: line.text.length - 1
  4422. }));
  4423. var types = firstTok.type ? firstTok.type.split(" ") : [];
  4424. if(lastTok && token_state(lastTok).indentedCode) {
  4425. // have to check last char, since first chars of first line aren"t marked as indented
  4426. return "indented";
  4427. } else if(types.indexOf("comment") === -1) {
  4428. // has to be after "indented" check, since first chars of first indented line aren"t marked as such
  4429. return false;
  4430. } else if(token_state(firstTok).fencedChars || token_state(lastTok).fencedChars || fencing_line(line)) {
  4431. return "fenced";
  4432. } else {
  4433. return "single";
  4434. }
  4435. }
  4436. function insertFencingAtSelection(cm, cur_start, cur_end, fenceCharsToInsert) {
  4437. var start_line_sel = cur_start.line + 1,
  4438. end_line_sel = cur_end.line + 1,
  4439. sel_multi = cur_start.line !== cur_end.line,
  4440. repl_start = fenceCharsToInsert + "\n",
  4441. repl_end = "\n" + fenceCharsToInsert;
  4442. if(sel_multi) {
  4443. end_line_sel++;
  4444. }
  4445. // handle last char including \n or not
  4446. if(sel_multi && cur_end.ch === 0) {
  4447. repl_end = fenceCharsToInsert + "\n";
  4448. end_line_sel--;
  4449. }
  4450. _replaceSelection(cm, false, [repl_start, repl_end]);
  4451. cm.setSelection({
  4452. line: start_line_sel,
  4453. ch: 0
  4454. }, {
  4455. line: end_line_sel,
  4456. ch: 0
  4457. });
  4458. }
  4459. var cm = editor.codemirror,
  4460. cur_start = cm.getCursor("start"),
  4461. cur_end = cm.getCursor("end"),
  4462. tok = cm.getTokenAt({
  4463. line: cur_start.line,
  4464. ch: cur_start.ch || 1
  4465. }), // avoid ch 0 which is a cursor pos but not token
  4466. line = cm.getLineHandle(cur_start.line),
  4467. is_code = code_type(cm, cur_start.line, line, tok);
  4468. var block_start, block_end, lineCount;
  4469. if(is_code === "single") {
  4470. // similar to some SimpleMDE _toggleBlock logic
  4471. var start = line.text.slice(0, cur_start.ch).replace("`", ""),
  4472. end = line.text.slice(cur_start.ch).replace("`", "");
  4473. cm.replaceRange(start + end, {
  4474. line: cur_start.line,
  4475. ch: 0
  4476. }, {
  4477. line: cur_start.line,
  4478. ch: 99999999999999
  4479. });
  4480. cur_start.ch--;
  4481. if(cur_start !== cur_end) {
  4482. cur_end.ch--;
  4483. }
  4484. cm.setSelection(cur_start, cur_end);
  4485. cm.focus();
  4486. } else if(is_code === "fenced") {
  4487. if(cur_start.line !== cur_end.line || cur_start.ch !== cur_end.ch) {
  4488. // use selection
  4489. // find the fenced line so we know what type it is (tilde, backticks, number of them)
  4490. for(block_start = cur_start.line; block_start >= 0; block_start--) {
  4491. line = cm.getLineHandle(block_start);
  4492. if(fencing_line(line)) {
  4493. break;
  4494. }
  4495. }
  4496. var fencedTok = cm.getTokenAt({
  4497. line: block_start,
  4498. ch: 1
  4499. });
  4500. var fence_chars = token_state(fencedTok).fencedChars;
  4501. var start_text, start_line;
  4502. var end_text, end_line;
  4503. // check for selection going up against fenced lines, in which case we don't want to add more fencing
  4504. if(fencing_line(cm.getLineHandle(cur_start.line))) {
  4505. start_text = "";
  4506. start_line = cur_start.line;
  4507. } else if(fencing_line(cm.getLineHandle(cur_start.line - 1))) {
  4508. start_text = "";
  4509. start_line = cur_start.line - 1;
  4510. } else {
  4511. start_text = fence_chars + "\n";
  4512. start_line = cur_start.line;
  4513. }
  4514. if(fencing_line(cm.getLineHandle(cur_end.line))) {
  4515. end_text = "";
  4516. end_line = cur_end.line;
  4517. if(cur_end.ch === 0) {
  4518. end_line += 1;
  4519. }
  4520. } else if(cur_end.ch !== 0 && fencing_line(cm.getLineHandle(cur_end.line + 1))) {
  4521. end_text = "";
  4522. end_line = cur_end.line + 1;
  4523. } else {
  4524. end_text = fence_chars + "\n";
  4525. end_line = cur_end.line + 1;
  4526. }
  4527. if(cur_end.ch === 0) {
  4528. // full last line selected, putting cursor at beginning of next
  4529. end_line -= 1;
  4530. }
  4531. cm.operation(function() {
  4532. // end line first, so that line numbers don't change
  4533. cm.replaceRange(end_text, {
  4534. line: end_line,
  4535. ch: 0
  4536. }, {
  4537. line: end_line + (end_text ? 0 : 1),
  4538. ch: 0
  4539. });
  4540. cm.replaceRange(start_text, {
  4541. line: start_line,
  4542. ch: 0
  4543. }, {
  4544. line: start_line + (start_text ? 0 : 1),
  4545. ch: 0
  4546. });
  4547. });
  4548. cm.setSelection({
  4549. line: start_line + (start_text ? 1 : 0),
  4550. ch: 0
  4551. }, {
  4552. line: end_line + (start_text ? 1 : -1),
  4553. ch: 0
  4554. });
  4555. cm.focus();
  4556. } else {
  4557. // no selection, search for ends of this fenced block
  4558. var search_from = cur_start.line;
  4559. if(fencing_line(cm.getLineHandle(cur_start.line))) { // gets a little tricky if cursor is right on a fenced line
  4560. if(code_type(cm, cur_start.line + 1) === "fenced") {
  4561. block_start = cur_start.line;
  4562. search_from = cur_start.line + 1; // for searching for "end"
  4563. } else {
  4564. block_end = cur_start.line;
  4565. search_from = cur_start.line - 1; // for searching for "start"
  4566. }
  4567. }
  4568. if(block_start === undefined) {
  4569. for(block_start = search_from; block_start >= 0; block_start--) {
  4570. line = cm.getLineHandle(block_start);
  4571. if(fencing_line(line)) {
  4572. break;
  4573. }
  4574. }
  4575. }
  4576. if(block_end === undefined) {
  4577. lineCount = cm.lineCount();
  4578. for(block_end = search_from; block_end < lineCount; block_end++) {
  4579. line = cm.getLineHandle(block_end);
  4580. if(fencing_line(line)) {
  4581. break;
  4582. }
  4583. }
  4584. }
  4585. cm.operation(function() {
  4586. cm.replaceRange("", {
  4587. line: block_start,
  4588. ch: 0
  4589. }, {
  4590. line: block_start + 1,
  4591. ch: 0
  4592. });
  4593. cm.replaceRange("", {
  4594. line: block_end - 1,
  4595. ch: 0
  4596. }, {
  4597. line: block_end,
  4598. ch: 0
  4599. });
  4600. });
  4601. cm.focus();
  4602. }
  4603. } else if(is_code === "indented") {
  4604. if(cur_start.line !== cur_end.line || cur_start.ch !== cur_end.ch) {
  4605. // use selection
  4606. block_start = cur_start.line;
  4607. block_end = cur_end.line;
  4608. if(cur_end.ch === 0) {
  4609. block_end--;
  4610. }
  4611. } else {
  4612. // no selection, search for ends of this indented block
  4613. for(block_start = cur_start.line; block_start >= 0; block_start--) {
  4614. line = cm.getLineHandle(block_start);
  4615. if(line.text.match(/^\s*$/)) {
  4616. // empty or all whitespace - keep going
  4617. continue;
  4618. } else {
  4619. if(code_type(cm, block_start, line) !== "indented") {
  4620. block_start += 1;
  4621. break;
  4622. }
  4623. }
  4624. }
  4625. lineCount = cm.lineCount();
  4626. for(block_end = cur_start.line; block_end < lineCount; block_end++) {
  4627. line = cm.getLineHandle(block_end);
  4628. if(line.text.match(/^\s*$/)) {
  4629. // empty or all whitespace - keep going
  4630. continue;
  4631. } else {
  4632. if(code_type(cm, block_end, line) !== "indented") {
  4633. block_end -= 1;
  4634. break;
  4635. }
  4636. }
  4637. }
  4638. }
  4639. // if we are going to un-indent based on a selected set of lines, and the next line is indented too, we need to
  4640. // insert a blank line so that the next line(s) continue to be indented code
  4641. var next_line = cm.getLineHandle(block_end + 1),
  4642. next_line_last_tok = next_line && cm.getTokenAt({
  4643. line: block_end + 1,
  4644. ch: next_line.text.length - 1
  4645. }),
  4646. next_line_indented = next_line_last_tok && token_state(next_line_last_tok).indentedCode;
  4647. if(next_line_indented) {
  4648. cm.replaceRange("\n", {
  4649. line: block_end + 1,
  4650. ch: 0
  4651. });
  4652. }
  4653. for(var i = block_start; i <= block_end; i++) {
  4654. cm.indentLine(i, "subtract"); // TODO: this doesn't get tracked in the history, so can't be undone :(
  4655. }
  4656. cm.focus();
  4657. } else {
  4658. // insert code formatting
  4659. var no_sel_and_starting_of_line = (cur_start.line === cur_end.line && cur_start.ch === cur_end.ch && cur_start.ch === 0);
  4660. var sel_multi = cur_start.line !== cur_end.line;
  4661. if(no_sel_and_starting_of_line || sel_multi) {
  4662. insertFencingAtSelection(cm, cur_start, cur_end, fenceCharsToInsert);
  4663. } else {
  4664. _replaceSelection(cm, false, ["`", "`"]);
  4665. }
  4666. }
  4667. }
  4668. /**
  4669. * Action for toggling blockquote.
  4670. */
  4671. function toggleBlockquote(editor) {
  4672. var cm = editor.codemirror;
  4673. _toggleLine(cm, "quote");
  4674. }
  4675. /**
  4676. * Action for toggling heading size: normal -> h1 -> h2 -> h3 -> h4 -> h5 -> h6 -> normal
  4677. */
  4678. function toggleHeadingSmaller(editor) {
  4679. var cm = editor.codemirror;
  4680. _toggleHeading(cm, "smaller");
  4681. }
  4682. /**
  4683. * Action for toggling heading size: normal -> h6 -> h5 -> h4 -> h3 -> h2 -> h1 -> normal
  4684. */
  4685. function toggleHeadingBigger(editor) {
  4686. var cm = editor.codemirror;
  4687. _toggleHeading(cm, "bigger");
  4688. }
  4689. /**
  4690. * Action for toggling heading size 1
  4691. */
  4692. function toggleHeading1(editor) {
  4693. var cm = editor.codemirror;
  4694. _toggleHeading(cm, undefined, 1);
  4695. }
  4696. /**
  4697. * Action for toggling heading size 2
  4698. */
  4699. function toggleHeading2(editor) {
  4700. var cm = editor.codemirror;
  4701. _toggleHeading(cm, undefined, 2);
  4702. }
  4703. /**
  4704. * Action for toggling heading size 3
  4705. */
  4706. function toggleHeading3(editor) {
  4707. var cm = editor.codemirror;
  4708. _toggleHeading(cm, undefined, 3);
  4709. }
  4710. /**
  4711. * Action for toggling ul.
  4712. */
  4713. function toggleUnorderedList(editor) {
  4714. var cm = editor.codemirror;
  4715. _toggleLine(cm, "unordered-list");
  4716. }
  4717. /**
  4718. * Action for toggling ol.
  4719. */
  4720. function toggleOrderedList(editor) {
  4721. var cm = editor.codemirror;
  4722. _toggleLine(cm, "ordered-list");
  4723. }
  4724. /**
  4725. * Action for clean block (remove headline, list, blockquote code, markers)
  4726. */
  4727. function cleanBlock(editor) {
  4728. var cm = editor.codemirror;
  4729. _cleanBlock(cm);
  4730. }
  4731. /**
  4732. * Action for drawing a link.
  4733. */
  4734. function drawLink(editor) {
  4735. var cm = editor.codemirror;
  4736. var stat = getState(cm);
  4737. var options = editor.options;
  4738. var url = "safe://";
  4739. if(options.promptURLs) {
  4740. url = prompt(options.promptTexts.link);
  4741. if(!url) {
  4742. return false;
  4743. }
  4744. }
  4745. _replaceSelection(cm, stat.link, options.insertTexts.link, url);
  4746. }
  4747. /**
  4748. * Action for drawing an img.
  4749. */
  4750. function drawImage(editor) {
  4751. var cm = editor.codemirror;
  4752. var stat = getState(cm);
  4753. var options = editor.options;
  4754. var url = "safe://";
  4755. if(options.promptURLs) {
  4756. url = prompt(options.promptTexts.image);
  4757. if(!url) {
  4758. return false;
  4759. }
  4760. }
  4761. _replaceSelection(cm, stat.image, options.insertTexts.image, url);
  4762. }
  4763. /**
  4764. * Action for drawing a table.
  4765. */
  4766. function drawTable(editor) {
  4767. var cm = editor.codemirror;
  4768. var stat = getState(cm);
  4769. var options = editor.options;
  4770. _replaceSelection(cm, stat.table, options.insertTexts.table);
  4771. }
  4772. /**
  4773. * Action for drawing a horizontal rule.
  4774. */
  4775. function drawHorizontalRule(editor) {
  4776. var cm = editor.codemirror;
  4777. var stat = getState(cm);
  4778. var options = editor.options;
  4779. _replaceSelection(cm, stat.image, options.insertTexts.horizontalRule);
  4780. }
  4781. /**
  4782. * Undo action.
  4783. */
  4784. function undo(editor) {
  4785. var cm = editor.codemirror;
  4786. cm.undo();
  4787. cm.focus();
  4788. }
  4789. /**
  4790. * Redo action.
  4791. */
  4792. function redo(editor) {
  4793. var cm = editor.codemirror;
  4794. cm.redo();
  4795. cm.focus();
  4796. }
  4797. /**
  4798. * Toggle side by side preview
  4799. */
  4800. function toggleSideBySide(editor) {
  4801. var cm = editor.codemirror;
  4802. var wrapper = cm.getWrapperElement();
  4803. var preview = wrapper.nextSibling;
  4804. var toolbarButton = editor.toolbarElements["side-by-side"];
  4805. var useSideBySideListener = false;
  4806. if(/editor-preview-active-side/.test(preview.className)) {
  4807. preview.className = preview.className.replace(
  4808. /\s*editor-preview-active-side\s*/g, ""
  4809. );
  4810. toolbarButton.className = toolbarButton.className.replace(/\s*active\s*/g, "");
  4811. wrapper.className = wrapper.className.replace(/\s*CodeMirror-sided\s*/g, " ");
  4812. } else {
  4813. // When the preview button is clicked for the first time,
  4814. // give some time for the transition from editor.css to fire and the view to slide from right to left,
  4815. // instead of just appearing.
  4816. setTimeout(function() {
  4817. if(!cm.getOption("fullScreen"))
  4818. toggleFullScreen(editor);
  4819. preview.className += " editor-preview-active-side";
  4820. }, 1);
  4821. toolbarButton.className += " active";
  4822. wrapper.className += " CodeMirror-sided";
  4823. useSideBySideListener = true;
  4824. }
  4825. // Hide normal preview if active
  4826. var previewNormal = wrapper.lastChild;
  4827. if(/editor-preview-active/.test(previewNormal.className)) {
  4828. previewNormal.className = previewNormal.className.replace(
  4829. /\s*editor-preview-active\s*/g, ""
  4830. );
  4831. var toolbar = editor.toolbarElements.preview;
  4832. var toolbar_div = wrapper.previousSibling;
  4833. toolbar.className = toolbar.className.replace(/\s*active\s*/g, "");
  4834. toolbar_div.className = toolbar_div.className.replace(/\s*disabled-for-preview*/g, "");
  4835. }
  4836. var sideBySideRenderingFunction = function() {
  4837. preview.innerHTML = editor.options.previewRender(editor.value(), preview);
  4838. };
  4839. if(!cm.sideBySideRenderingFunction) {
  4840. cm.sideBySideRenderingFunction = sideBySideRenderingFunction;
  4841. }
  4842. if(useSideBySideListener) {
  4843. preview.innerHTML = editor.options.previewRender(editor.value(), preview);
  4844. cm.on("update", cm.sideBySideRenderingFunction);
  4845. } else {
  4846. cm.off("update", cm.sideBySideRenderingFunction);
  4847. }
  4848. // Refresh to fix selection being off (#309)
  4849. cm.refresh();
  4850. }
  4851. /**
  4852. * Preview action.
  4853. */
  4854. function togglePreview(editor) {
  4855. var cm = editor.codemirror;
  4856. var wrapper = cm.getWrapperElement();
  4857. var toolbar_div = wrapper.previousSibling;
  4858. var toolbar = editor.options.toolbar ? editor.toolbarElements.preview : false;
  4859. var preview = wrapper.lastChild;
  4860. if(!preview || !/editor-preview/.test(preview.className)) {
  4861. preview = document.createElement("div");
  4862. preview.className = "editor-preview";
  4863. wrapper.appendChild(preview);
  4864. }
  4865. if(/editor-preview-active/.test(preview.className)) {
  4866. preview.className = preview.className.replace(
  4867. /\s*editor-preview-active\s*/g, ""
  4868. );
  4869. if(toolbar) {
  4870. toolbar.className = toolbar.className.replace(/\s*active\s*/g, "");
  4871. toolbar_div.className = toolbar_div.className.replace(/\s*disabled-for-preview*/g, "");
  4872. }
  4873. } else {
  4874. // When the preview button is clicked for the first time,
  4875. // give some time for the transition from editor.css to fire and the view to slide from right to left,
  4876. // instead of just appearing.
  4877. setTimeout(function() {
  4878. preview.className += " editor-preview-active";
  4879. }, 1);
  4880. if(toolbar) {
  4881. toolbar.className += " active";
  4882. toolbar_div.className += " disabled-for-preview";
  4883. }
  4884. }
  4885. preview.innerHTML = editor.options.previewRender(editor.value(), preview);
  4886. // Turn off side by side if needed
  4887. var sidebyside = cm.getWrapperElement().nextSibling;
  4888. if(/editor-preview-active-side/.test(sidebyside.className))
  4889. toggleSideBySide(editor);
  4890. }
  4891. function _replaceSelection(cm, active, startEnd, url) {
  4892. if(/editor-preview-active/.test(cm.getWrapperElement().lastChild.className))
  4893. return;
  4894. var text;
  4895. var start = startEnd[0];
  4896. var end = startEnd[1];
  4897. var startPoint = cm.getCursor("start");
  4898. var endPoint = cm.getCursor("end");
  4899. if(url) {
  4900. end = end.replace("#url#", url);
  4901. }
  4902. if(active) {
  4903. text = cm.getLine(startPoint.line);
  4904. start = text.slice(0, startPoint.ch);
  4905. end = text.slice(startPoint.ch);
  4906. cm.replaceRange(start + end, {
  4907. line: startPoint.line,
  4908. ch: 0
  4909. });
  4910. } else {
  4911. text = cm.getSelection();
  4912. cm.replaceSelection(start + text + end);
  4913. startPoint.ch += start.length;
  4914. if(startPoint !== endPoint) {
  4915. endPoint.ch += start.length;
  4916. }
  4917. }
  4918. cm.setSelection(startPoint, endPoint);
  4919. cm.focus();
  4920. }
  4921. function _toggleHeading(cm, direction, size) {
  4922. if(/editor-preview-active/.test(cm.getWrapperElement().lastChild.className))
  4923. return;
  4924. var startPoint = cm.getCursor("start");
  4925. var endPoint = cm.getCursor("end");
  4926. for(var i = startPoint.line; i <= endPoint.line; i++) {
  4927. (function(i) {
  4928. var text = cm.getLine(i);
  4929. var currHeadingLevel = text.search(/[^#]/);
  4930. if(direction !== undefined) {
  4931. if(currHeadingLevel <= 0) {
  4932. if(direction == "bigger") {
  4933. text = "###### " + text;
  4934. } else {
  4935. text = "# " + text;
  4936. }
  4937. } else if(currHeadingLevel == 6 && direction == "smaller") {
  4938. text = text.substr(7);
  4939. } else if(currHeadingLevel == 1 && direction == "bigger") {
  4940. text = text.substr(2);
  4941. } else {
  4942. if(direction == "bigger") {
  4943. text = text.substr(1);
  4944. } else {
  4945. text = "#" + text;
  4946. }
  4947. }
  4948. } else {
  4949. if(size == 1) {
  4950. if(currHeadingLevel <= 0) {
  4951. text = "# " + text;
  4952. } else if(currHeadingLevel == size) {
  4953. text = text.substr(currHeadingLevel + 1);
  4954. } else {
  4955. text = "# " + text.substr(currHeadingLevel + 1);
  4956. }
  4957. } else if(size == 2) {
  4958. if(currHeadingLevel <= 0) {
  4959. text = "## " + text;
  4960. } else if(currHeadingLevel == size) {
  4961. text = text.substr(currHeadingLevel + 1);
  4962. } else {
  4963. text = "## " + text.substr(currHeadingLevel + 1);
  4964. }
  4965. } else {
  4966. if(currHeadingLevel <= 0) {
  4967. text = "### " + text;
  4968. } else if(currHeadingLevel == size) {
  4969. text = text.substr(currHeadingLevel + 1);
  4970. } else {
  4971. text = "### " + text.substr(currHeadingLevel + 1);
  4972. }
  4973. }
  4974. }
  4975. cm.replaceRange(text, {
  4976. line: i,
  4977. ch: 0
  4978. }, {
  4979. line: i,
  4980. ch: 99999999999999
  4981. });
  4982. })(i);
  4983. }
  4984. cm.focus();
  4985. }
  4986. function _toggleLine(cm, name) {
  4987. if(/editor-preview-active/.test(cm.getWrapperElement().lastChild.className))
  4988. return;
  4989. var stat = getState(cm);
  4990. var startPoint = cm.getCursor("start");
  4991. var endPoint = cm.getCursor("end");
  4992. var repl = {
  4993. "quote": /^(\s*)\>\s+/,
  4994. "unordered-list": /^(\s*)(\*|\-|\+)\s+/,
  4995. "ordered-list": /^(\s*)\d+\.\s+/
  4996. };
  4997. var map = {
  4998. "quote": "> ",
  4999. "unordered-list": "* ",
  5000. "ordered-list": "1. "
  5001. };
  5002. for(var i = startPoint.line; i <= endPoint.line; i++) {
  5003. (function(i) {
  5004. var text = cm.getLine(i);
  5005. if(stat[name]) {
  5006. text = text.replace(repl[name], "$1");
  5007. } else {
  5008. text = map[name] + text;
  5009. }
  5010. cm.replaceRange(text, {
  5011. line: i,
  5012. ch: 0
  5013. }, {
  5014. line: i,
  5015. ch: 99999999999999
  5016. });
  5017. })(i);
  5018. }
  5019. cm.focus();
  5020. }
  5021. function _toggleBlock(editor, type, start_chars, end_chars) {
  5022. if(/editor-preview-active/.test(editor.codemirror.getWrapperElement().lastChild.className))
  5023. return;
  5024. end_chars = (typeof end_chars === "undefined") ? start_chars : end_chars;
  5025. var cm = editor.codemirror;
  5026. var stat = getState(cm);
  5027. var text;
  5028. var start = start_chars;
  5029. var end = end_chars;
  5030. var startPoint = cm.getCursor("start");
  5031. var endPoint = cm.getCursor("end");
  5032. if(stat[type]) {
  5033. text = cm.getLine(startPoint.line);
  5034. start = text.slice(0, startPoint.ch);
  5035. end = text.slice(startPoint.ch);
  5036. if(type == "bold") {
  5037. start = start.replace(/(\*\*|__)(?![\s\S]*(\*\*|__))/, "");
  5038. end = end.replace(/(\*\*|__)/, "");
  5039. } else if(type == "italic") {
  5040. start = start.replace(/(\*|_)(?![\s\S]*(\*|_))/, "");
  5041. end = end.replace(/(\*|_)/, "");
  5042. } else if(type == "strikethrough") {
  5043. start = start.replace(/(\*\*|~~)(?![\s\S]*(\*\*|~~))/, "");
  5044. end = end.replace(/(\*\*|~~)/, "");
  5045. }
  5046. cm.replaceRange(start + end, {
  5047. line: startPoint.line,
  5048. ch: 0
  5049. }, {
  5050. line: startPoint.line,
  5051. ch: 99999999999999
  5052. });
  5053. if(type == "bold" || type == "strikethrough") {
  5054. startPoint.ch -= 2;
  5055. if(startPoint !== endPoint) {
  5056. endPoint.ch -= 2;
  5057. }
  5058. } else if(type == "italic") {
  5059. startPoint.ch -= 1;
  5060. if(startPoint !== endPoint) {
  5061. endPoint.ch -= 1;
  5062. }
  5063. }
  5064. } else {
  5065. text = cm.getSelection();
  5066. if(type == "bold") {
  5067. text = text.split("**").join("");
  5068. text = text.split("__").join("");
  5069. } else if(type == "italic") {
  5070. text = text.split("*").join("");
  5071. text = text.split("_").join("");
  5072. } else if(type == "strikethrough") {
  5073. text = text.split("~~").join("");
  5074. }
  5075. cm.replaceSelection(start + text + end);
  5076. startPoint.ch += start_chars.length;
  5077. endPoint.ch = startPoint.ch + text.length;
  5078. }
  5079. cm.setSelection(startPoint, endPoint);
  5080. cm.focus();
  5081. }
  5082. function _cleanBlock(cm) {
  5083. if(/editor-preview-active/.test(cm.getWrapperElement().lastChild.className))
  5084. return;
  5085. var startPoint = cm.getCursor("start");
  5086. var endPoint = cm.getCursor("end");
  5087. var text;
  5088. for(var line = startPoint.line; line <= endPoint.line; line++) {
  5089. text = cm.getLine(line);
  5090. text = text.replace(/^[ ]*([# ]+|\*|\-|[> ]+|[0-9]+(.|\)))[ ]*/, "");
  5091. cm.replaceRange(text, {
  5092. line: line,
  5093. ch: 0
  5094. }, {
  5095. line: line,
  5096. ch: 99999999999999
  5097. });
  5098. }
  5099. }
  5100. // Merge the properties of one object into another.
  5101. function _mergeProperties(target, source) {
  5102. for(var property in source) {
  5103. if(source.hasOwnProperty(property)) {
  5104. if(source[property] instanceof Array) {
  5105. target[property] = source[property].concat(target[property] instanceof Array ? target[property] : []);
  5106. } else if(
  5107. source[property] !== null &&
  5108. typeof source[property] === "object" &&
  5109. source[property].constructor === Object
  5110. ) {
  5111. target[property] = _mergeProperties(target[property] || {}, source[property]);
  5112. } else {
  5113. target[property] = source[property];
  5114. }
  5115. }
  5116. }
  5117. return target;
  5118. }
  5119. // Merge an arbitrary number of objects into one.
  5120. function extend(target) {
  5121. for(var i = 1; i < arguments.length; i++) {
  5122. target = _mergeProperties(target, arguments[i]);
  5123. }
  5124. return target;
  5125. }
  5126. /* The right word count in respect for CJK. */
  5127. function wordCount(data) {
  5128. var pattern = /[a-zA-Z0-9_\u0392-\u03c9\u0410-\u04F9]+|[\u4E00-\u9FFF\u3400-\u4dbf\uf900-\ufaff\u3040-\u309f\uac00-\ud7af]+/g;
  5129. var m = data.match(pattern);
  5130. var count = 0;
  5131. if(m === null) return count;
  5132. for(var i = 0; i < m.length; i++) {
  5133. if(m[i].charCodeAt(0) >= 0x4E00) {
  5134. count += m[i].length;
  5135. } else {
  5136. count += 1;
  5137. }
  5138. }
  5139. return count;
  5140. }
  5141. var toolbarBuiltInButtons = {
  5142. "bold": {
  5143. name: "bold",
  5144. action: toggleBold,
  5145. className: "fa fa-bold",
  5146. title: "Bold",
  5147. default: true
  5148. },
  5149. "italic": {
  5150. name: "italic",
  5151. action: toggleItalic,
  5152. className: "fa fa-italic",
  5153. title: "Italic",
  5154. default: true
  5155. },
  5156. "strikethrough": {
  5157. name: "strikethrough",
  5158. action: toggleStrikethrough,
  5159. className: "fa fa-strikethrough",
  5160. title: "Strikethrough"
  5161. },
  5162. "heading": {
  5163. name: "heading",
  5164. action: toggleHeadingSmaller,
  5165. className: "fa fa-header",
  5166. title: "Heading",
  5167. default: true
  5168. },
  5169. "heading-smaller": {
  5170. name: "heading-smaller",
  5171. action: toggleHeadingSmaller,
  5172. className: "fa fa-header fa-header-x fa-header-smaller",
  5173. title: "Smaller Heading"
  5174. },
  5175. "heading-bigger": {
  5176. name: "heading-bigger",
  5177. action: toggleHeadingBigger,
  5178. className: "fa fa-header fa-header-x fa-header-bigger",
  5179. title: "Bigger Heading"
  5180. },
  5181. "heading-1": {
  5182. name: "heading-1",
  5183. action: toggleHeading1,
  5184. className: "fa fa-header fa-header-x fa-header-1",
  5185. title: "Big Heading"
  5186. },
  5187. "heading-2": {
  5188. name: "heading-2",
  5189. action: toggleHeading2,
  5190. className: "fa fa-header fa-header-x fa-header-2",
  5191. title: "Medium Heading"
  5192. },
  5193. "heading-3": {
  5194. name: "heading-3",
  5195. action: toggleHeading3,
  5196. className: "fa fa-header fa-header-x fa-header-3",
  5197. title: "Small Heading"
  5198. },
  5199. "separator-1": {
  5200. name: "separator-1"
  5201. },
  5202. "code": {
  5203. name: "code",
  5204. action: toggleCodeBlock,
  5205. className: "fa fa-code",
  5206. title: "Code"
  5207. },
  5208. "quote": {
  5209. name: "quote",
  5210. action: toggleBlockquote,
  5211. className: "fa fa-quote-left",
  5212. title: "Quote",
  5213. default: true
  5214. },
  5215. "unordered-list": {
  5216. name: "unordered-list",
  5217. action: toggleUnorderedList,
  5218. className: "fa fa-list-ul",
  5219. title: "Generic List",
  5220. default: true
  5221. },
  5222. "ordered-list": {
  5223. name: "ordered-list",
  5224. action: toggleOrderedList,
  5225. className: "fa fa-list-ol",
  5226. title: "Numbered List",
  5227. default: true
  5228. },
  5229. "clean-block": {
  5230. name: "clean-block",
  5231. action: cleanBlock,
  5232. className: "fa fa-eraser fa-clean-block",
  5233. title: "Clean block"
  5234. },
  5235. "separator-2": {
  5236. name: "separator-2"
  5237. },
  5238. "link": {
  5239. name: "link",
  5240. action: drawLink,
  5241. className: "fa fa-link",
  5242. title: "Create Link",
  5243. default: true
  5244. },
  5245. "image": {
  5246. name: "image",
  5247. action: drawImage,
  5248. className: "fa fa-picture-o",
  5249. title: "Insert Image",
  5250. default: true
  5251. },
  5252. "table": {
  5253. name: "table",
  5254. action: drawTable,
  5255. className: "fa fa-table",
  5256. title: "Insert Table"
  5257. },
  5258. "horizontal-rule": {
  5259. name: "horizontal-rule",
  5260. action: drawHorizontalRule,
  5261. className: "fa fa-minus",
  5262. title: "Insert Horizontal Line"
  5263. },
  5264. "separator-3": {
  5265. name: "separator-3"
  5266. },
  5267. "preview": {
  5268. name: "preview",
  5269. action: togglePreview,
  5270. className: "fa fa-eye no-disable",
  5271. title: "Toggle Preview",
  5272. default: true
  5273. },
  5274. "side-by-side": {
  5275. name: "side-by-side",
  5276. action: toggleSideBySide,
  5277. className: "fa fa-columns no-disable no-mobile",
  5278. title: "Toggle Side by Side",
  5279. default: true
  5280. },
  5281. "fullscreen": {
  5282. name: "fullscreen",
  5283. action: toggleFullScreen,
  5284. className: "fa fa-arrows-alt no-disable no-mobile",
  5285. title: "Toggle Fullscreen",
  5286. default: true
  5287. },
  5288. "separator-4": {
  5289. name: "separator-4"
  5290. },
  5291. "guide": {
  5292. name: "guide",
  5293. action: "safe://markdown-guide", // maybe one day
  5294. className: "fa fa-question-circle",
  5295. title: "Markdown Guide",
  5296. default: false // disable this for now
  5297. },
  5298. "separator-5": {
  5299. name: "separator-5"
  5300. },
  5301. "undo": {
  5302. name: "undo",
  5303. action: undo,
  5304. className: "fa fa-undo no-disable",
  5305. title: "Undo"
  5306. },
  5307. "redo": {
  5308. name: "redo",
  5309. action: redo,
  5310. className: "fa fa-repeat no-disable",
  5311. title: "Redo"
  5312. }
  5313. };
  5314. var insertTexts = {
  5315. link: ["[", "](#url#)"],
  5316. image: ["![", "](#url#)"],
  5317. table: ["", "\n\n| Column 1 | Column 2 | Column 3 |\n| -------- | -------- | -------- |\n| Text | Text | Text |\n\n"],
  5318. horizontalRule: ["", "\n\n-----\n\n"]
  5319. };
  5320. var promptTexts = {
  5321. link: "URL for the link:",
  5322. image: "URL of the image:"
  5323. };
  5324. var blockStyles = {
  5325. "bold": "**",
  5326. "code": "```",
  5327. "italic": "*"
  5328. };
  5329. /**
  5330. * Interface of SimpleMDE.
  5331. */
  5332. function SimpleMDE(options) {
  5333. // Handle options parameter
  5334. options = options || {};
  5335. // Used later to refer to it"s parent
  5336. options.parent = this;
  5337. // Check if Font Awesome needs to be auto downloaded
  5338. // var autoDownloadFA = true;
  5339. var autoDownloadFA = false; // lets disable this for now
  5340. if(options.autoDownloadFontAwesome === false) {
  5341. autoDownloadFA = false; //
  5342. }
  5343. if(options.autoDownloadFontAwesome !== true) {
  5344. var styleSheets = document.styleSheets;
  5345. for(var i = 0; i < styleSheets.length; i++) {
  5346. if(!styleSheets[i].href)
  5347. continue;
  5348. if(styleSheets[i].href.indexOf("//maxcdn.bootstrapcdn.com/font-awesome/") > -1) {
  5349. autoDownloadFA = false;
  5350. }
  5351. }
  5352. }
  5353. if(autoDownloadFA) {
  5354. var link = document.createElement("link");
  5355. link.rel = "stylesheet";
  5356. // link.href = "https://maxcdn.bootstrapcdn.com/font-awesome/latest/css/font-awesome.min.css"; //we really don't want to make an http request
  5357. link.href = "safe://somepath/font-awesome.min.css"; // one day maybe
  5358. document.getElementsByTagName("head")[0].appendChild(link);
  5359. }
  5360. // Find the textarea to use
  5361. if(options.element) {
  5362. this.element = options.element;
  5363. } else if(options.element === null) {
  5364. // This means that the element option was specified, but no element was found
  5365. console.log("SimpleMDE: Error. No element was found.");
  5366. return;
  5367. }
  5368. // Handle toolbar
  5369. if(options.toolbar === undefined) {
  5370. // Initialize
  5371. options.toolbar = [];
  5372. // Loop over the built in buttons, to get the preferred order
  5373. for(var key in toolbarBuiltInButtons) {
  5374. if(toolbarBuiltInButtons.hasOwnProperty(key)) {
  5375. if(key.indexOf("separator-") != -1) {
  5376. options.toolbar.push("|");
  5377. }
  5378. if(toolbarBuiltInButtons[key].default === true || (options.showIcons && options.showIcons.constructor === Array && options.showIcons.indexOf(key) != -1)) {
  5379. options.toolbar.push(key);
  5380. }
  5381. }
  5382. }
  5383. }
  5384. // Handle status bar
  5385. if(!options.hasOwnProperty("status")) {
  5386. options.status = ["autosave", "lines", "words", "cursor"];
  5387. }
  5388. // Add default preview rendering function
  5389. if(!options.previewRender) {
  5390. options.previewRender = function(plainText) {
  5391. // Note: "this" refers to the options object
  5392. return this.parent.markdown(plainText);
  5393. };
  5394. }
  5395. // Set default options for parsing config
  5396. options.parsingConfig = extend({
  5397. highlightFormatting: true // needed for toggleCodeBlock to detect types of code
  5398. }, options.parsingConfig || {});
  5399. // Merging the insertTexts, with the given options
  5400. options.insertTexts = extend({}, insertTexts, options.insertTexts || {});
  5401. // Merging the promptTexts, with the given options
  5402. options.promptTexts = promptTexts;
  5403. // Merging the blockStyles, with the given options
  5404. options.blockStyles = extend({}, blockStyles, options.blockStyles || {});
  5405. // Merging the shortcuts, with the given options
  5406. options.shortcuts = extend({}, shortcuts, options.shortcuts || {});
  5407. // Change unique_id to uniqueId for backwards compatibility
  5408. if(options.autosave != undefined && options.autosave.unique_id != undefined && options.autosave.unique_id != "")
  5409. options.autosave.uniqueId = options.autosave.unique_id;
  5410. // Update this options
  5411. this.options = options;
  5412. // Auto render
  5413. this.render();
  5414. // The codemirror component is only available after rendering
  5415. // so, the setter for the initialValue can only run after
  5416. // the element has been rendered
  5417. if(options.initialValue && (!this.options.autosave || this.options.autosave.foundSavedValue !== true)) {
  5418. this.value(options.initialValue);
  5419. }
  5420. }
  5421. /**
  5422. * Default markdown render.
  5423. */
  5424. SimpleMDE.prototype.markdown = function(text) {
  5425. if(marked) {
  5426. // Initialize
  5427. var markedOptions = {};
  5428. // Update options
  5429. if(this.options && this.options.renderingConfig && this.options.renderingConfig.singleLineBreaks === false) {
  5430. markedOptions.breaks = false;
  5431. } else {
  5432. markedOptions.breaks = true;
  5433. }
  5434. if(this.options && this.options.renderingConfig && this.options.renderingConfig.codeSyntaxHighlighting === true && window.hljs) {
  5435. markedOptions.highlight = function(code) {
  5436. return window.hljs.highlightAuto(code).value;
  5437. };
  5438. }
  5439. // Set options
  5440. marked.setOptions(markedOptions);
  5441. // Return
  5442. return marked(text);
  5443. }
  5444. };
  5445. /**
  5446. * Render editor to the given element.
  5447. */
  5448. SimpleMDE.prototype.render = function(el) {
  5449. if(!el) {
  5450. el = this.element || document.getElementsByTagName("textarea")[0];
  5451. }
  5452. if(this._rendered && this._rendered === el) {
  5453. // Already rendered.
  5454. return;
  5455. }
  5456. this.element = el;
  5457. var options = this.options;
  5458. var self = this;
  5459. var keyMaps = {};
  5460. for(var key in options.shortcuts) {
  5461. // null stands for "do not bind this command"
  5462. if(options.shortcuts[key] !== null && bindings[key] !== null) {
  5463. (function(key) {
  5464. keyMaps[fixShortcut(options.shortcuts[key])] = function() {
  5465. bindings[key](self);
  5466. };
  5467. })(key);
  5468. }
  5469. }
  5470. keyMaps["Enter"] = "newlineAndIndentContinueMarkdownList";
  5471. keyMaps["Tab"] = "tabAndIndentMarkdownList";
  5472. keyMaps["Shift-Tab"] = "shiftTabAndUnindentMarkdownList";
  5473. keyMaps["Esc"] = function(cm) {
  5474. if(cm.getOption("fullScreen")) toggleFullScreen(self);
  5475. };
  5476. document.addEventListener("keydown", function(e) {
  5477. e = e || window.event;
  5478. if(e.keyCode == 27) {
  5479. if(self.codemirror.getOption("fullScreen")) toggleFullScreen(self);
  5480. }
  5481. }, false);
  5482. var mode, backdrop;
  5483. if(options.spellChecker !== false) {
  5484. mode = "spell-checker";
  5485. backdrop = options.parsingConfig;
  5486. backdrop.name = "gfm";
  5487. backdrop.gitHubSpice = false;
  5488. CodeMirrorSpellChecker({
  5489. codeMirrorInstance: CodeMirror
  5490. });
  5491. } else {
  5492. mode = options.parsingConfig;
  5493. mode.name = "gfm";
  5494. mode.gitHubSpice = false;
  5495. }
  5496. this.codemirror = CodeMirror.fromTextArea(el, {
  5497. mode: mode,
  5498. backdrop: backdrop,
  5499. theme: "paper",
  5500. tabSize: (options.tabSize != undefined) ? options.tabSize : 2,
  5501. indentUnit: (options.tabSize != undefined) ? options.tabSize : 2,
  5502. indentWithTabs: (options.indentWithTabs === false) ? false : true,
  5503. lineNumbers: false,
  5504. autofocus: (options.autofocus === true) ? true : false,
  5505. extraKeys: keyMaps,
  5506. lineWrapping: (options.lineWrapping === false) ? false : true,
  5507. allowDropFileTypes: ["text/plain"],
  5508. placeholder: options.placeholder || el.getAttribute("placeholder") || "",
  5509. styleSelectedText: (options.styleSelectedText != undefined) ? options.styleSelectedText : true
  5510. });
  5511. if(options.forceSync === true) {
  5512. var cm = this.codemirror;
  5513. cm.on("change", function() {
  5514. cm.save();
  5515. });
  5516. }
  5517. this.gui = {};
  5518. if(options.toolbar !== false) {
  5519. this.gui.toolbar = this.createToolbar();
  5520. }
  5521. if(options.status !== false) {
  5522. this.gui.statusbar = this.createStatusbar();
  5523. }
  5524. if(options.autosave != undefined && options.autosave.enabled === true) {
  5525. this.autosave();
  5526. }
  5527. this.gui.sideBySide = this.createSideBySide();
  5528. this._rendered = this.element;
  5529. // Fixes CodeMirror bug (#344)
  5530. var temp_cm = this.codemirror;
  5531. setTimeout(function() {
  5532. temp_cm.refresh();
  5533. }.bind(temp_cm), 0);
  5534. };
  5535. // 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.
  5536. function isLocalStorageAvailable() {
  5537. if(typeof localStorage === "object") {
  5538. try {
  5539. localStorage.setItem("smde_localStorage", 1);
  5540. localStorage.removeItem("smde_localStorage");
  5541. } catch(e) {
  5542. return false;
  5543. }
  5544. } else {
  5545. return false;
  5546. }
  5547. return true;
  5548. }
  5549. SimpleMDE.prototype.autosave = function() {
  5550. if(isLocalStorageAvailable()) {
  5551. var simplemde = this;
  5552. if(this.options.autosave.uniqueId == undefined || this.options.autosave.uniqueId == "") {
  5553. console.log("SimpleMDE: You must set a uniqueId to use the autosave feature");
  5554. return;
  5555. }
  5556. if(simplemde.element.form != null && simplemde.element.form != undefined) {
  5557. simplemde.element.form.addEventListener("submit", function() {
  5558. localStorage.removeItem("smde_" + simplemde.options.autosave.uniqueId);
  5559. });
  5560. }
  5561. if(this.options.autosave.loaded !== true) {
  5562. if(typeof localStorage.getItem("smde_" + this.options.autosave.uniqueId) == "string" && localStorage.getItem("smde_" + this.options.autosave.uniqueId) != "") {
  5563. this.codemirror.setValue(localStorage.getItem("smde_" + this.options.autosave.uniqueId));
  5564. this.options.autosave.foundSavedValue = true;
  5565. }
  5566. this.options.autosave.loaded = true;
  5567. }
  5568. localStorage.setItem("smde_" + this.options.autosave.uniqueId, simplemde.value());
  5569. var el = document.getElementById("autosaved");
  5570. if(el != null && el != undefined && el != "") {
  5571. var d = new Date();
  5572. var hh = d.getHours();
  5573. var m = d.getMinutes();
  5574. var dd = "am";
  5575. var h = hh;
  5576. if(h >= 12) {
  5577. h = hh - 12;
  5578. dd = "pm";
  5579. }
  5580. if(h == 0) {
  5581. h = 12;
  5582. }
  5583. m = m < 10 ? "0" + m : m;
  5584. el.innerHTML = "Autosaved: " + h + ":" + m + " " + dd;
  5585. }
  5586. this.autosaveTimeoutId = setTimeout(function() {
  5587. simplemde.autosave();
  5588. }, this.options.autosave.delay || 10000);
  5589. } else {
  5590. console.log("SimpleMDE: localStorage not available, cannot autosave");
  5591. }
  5592. };
  5593. SimpleMDE.prototype.clearAutosavedValue = function() {
  5594. if(isLocalStorageAvailable()) {
  5595. if(this.options.autosave == undefined || this.options.autosave.uniqueId == undefined || this.options.autosave.uniqueId == "") {
  5596. console.log("SimpleMDE: You must set a uniqueId to clear the autosave value");
  5597. return;
  5598. }
  5599. localStorage.removeItem("smde_" + this.options.autosave.uniqueId);
  5600. } else {
  5601. console.log("SimpleMDE: localStorage not available, cannot autosave");
  5602. }
  5603. };
  5604. SimpleMDE.prototype.createSideBySide = function() {
  5605. var cm = this.codemirror;
  5606. var wrapper = cm.getWrapperElement();
  5607. var preview = wrapper.nextSibling;
  5608. if(!preview || !/editor-preview-side/.test(preview.className)) {
  5609. preview = document.createElement("div");
  5610. preview.className = "editor-preview-side";
  5611. wrapper.parentNode.insertBefore(preview, wrapper.nextSibling);
  5612. }
  5613. // Syncs scroll editor -> preview
  5614. var cScroll = false;
  5615. var pScroll = false;
  5616. cm.on("scroll", function(v) {
  5617. if(cScroll) {
  5618. cScroll = false;
  5619. return;
  5620. }
  5621. pScroll = true;
  5622. var height = v.getScrollInfo().height - v.getScrollInfo().clientHeight;
  5623. var ratio = parseFloat(v.getScrollInfo().top) / height;
  5624. var move = (preview.scrollHeight - preview.clientHeight) * ratio;
  5625. preview.scrollTop = move;
  5626. });
  5627. // Syncs scroll preview -> editor
  5628. preview.onscroll = function() {
  5629. if(pScroll) {
  5630. pScroll = false;
  5631. return;
  5632. }
  5633. cScroll = true;
  5634. var height = preview.scrollHeight - preview.clientHeight;
  5635. var ratio = parseFloat(preview.scrollTop) / height;
  5636. var move = (cm.getScrollInfo().height - cm.getScrollInfo().clientHeight) * ratio;
  5637. cm.scrollTo(0, move);
  5638. };
  5639. return preview;
  5640. };
  5641. SimpleMDE.prototype.createToolbar = function(items) {
  5642. items = items || this.options.toolbar;
  5643. if(!items || items.length === 0) {
  5644. return;
  5645. }
  5646. var i;
  5647. for(i = 0; i < items.length; i++) {
  5648. if(toolbarBuiltInButtons[items[i]] != undefined) {
  5649. items[i] = toolbarBuiltInButtons[items[i]];
  5650. }
  5651. }
  5652. var bar = document.createElement("div");
  5653. bar.className = "editor-toolbar";
  5654. var self = this;
  5655. var toolbarData = {};
  5656. self.toolbar = items;
  5657. for(i = 0; i < items.length; i++) {
  5658. if(items[i].name == "guide" && self.options.toolbarGuideIcon === false)
  5659. continue;
  5660. if(self.options.hideIcons && self.options.hideIcons.indexOf(items[i].name) != -1)
  5661. continue;
  5662. // Fullscreen does not work well on mobile devices (even tablets)
  5663. // In the future, hopefully this can be resolved
  5664. if((items[i].name == "fullscreen" || items[i].name == "side-by-side") && isMobile())
  5665. continue;
  5666. // Don't include trailing separators
  5667. if(items[i] === "|") {
  5668. var nonSeparatorIconsFollow = false;
  5669. for(var x = (i + 1); x < items.length; x++) {
  5670. if(items[x] !== "|" && (!self.options.hideIcons || self.options.hideIcons.indexOf(items[x].name) == -1)) {
  5671. nonSeparatorIconsFollow = true;
  5672. }
  5673. }
  5674. if(!nonSeparatorIconsFollow)
  5675. continue;
  5676. }
  5677. // Create the icon and append to the toolbar
  5678. (function(item) {
  5679. var el;
  5680. if(item === "|") {
  5681. el = createSep();
  5682. } else {
  5683. el = createIcon(item, self.options.toolbarTips, self.options.shortcuts);
  5684. }
  5685. // bind events, special for info
  5686. if(item.action) {
  5687. if(typeof item.action === "function") {
  5688. el.onclick = function(e) {
  5689. e.preventDefault();
  5690. item.action(self);
  5691. };
  5692. } else if(typeof item.action === "string") {
  5693. el.href = item.action;
  5694. el.target = "_blank";
  5695. }
  5696. }
  5697. toolbarData[item.name || item] = el;
  5698. bar.appendChild(el);
  5699. })(items[i]);
  5700. }
  5701. self.toolbarElements = toolbarData;
  5702. var cm = this.codemirror;
  5703. cm.on("cursorActivity", function() {
  5704. var stat = getState(cm);
  5705. for(var key in toolbarData) {
  5706. (function(key) {
  5707. var el = toolbarData[key];
  5708. if(stat[key]) {
  5709. el.className += " active";
  5710. } else if(key != "fullscreen" && key != "side-by-side") {
  5711. el.className = el.className.replace(/\s*active\s*/g, "");
  5712. }
  5713. })(key);
  5714. }
  5715. });
  5716. var cmWrapper = cm.getWrapperElement();
  5717. cmWrapper.parentNode.insertBefore(bar, cmWrapper);
  5718. return bar;
  5719. };
  5720. SimpleMDE.prototype.createStatusbar = function(status) {
  5721. // Initialize
  5722. status = status || this.options.status;
  5723. var options = this.options;
  5724. var cm = this.codemirror;
  5725. // Make sure the status variable is valid
  5726. if(!status || status.length === 0)
  5727. return;
  5728. // Set up the built-in items
  5729. var items = [];
  5730. var i, onUpdate, defaultValue;
  5731. for(i = 0; i < status.length; i++) {
  5732. // Reset some values
  5733. onUpdate = undefined;
  5734. defaultValue = undefined;
  5735. // Handle if custom or not
  5736. if(typeof status[i] === "object") {
  5737. items.push({
  5738. className: status[i].className,
  5739. defaultValue: status[i].defaultValue,
  5740. onUpdate: status[i].onUpdate
  5741. });
  5742. } else {
  5743. var name = status[i];
  5744. if(name === "words") {
  5745. defaultValue = function(el) {
  5746. el.innerHTML = wordCount(cm.getValue());
  5747. };
  5748. onUpdate = function(el) {
  5749. el.innerHTML = wordCount(cm.getValue());
  5750. };
  5751. } else if(name === "lines") {
  5752. defaultValue = function(el) {
  5753. el.innerHTML = cm.lineCount();
  5754. };
  5755. onUpdate = function(el) {
  5756. el.innerHTML = cm.lineCount();
  5757. };
  5758. } else if(name === "cursor") {
  5759. defaultValue = function(el) {
  5760. el.innerHTML = "0:0";
  5761. };
  5762. onUpdate = function(el) {
  5763. var pos = cm.getCursor();
  5764. el.innerHTML = pos.line + ":" + pos.ch;
  5765. };
  5766. } else if(name === "autosave") {
  5767. defaultValue = function(el) {
  5768. if(options.autosave != undefined && options.autosave.enabled === true) {
  5769. el.setAttribute("id", "autosaved");
  5770. }
  5771. };
  5772. }
  5773. items.push({
  5774. className: name,
  5775. defaultValue: defaultValue,
  5776. onUpdate: onUpdate
  5777. });
  5778. }
  5779. }
  5780. // Create element for the status bar
  5781. var bar = document.createElement("div");
  5782. bar.className = "editor-statusbar";
  5783. // Create a new span for each item
  5784. for(i = 0; i < items.length; i++) {
  5785. // Store in temporary variable
  5786. var item = items[i];
  5787. // Create span element
  5788. var el = document.createElement("span");
  5789. el.className = item.className;
  5790. // Ensure the defaultValue is a function
  5791. if(typeof item.defaultValue === "function") {
  5792. item.defaultValue(el);
  5793. }
  5794. // Ensure the onUpdate is a function
  5795. if(typeof item.onUpdate === "function") {
  5796. // Create a closure around the span of the current action, then execute the onUpdate handler
  5797. this.codemirror.on("update", (function(el, item) {
  5798. return function() {
  5799. item.onUpdate(el);
  5800. };
  5801. }(el, item)));
  5802. }
  5803. // Append the item to the status bar
  5804. bar.appendChild(el);
  5805. }
  5806. // Insert the status bar into the DOM
  5807. var cmWrapper = this.codemirror.getWrapperElement();
  5808. cmWrapper.parentNode.insertBefore(bar, cmWrapper.nextSibling);
  5809. return bar;
  5810. };
  5811. /**
  5812. * Get or set the text content.
  5813. */
  5814. SimpleMDE.prototype.value = function(val) {
  5815. if(val === undefined) {
  5816. return this.codemirror.getValue();
  5817. } else {
  5818. this.codemirror.getDoc().setValue(val);
  5819. return this;
  5820. }
  5821. };
  5822. /**
  5823. * Bind static methods for exports.
  5824. */
  5825. SimpleMDE.toggleBold = toggleBold;
  5826. SimpleMDE.toggleItalic = toggleItalic;
  5827. SimpleMDE.toggleStrikethrough = toggleStrikethrough;
  5828. SimpleMDE.toggleBlockquote = toggleBlockquote;
  5829. SimpleMDE.toggleHeadingSmaller = toggleHeadingSmaller;
  5830. SimpleMDE.toggleHeadingBigger = toggleHeadingBigger;
  5831. SimpleMDE.toggleHeading1 = toggleHeading1;
  5832. SimpleMDE.toggleHeading2 = toggleHeading2;
  5833. SimpleMDE.toggleHeading3 = toggleHeading3;
  5834. SimpleMDE.toggleCodeBlock = toggleCodeBlock;
  5835. SimpleMDE.toggleUnorderedList = toggleUnorderedList;
  5836. SimpleMDE.toggleOrderedList = toggleOrderedList;
  5837. SimpleMDE.cleanBlock = cleanBlock;
  5838. SimpleMDE.drawLink = drawLink;
  5839. SimpleMDE.drawImage = drawImage;
  5840. SimpleMDE.drawTable = drawTable;
  5841. SimpleMDE.drawHorizontalRule = drawHorizontalRule;
  5842. SimpleMDE.undo = undo;
  5843. SimpleMDE.redo = redo;
  5844. SimpleMDE.togglePreview = togglePreview;
  5845. SimpleMDE.toggleSideBySide = toggleSideBySide;
  5846. SimpleMDE.toggleFullScreen = toggleFullScreen;
  5847. /**
  5848. * Bind instance methods for exports.
  5849. */
  5850. SimpleMDE.prototype.toggleBold = function() {
  5851. toggleBold(this);
  5852. };
  5853. SimpleMDE.prototype.toggleItalic = function() {
  5854. toggleItalic(this);
  5855. };
  5856. SimpleMDE.prototype.toggleStrikethrough = function() {
  5857. toggleStrikethrough(this);
  5858. };
  5859. SimpleMDE.prototype.toggleBlockquote = function() {
  5860. toggleBlockquote(this);
  5861. };
  5862. SimpleMDE.prototype.toggleHeadingSmaller = function() {
  5863. toggleHeadingSmaller(this);
  5864. };
  5865. SimpleMDE.prototype.toggleHeadingBigger = function() {
  5866. toggleHeadingBigger(this);
  5867. };
  5868. SimpleMDE.prototype.toggleHeading1 = function() {
  5869. toggleHeading1(this);
  5870. };
  5871. SimpleMDE.prototype.toggleHeading2 = function() {
  5872. toggleHeading2(this);
  5873. };
  5874. SimpleMDE.prototype.toggleHeading3 = function() {
  5875. toggleHeading3(this);
  5876. };
  5877. SimpleMDE.prototype.toggleCodeBlock = function() {
  5878. toggleCodeBlock(this);
  5879. };
  5880. SimpleMDE.prototype.toggleUnorderedList = function() {
  5881. toggleUnorderedList(this);
  5882. };
  5883. SimpleMDE.prototype.toggleOrderedList = function() {
  5884. toggleOrderedList(this);
  5885. };
  5886. SimpleMDE.prototype.cleanBlock = function() {
  5887. cleanBlock(this);
  5888. };
  5889. SimpleMDE.prototype.drawLink = function() {
  5890. drawLink(this);
  5891. };
  5892. SimpleMDE.prototype.drawImage = function() {
  5893. drawImage(this);
  5894. };
  5895. SimpleMDE.prototype.drawTable = function() {
  5896. drawTable(this);
  5897. };
  5898. SimpleMDE.prototype.drawHorizontalRule = function() {
  5899. drawHorizontalRule(this);
  5900. };
  5901. SimpleMDE.prototype.undo = function() {
  5902. undo(this);
  5903. };
  5904. SimpleMDE.prototype.redo = function() {
  5905. redo(this);
  5906. };
  5907. SimpleMDE.prototype.togglePreview = function() {
  5908. togglePreview(this);
  5909. };
  5910. SimpleMDE.prototype.toggleSideBySide = function() {
  5911. toggleSideBySide(this);
  5912. };
  5913. SimpleMDE.prototype.toggleFullScreen = function() {
  5914. toggleFullScreen(this);
  5915. };
  5916. SimpleMDE.prototype.isPreviewActive = function() {
  5917. var cm = this.codemirror;
  5918. var wrapper = cm.getWrapperElement();
  5919. var preview = wrapper.lastChild;
  5920. return /editor-preview-active/.test(preview.className);
  5921. };
  5922. SimpleMDE.prototype.isSideBySideActive = function() {
  5923. var cm = this.codemirror;
  5924. var wrapper = cm.getWrapperElement();
  5925. var preview = wrapper.nextSibling;
  5926. return /editor-preview-active-side/.test(preview.className);
  5927. };
  5928. SimpleMDE.prototype.isFullscreenActive = function() {
  5929. var cm = this.codemirror;
  5930. return cm.getOption("fullScreen");
  5931. };
  5932. SimpleMDE.prototype.getState = function() {
  5933. var cm = this.codemirror;
  5934. return getState(cm);
  5935. };
  5936. SimpleMDE.prototype.toTextArea = function() {
  5937. var cm = this.codemirror;
  5938. var wrapper = cm.getWrapperElement();
  5939. if(wrapper.parentNode) {
  5940. if(this.gui.toolbar) {
  5941. wrapper.parentNode.removeChild(this.gui.toolbar);
  5942. }
  5943. if(this.gui.statusbar) {
  5944. wrapper.parentNode.removeChild(this.gui.statusbar);
  5945. }
  5946. if(this.gui.sideBySide) {
  5947. wrapper.parentNode.removeChild(this.gui.sideBySide);
  5948. }
  5949. }
  5950. cm.toTextArea();
  5951. if(this.autosaveTimeoutId) {
  5952. clearTimeout(this.autosaveTimeoutId);
  5953. this.autosaveTimeoutId = undefined;
  5954. this.clearAutosavedValue();
  5955. }
  5956. };
  5957. module.exports = SimpleMDE;
  5958. /***/ }),
  5959. /* 40 */
  5960. /***/ (function(module, exports, __webpack_require__) {
  5961. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  5962. // Distributed under an MIT license: http://codemirror.net/LICENSE
  5963. // This is CodeMirror (http://codemirror.net), a code editor
  5964. // implemented in JavaScript on top of the browser's DOM.
  5965. //
  5966. // You can find some technical background for some of the code below
  5967. // at http://marijnhaverbeke.nl/blog/#cm-internals .
  5968. (function (global, factory) {
  5969. true ? module.exports = factory() :
  5970. typeof define === 'function' && define.amd ? define(factory) :
  5971. (global.CodeMirror = factory());
  5972. }(this, (function () { 'use strict';
  5973. // Kludges for bugs and behavior differences that can't be feature
  5974. // detected are enabled based on userAgent etc sniffing.
  5975. var userAgent = navigator.userAgent;
  5976. var platform = navigator.platform;
  5977. var gecko = /gecko\/\d/i.test(userAgent);
  5978. var ie_upto10 = /MSIE \d/.test(userAgent);
  5979. var ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(userAgent);
  5980. var edge = /Edge\/(\d+)/.exec(userAgent);
  5981. var ie = ie_upto10 || ie_11up || edge;
  5982. var ie_version = ie && (ie_upto10 ? document.documentMode || 6 : +(edge || ie_11up)[1]);
  5983. var webkit = !edge && /WebKit\//.test(userAgent);
  5984. var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(userAgent);
  5985. var chrome = !edge && /Chrome\//.test(userAgent);
  5986. var presto = /Opera\//.test(userAgent);
  5987. var safari = /Apple Computer/.test(navigator.vendor);
  5988. var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(userAgent);
  5989. var phantom = /PhantomJS/.test(userAgent);
  5990. var ios = !edge && /AppleWebKit/.test(userAgent) && /Mobile\/\w+/.test(userAgent);
  5991. var android = /Android/.test(userAgent);
  5992. // This is woefully incomplete. Suggestions for alternative methods welcome.
  5993. var mobile = ios || android || /webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(userAgent);
  5994. var mac = ios || /Mac/.test(platform);
  5995. var chromeOS = /\bCrOS\b/.test(userAgent);
  5996. var windows = /win/i.test(platform);
  5997. var presto_version = presto && userAgent.match(/Version\/(\d*\.\d*)/);
  5998. if (presto_version) { presto_version = Number(presto_version[1]); }
  5999. if (presto_version && presto_version >= 15) { presto = false; webkit = true; }
  6000. // Some browsers use the wrong event properties to signal cmd/ctrl on OS X
  6001. var flipCtrlCmd = mac && (qtwebkit || presto && (presto_version == null || presto_version < 12.11));
  6002. var captureRightClick = gecko || (ie && ie_version >= 9);
  6003. function classTest(cls) { return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*") }
  6004. var rmClass = function(node, cls) {
  6005. var current = node.className;
  6006. var match = classTest(cls).exec(current);
  6007. if (match) {
  6008. var after = current.slice(match.index + match[0].length);
  6009. node.className = current.slice(0, match.index) + (after ? match[1] + after : "");
  6010. }
  6011. };
  6012. function removeChildren(e) {
  6013. for (var count = e.childNodes.length; count > 0; --count)
  6014. { e.removeChild(e.firstChild); }
  6015. return e
  6016. }
  6017. function removeChildrenAndAdd(parent, e) {
  6018. return removeChildren(parent).appendChild(e)
  6019. }
  6020. function elt(tag, content, className, style) {
  6021. var e = document.createElement(tag);
  6022. if (className) { e.className = className; }
  6023. if (style) { e.style.cssText = style; }
  6024. if (typeof content == "string") { e.appendChild(document.createTextNode(content)); }
  6025. else if (content) { for (var i = 0; i < content.length; ++i) { e.appendChild(content[i]); } }
  6026. return e
  6027. }
  6028. // wrapper for elt, which removes the elt from the accessibility tree
  6029. function eltP(tag, content, className, style) {
  6030. var e = elt(tag, content, className, style);
  6031. e.setAttribute("role", "presentation");
  6032. return e
  6033. }
  6034. var range;
  6035. if (document.createRange) { range = function(node, start, end, endNode) {
  6036. var r = document.createRange();
  6037. r.setEnd(endNode || node, end);
  6038. r.setStart(node, start);
  6039. return r
  6040. }; }
  6041. else { range = function(node, start, end) {
  6042. var r = document.body.createTextRange();
  6043. try { r.moveToElementText(node.parentNode); }
  6044. catch(e) { return r }
  6045. r.collapse(true);
  6046. r.moveEnd("character", end);
  6047. r.moveStart("character", start);
  6048. return r
  6049. }; }
  6050. function contains(parent, child) {
  6051. if (child.nodeType == 3) // Android browser always returns false when child is a textnode
  6052. { child = child.parentNode; }
  6053. if (parent.contains)
  6054. { return parent.contains(child) }
  6055. do {
  6056. if (child.nodeType == 11) { child = child.host; }
  6057. if (child == parent) { return true }
  6058. } while (child = child.parentNode)
  6059. }
  6060. function activeElt() {
  6061. // IE and Edge may throw an "Unspecified Error" when accessing document.activeElement.
  6062. // IE < 10 will throw when accessed while the page is loading or in an iframe.
  6063. // IE > 9 and Edge will throw when accessed in an iframe if document.body is unavailable.
  6064. var activeElement;
  6065. try {
  6066. activeElement = document.activeElement;
  6067. } catch(e) {
  6068. activeElement = document.body || null;
  6069. }
  6070. while (activeElement && activeElement.shadowRoot && activeElement.shadowRoot.activeElement)
  6071. { activeElement = activeElement.shadowRoot.activeElement; }
  6072. return activeElement
  6073. }
  6074. function addClass(node, cls) {
  6075. var current = node.className;
  6076. if (!classTest(cls).test(current)) { node.className += (current ? " " : "") + cls; }
  6077. }
  6078. function joinClasses(a, b) {
  6079. var as = a.split(" ");
  6080. for (var i = 0; i < as.length; i++)
  6081. { if (as[i] && !classTest(as[i]).test(b)) { b += " " + as[i]; } }
  6082. return b
  6083. }
  6084. var selectInput = function(node) { node.select(); };
  6085. if (ios) // Mobile Safari apparently has a bug where select() is broken.
  6086. { selectInput = function(node) { node.selectionStart = 0; node.selectionEnd = node.value.length; }; }
  6087. else if (ie) // Suppress mysterious IE10 errors
  6088. { selectInput = function(node) { try { node.select(); } catch(_e) {} }; }
  6089. function bind(f) {
  6090. var args = Array.prototype.slice.call(arguments, 1);
  6091. return function(){return f.apply(null, args)}
  6092. }
  6093. function copyObj(obj, target, overwrite) {
  6094. if (!target) { target = {}; }
  6095. for (var prop in obj)
  6096. { if (obj.hasOwnProperty(prop) && (overwrite !== false || !target.hasOwnProperty(prop)))
  6097. { target[prop] = obj[prop]; } }
  6098. return target
  6099. }
  6100. // Counts the column offset in a string, taking tabs into account.
  6101. // Used mostly to find indentation.
  6102. function countColumn(string, end, tabSize, startIndex, startValue) {
  6103. if (end == null) {
  6104. end = string.search(/[^\s\u00a0]/);
  6105. if (end == -1) { end = string.length; }
  6106. }
  6107. for (var i = startIndex || 0, n = startValue || 0;;) {
  6108. var nextTab = string.indexOf("\t", i);
  6109. if (nextTab < 0 || nextTab >= end)
  6110. { return n + (end - i) }
  6111. n += nextTab - i;
  6112. n += tabSize - (n % tabSize);
  6113. i = nextTab + 1;
  6114. }
  6115. }
  6116. var Delayed = function() {this.id = null;};
  6117. Delayed.prototype.set = function (ms, f) {
  6118. clearTimeout(this.id);
  6119. this.id = setTimeout(f, ms);
  6120. };
  6121. function indexOf(array, elt) {
  6122. for (var i = 0; i < array.length; ++i)
  6123. { if (array[i] == elt) { return i } }
  6124. return -1
  6125. }
  6126. // Number of pixels added to scroller and sizer to hide scrollbar
  6127. var scrollerGap = 30;
  6128. // Returned or thrown by various protocols to signal 'I'm not
  6129. // handling this'.
  6130. var Pass = {toString: function(){return "CodeMirror.Pass"}};
  6131. // Reused option objects for setSelection & friends
  6132. var sel_dontScroll = {scroll: false};
  6133. var sel_mouse = {origin: "*mouse"};
  6134. var sel_move = {origin: "+move"};
  6135. // The inverse of countColumn -- find the offset that corresponds to
  6136. // a particular column.
  6137. function findColumn(string, goal, tabSize) {
  6138. for (var pos = 0, col = 0;;) {
  6139. var nextTab = string.indexOf("\t", pos);
  6140. if (nextTab == -1) { nextTab = string.length; }
  6141. var skipped = nextTab - pos;
  6142. if (nextTab == string.length || col + skipped >= goal)
  6143. { return pos + Math.min(skipped, goal - col) }
  6144. col += nextTab - pos;
  6145. col += tabSize - (col % tabSize);
  6146. pos = nextTab + 1;
  6147. if (col >= goal) { return pos }
  6148. }
  6149. }
  6150. var spaceStrs = [""];
  6151. function spaceStr(n) {
  6152. while (spaceStrs.length <= n)
  6153. { spaceStrs.push(lst(spaceStrs) + " "); }
  6154. return spaceStrs[n]
  6155. }
  6156. function lst(arr) { return arr[arr.length-1] }
  6157. function map(array, f) {
  6158. var out = [];
  6159. for (var i = 0; i < array.length; i++) { out[i] = f(array[i], i); }
  6160. return out
  6161. }
  6162. function insertSorted(array, value, score) {
  6163. var pos = 0, priority = score(value);
  6164. while (pos < array.length && score(array[pos]) <= priority) { pos++; }
  6165. array.splice(pos, 0, value);
  6166. }
  6167. function nothing() {}
  6168. function createObj(base, props) {
  6169. var inst;
  6170. if (Object.create) {
  6171. inst = Object.create(base);
  6172. } else {
  6173. nothing.prototype = base;
  6174. inst = new nothing();
  6175. }
  6176. if (props) { copyObj(props, inst); }
  6177. return inst
  6178. }
  6179. var nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;
  6180. function isWordCharBasic(ch) {
  6181. return /\w/.test(ch) || ch > "\x80" &&
  6182. (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch))
  6183. }
  6184. function isWordChar(ch, helper) {
  6185. if (!helper) { return isWordCharBasic(ch) }
  6186. if (helper.source.indexOf("\\w") > -1 && isWordCharBasic(ch)) { return true }
  6187. return helper.test(ch)
  6188. }
  6189. function isEmpty(obj) {
  6190. for (var n in obj) { if (obj.hasOwnProperty(n) && obj[n]) { return false } }
  6191. return true
  6192. }
  6193. // Extending unicode characters. A series of a non-extending char +
  6194. // any number of extending chars is treated as a single unit as far
  6195. // as editing and measuring is concerned. This is not fully correct,
  6196. // since some scripts/fonts/browsers also treat other configurations
  6197. // of code points as a group.
  6198. 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]/;
  6199. function isExtendingChar(ch) { return ch.charCodeAt(0) >= 768 && extendingChars.test(ch) }
  6200. // Returns a number from the range [`0`; `str.length`] unless `pos` is outside that range.
  6201. function skipExtendingChars(str, pos, dir) {
  6202. while ((dir < 0 ? pos > 0 : pos < str.length) && isExtendingChar(str.charAt(pos))) { pos += dir; }
  6203. return pos
  6204. }
  6205. // Returns the value from the range [`from`; `to`] that satisfies
  6206. // `pred` and is closest to `from`. Assumes that at least `to`
  6207. // satisfies `pred`. Supports `from` being greater than `to`.
  6208. function findFirst(pred, from, to) {
  6209. // At any point we are certain `to` satisfies `pred`, don't know
  6210. // whether `from` does.
  6211. var dir = from > to ? -1 : 1;
  6212. for (;;) {
  6213. if (from == to) { return from }
  6214. var midF = (from + to) / 2, mid = dir < 0 ? Math.ceil(midF) : Math.floor(midF);
  6215. if (mid == from) { return pred(mid) ? from : to }
  6216. if (pred(mid)) { to = mid; }
  6217. else { from = mid + dir; }
  6218. }
  6219. }
  6220. // The display handles the DOM integration, both for input reading
  6221. // and content drawing. It holds references to DOM nodes and
  6222. // display-related state.
  6223. function Display(place, doc, input) {
  6224. var d = this;
  6225. this.input = input;
  6226. // Covers bottom-right square when both scrollbars are present.
  6227. d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler");
  6228. d.scrollbarFiller.setAttribute("cm-not-content", "true");
  6229. // Covers bottom of gutter when coverGutterNextToScrollbar is on
  6230. // and h scrollbar is present.
  6231. d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler");
  6232. d.gutterFiller.setAttribute("cm-not-content", "true");
  6233. // Will contain the actual code, positioned to cover the viewport.
  6234. d.lineDiv = eltP("div", null, "CodeMirror-code");
  6235. // Elements are added to these to represent selection and cursors.
  6236. d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1");
  6237. d.cursorDiv = elt("div", null, "CodeMirror-cursors");
  6238. // A visibility: hidden element used to find the size of things.
  6239. d.measure = elt("div", null, "CodeMirror-measure");
  6240. // When lines outside of the viewport are measured, they are drawn in this.
  6241. d.lineMeasure = elt("div", null, "CodeMirror-measure");
  6242. // Wraps everything that needs to exist inside the vertically-padded coordinate system
  6243. d.lineSpace = eltP("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv],
  6244. null, "position: relative; outline: none");
  6245. var lines = eltP("div", [d.lineSpace], "CodeMirror-lines");
  6246. // Moved around its parent to cover visible view.
  6247. d.mover = elt("div", [lines], null, "position: relative");
  6248. // Set to the height of the document, allowing scrolling.
  6249. d.sizer = elt("div", [d.mover], "CodeMirror-sizer");
  6250. d.sizerWidth = null;
  6251. // Behavior of elts with overflow: auto and padding is
  6252. // inconsistent across browsers. This is used to ensure the
  6253. // scrollable area is big enough.
  6254. d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerGap + "px; width: 1px;");
  6255. // Will contain the gutters, if any.
  6256. d.gutters = elt("div", null, "CodeMirror-gutters");
  6257. d.lineGutter = null;
  6258. // Actual scrollable element.
  6259. d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll");
  6260. d.scroller.setAttribute("tabIndex", "-1");
  6261. // The element in which the editor lives.
  6262. d.wrapper = elt("div", [d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror");
  6263. // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported)
  6264. if (ie && ie_version < 8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; }
  6265. if (!webkit && !(gecko && mobile)) { d.scroller.draggable = true; }
  6266. if (place) {
  6267. if (place.appendChild) { place.appendChild(d.wrapper); }
  6268. else { place(d.wrapper); }
  6269. }
  6270. // Current rendered range (may be bigger than the view window).
  6271. d.viewFrom = d.viewTo = doc.first;
  6272. d.reportedViewFrom = d.reportedViewTo = doc.first;
  6273. // Information about the rendered lines.
  6274. d.view = [];
  6275. d.renderedView = null;
  6276. // Holds info about a single rendered line when it was rendered
  6277. // for measurement, while not in view.
  6278. d.externalMeasured = null;
  6279. // Empty space (in pixels) above the view
  6280. d.viewOffset = 0;
  6281. d.lastWrapHeight = d.lastWrapWidth = 0;
  6282. d.updateLineNumbers = null;
  6283. d.nativeBarWidth = d.barHeight = d.barWidth = 0;
  6284. d.scrollbarsClipped = false;
  6285. // Used to only resize the line number gutter when necessary (when
  6286. // the amount of lines crosses a boundary that makes its width change)
  6287. d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null;
  6288. // Set to true when a non-horizontal-scrolling line widget is
  6289. // added. As an optimization, line widget aligning is skipped when
  6290. // this is false.
  6291. d.alignWidgets = false;
  6292. d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
  6293. // Tracks the maximum line length so that the horizontal scrollbar
  6294. // can be kept static when scrolling.
  6295. d.maxLine = null;
  6296. d.maxLineLength = 0;
  6297. d.maxLineChanged = false;
  6298. // Used for measuring wheel scrolling granularity
  6299. d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null;
  6300. // True when shift is held down.
  6301. d.shift = false;
  6302. // Used to track whether anything happened since the context menu
  6303. // was opened.
  6304. d.selForContextMenu = null;
  6305. d.activeTouch = null;
  6306. input.init(d);
  6307. }
  6308. // Find the line object corresponding to the given line number.
  6309. function getLine(doc, n) {
  6310. n -= doc.first;
  6311. if (n < 0 || n >= doc.size) { throw new Error("There is no line " + (n + doc.first) + " in the document.") }
  6312. var chunk = doc;
  6313. while (!chunk.lines) {
  6314. for (var i = 0;; ++i) {
  6315. var child = chunk.children[i], sz = child.chunkSize();
  6316. if (n < sz) { chunk = child; break }
  6317. n -= sz;
  6318. }
  6319. }
  6320. return chunk.lines[n]
  6321. }
  6322. // Get the part of a document between two positions, as an array of
  6323. // strings.
  6324. function getBetween(doc, start, end) {
  6325. var out = [], n = start.line;
  6326. doc.iter(start.line, end.line + 1, function (line) {
  6327. var text = line.text;
  6328. if (n == end.line) { text = text.slice(0, end.ch); }
  6329. if (n == start.line) { text = text.slice(start.ch); }
  6330. out.push(text);
  6331. ++n;
  6332. });
  6333. return out
  6334. }
  6335. // Get the lines between from and to, as array of strings.
  6336. function getLines(doc, from, to) {
  6337. var out = [];
  6338. doc.iter(from, to, function (line) { out.push(line.text); }); // iter aborts when callback returns truthy value
  6339. return out
  6340. }
  6341. // Update the height of a line, propagating the height change
  6342. // upwards to parent nodes.
  6343. function updateLineHeight(line, height) {
  6344. var diff = height - line.height;
  6345. if (diff) { for (var n = line; n; n = n.parent) { n.height += diff; } }
  6346. }
  6347. // Given a line object, find its line number by walking up through
  6348. // its parent links.
  6349. function lineNo(line) {
  6350. if (line.parent == null) { return null }
  6351. var cur = line.parent, no = indexOf(cur.lines, line);
  6352. for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) {
  6353. for (var i = 0;; ++i) {
  6354. if (chunk.children[i] == cur) { break }
  6355. no += chunk.children[i].chunkSize();
  6356. }
  6357. }
  6358. return no + cur.first
  6359. }
  6360. // Find the line at the given vertical position, using the height
  6361. // information in the document tree.
  6362. function lineAtHeight(chunk, h) {
  6363. var n = chunk.first;
  6364. outer: do {
  6365. for (var i$1 = 0; i$1 < chunk.children.length; ++i$1) {
  6366. var child = chunk.children[i$1], ch = child.height;
  6367. if (h < ch) { chunk = child; continue outer }
  6368. h -= ch;
  6369. n += child.chunkSize();
  6370. }
  6371. return n
  6372. } while (!chunk.lines)
  6373. var i = 0;
  6374. for (; i < chunk.lines.length; ++i) {
  6375. var line = chunk.lines[i], lh = line.height;
  6376. if (h < lh) { break }
  6377. h -= lh;
  6378. }
  6379. return n + i
  6380. }
  6381. function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size}
  6382. function lineNumberFor(options, i) {
  6383. return String(options.lineNumberFormatter(i + options.firstLineNumber))
  6384. }
  6385. // A Pos instance represents a position within the text.
  6386. function Pos(line, ch, sticky) {
  6387. if ( sticky === void 0 ) sticky = null;
  6388. if (!(this instanceof Pos)) { return new Pos(line, ch, sticky) }
  6389. this.line = line;
  6390. this.ch = ch;
  6391. this.sticky = sticky;
  6392. }
  6393. // Compare two positions, return 0 if they are the same, a negative
  6394. // number when a is less, and a positive number otherwise.
  6395. function cmp(a, b) { return a.line - b.line || a.ch - b.ch }
  6396. function equalCursorPos(a, b) { return a.sticky == b.sticky && cmp(a, b) == 0 }
  6397. function copyPos(x) {return Pos(x.line, x.ch)}
  6398. function maxPos(a, b) { return cmp(a, b) < 0 ? b : a }
  6399. function minPos(a, b) { return cmp(a, b) < 0 ? a : b }
  6400. // Most of the external API clips given positions to make sure they
  6401. // actually exist within the document.
  6402. function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1))}
  6403. function clipPos(doc, pos) {
  6404. if (pos.line < doc.first) { return Pos(doc.first, 0) }
  6405. var last = doc.first + doc.size - 1;
  6406. if (pos.line > last) { return Pos(last, getLine(doc, last).text.length) }
  6407. return clipToLen(pos, getLine(doc, pos.line).text.length)
  6408. }
  6409. function clipToLen(pos, linelen) {
  6410. var ch = pos.ch;
  6411. if (ch == null || ch > linelen) { return Pos(pos.line, linelen) }
  6412. else if (ch < 0) { return Pos(pos.line, 0) }
  6413. else { return pos }
  6414. }
  6415. function clipPosArray(doc, array) {
  6416. var out = [];
  6417. for (var i = 0; i < array.length; i++) { out[i] = clipPos(doc, array[i]); }
  6418. return out
  6419. }
  6420. // Optimize some code when these features are not used.
  6421. var sawReadOnlySpans = false;
  6422. var sawCollapsedSpans = false;
  6423. function seeReadOnlySpans() {
  6424. sawReadOnlySpans = true;
  6425. }
  6426. function seeCollapsedSpans() {
  6427. sawCollapsedSpans = true;
  6428. }
  6429. // TEXTMARKER SPANS
  6430. function MarkedSpan(marker, from, to) {
  6431. this.marker = marker;
  6432. this.from = from; this.to = to;
  6433. }
  6434. // Search an array of spans for a span matching the given marker.
  6435. function getMarkedSpanFor(spans, marker) {
  6436. if (spans) { for (var i = 0; i < spans.length; ++i) {
  6437. var span = spans[i];
  6438. if (span.marker == marker) { return span }
  6439. } }
  6440. }
  6441. // Remove a span from an array, returning undefined if no spans are
  6442. // left (we don't store arrays for lines without spans).
  6443. function removeMarkedSpan(spans, span) {
  6444. var r;
  6445. for (var i = 0; i < spans.length; ++i)
  6446. { if (spans[i] != span) { (r || (r = [])).push(spans[i]); } }
  6447. return r
  6448. }
  6449. // Add a span to a line.
  6450. function addMarkedSpan(line, span) {
  6451. line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span];
  6452. span.marker.attachLine(line);
  6453. }
  6454. // Used for the algorithm that adjusts markers for a change in the
  6455. // document. These functions cut an array of spans at a given
  6456. // character position, returning an array of remaining chunks (or
  6457. // undefined if nothing remains).
  6458. function markedSpansBefore(old, startCh, isInsert) {
  6459. var nw;
  6460. if (old) { for (var i = 0; i < old.length; ++i) {
  6461. var span = old[i], marker = span.marker;
  6462. var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh);
  6463. if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) {
  6464. 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));
  6465. }
  6466. } }
  6467. return nw
  6468. }
  6469. function markedSpansAfter(old, endCh, isInsert) {
  6470. var nw;
  6471. if (old) { for (var i = 0; i < old.length; ++i) {
  6472. var span = old[i], marker = span.marker;
  6473. var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh);
  6474. if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) {
  6475. var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh);(nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh,
  6476. span.to == null ? null : span.to - endCh));
  6477. }
  6478. } }
  6479. return nw
  6480. }
  6481. // Given a change object, compute the new set of marker spans that
  6482. // cover the line in which the change took place. Removes spans
  6483. // entirely within the change, reconnects spans belonging to the
  6484. // same marker that appear on both sides of the change, and cuts off
  6485. // spans partially within the change. Returns an array of span
  6486. // arrays with one element for each line in (after) the change.
  6487. function stretchSpansOverChange(doc, change) {
  6488. if (change.full) { return null }
  6489. var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans;
  6490. var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans;
  6491. if (!oldFirst && !oldLast) { return null }
  6492. var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0;
  6493. // Get the spans that 'stick out' on both sides
  6494. var first = markedSpansBefore(oldFirst, startCh, isInsert);
  6495. var last = markedSpansAfter(oldLast, endCh, isInsert);
  6496. // Next, merge those two ends
  6497. var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0);
  6498. if (first) {
  6499. // Fix up .to properties of first
  6500. for (var i = 0; i < first.length; ++i) {
  6501. var span = first[i];
  6502. if (span.to == null) {
  6503. var found = getMarkedSpanFor(last, span.marker);
  6504. if (!found) { span.to = startCh; }
  6505. else if (sameLine) { span.to = found.to == null ? null : found.to + offset; }
  6506. }
  6507. }
  6508. }
  6509. if (last) {
  6510. // Fix up .from in last (or move them into first in case of sameLine)
  6511. for (var i$1 = 0; i$1 < last.length; ++i$1) {
  6512. var span$1 = last[i$1];
  6513. if (span$1.to != null) { span$1.to += offset; }
  6514. if (span$1.from == null) {
  6515. var found$1 = getMarkedSpanFor(first, span$1.marker);
  6516. if (!found$1) {
  6517. span$1.from = offset;
  6518. if (sameLine) { (first || (first = [])).push(span$1); }
  6519. }
  6520. } else {
  6521. span$1.from += offset;
  6522. if (sameLine) { (first || (first = [])).push(span$1); }
  6523. }
  6524. }
  6525. }
  6526. // Make sure we didn't create any zero-length spans
  6527. if (first) { first = clearEmptySpans(first); }
  6528. if (last && last != first) { last = clearEmptySpans(last); }
  6529. var newMarkers = [first];
  6530. if (!sameLine) {
  6531. // Fill gap with whole-line-spans
  6532. var gap = change.text.length - 2, gapMarkers;
  6533. if (gap > 0 && first)
  6534. { for (var i$2 = 0; i$2 < first.length; ++i$2)
  6535. { if (first[i$2].to == null)
  6536. { (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i$2].marker, null, null)); } } }
  6537. for (var i$3 = 0; i$3 < gap; ++i$3)
  6538. { newMarkers.push(gapMarkers); }
  6539. newMarkers.push(last);
  6540. }
  6541. return newMarkers
  6542. }
  6543. // Remove spans that are empty and don't have a clearWhenEmpty
  6544. // option of false.
  6545. function clearEmptySpans(spans) {
  6546. for (var i = 0; i < spans.length; ++i) {
  6547. var span = spans[i];
  6548. if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false)
  6549. { spans.splice(i--, 1); }
  6550. }
  6551. if (!spans.length) { return null }
  6552. return spans
  6553. }
  6554. // Used to 'clip' out readOnly ranges when making a change.
  6555. function removeReadOnlyRanges(doc, from, to) {
  6556. var markers = null;
  6557. doc.iter(from.line, to.line + 1, function (line) {
  6558. if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) {
  6559. var mark = line.markedSpans[i].marker;
  6560. if (mark.readOnly && (!markers || indexOf(markers, mark) == -1))
  6561. { (markers || (markers = [])).push(mark); }
  6562. } }
  6563. });
  6564. if (!markers) { return null }
  6565. var parts = [{from: from, to: to}];
  6566. for (var i = 0; i < markers.length; ++i) {
  6567. var mk = markers[i], m = mk.find(0);
  6568. for (var j = 0; j < parts.length; ++j) {
  6569. var p = parts[j];
  6570. if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) { continue }
  6571. var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to);
  6572. if (dfrom < 0 || !mk.inclusiveLeft && !dfrom)
  6573. { newParts.push({from: p.from, to: m.from}); }
  6574. if (dto > 0 || !mk.inclusiveRight && !dto)
  6575. { newParts.push({from: m.to, to: p.to}); }
  6576. parts.splice.apply(parts, newParts);
  6577. j += newParts.length - 3;
  6578. }
  6579. }
  6580. return parts
  6581. }
  6582. // Connect or disconnect spans from a line.
  6583. function detachMarkedSpans(line) {
  6584. var spans = line.markedSpans;
  6585. if (!spans) { return }
  6586. for (var i = 0; i < spans.length; ++i)
  6587. { spans[i].marker.detachLine(line); }
  6588. line.markedSpans = null;
  6589. }
  6590. function attachMarkedSpans(line, spans) {
  6591. if (!spans) { return }
  6592. for (var i = 0; i < spans.length; ++i)
  6593. { spans[i].marker.attachLine(line); }
  6594. line.markedSpans = spans;
  6595. }
  6596. // Helpers used when computing which overlapping collapsed span
  6597. // counts as the larger one.
  6598. function extraLeft(marker) { return marker.inclusiveLeft ? -1 : 0 }
  6599. function extraRight(marker) { return marker.inclusiveRight ? 1 : 0 }
  6600. // Returns a number indicating which of two overlapping collapsed
  6601. // spans is larger (and thus includes the other). Falls back to
  6602. // comparing ids when the spans cover exactly the same range.
  6603. function compareCollapsedMarkers(a, b) {
  6604. var lenDiff = a.lines.length - b.lines.length;
  6605. if (lenDiff != 0) { return lenDiff }
  6606. var aPos = a.find(), bPos = b.find();
  6607. var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b);
  6608. if (fromCmp) { return -fromCmp }
  6609. var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b);
  6610. if (toCmp) { return toCmp }
  6611. return b.id - a.id
  6612. }
  6613. // Find out whether a line ends or starts in a collapsed span. If
  6614. // so, return the marker for that span.
  6615. function collapsedSpanAtSide(line, start) {
  6616. var sps = sawCollapsedSpans && line.markedSpans, found;
  6617. if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) {
  6618. sp = sps[i];
  6619. if (sp.marker.collapsed && (start ? sp.from : sp.to) == null &&
  6620. (!found || compareCollapsedMarkers(found, sp.marker) < 0))
  6621. { found = sp.marker; }
  6622. } }
  6623. return found
  6624. }
  6625. function collapsedSpanAtStart(line) { return collapsedSpanAtSide(line, true) }
  6626. function collapsedSpanAtEnd(line) { return collapsedSpanAtSide(line, false) }
  6627. // Test whether there exists a collapsed span that partially
  6628. // overlaps (covers the start or end, but not both) of a new span.
  6629. // Such overlap is not allowed.
  6630. function conflictingCollapsedRange(doc, lineNo$$1, from, to, marker) {
  6631. var line = getLine(doc, lineNo$$1);
  6632. var sps = sawCollapsedSpans && line.markedSpans;
  6633. if (sps) { for (var i = 0; i < sps.length; ++i) {
  6634. var sp = sps[i];
  6635. if (!sp.marker.collapsed) { continue }
  6636. var found = sp.marker.find(0);
  6637. var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker);
  6638. var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker);
  6639. if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) { continue }
  6640. if (fromCmp <= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.to, from) >= 0 : cmp(found.to, from) > 0) ||
  6641. fromCmp >= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.from, to) <= 0 : cmp(found.from, to) < 0))
  6642. { return true }
  6643. } }
  6644. }
  6645. // A visual line is a line as drawn on the screen. Folding, for
  6646. // example, can cause multiple logical lines to appear on the same
  6647. // visual line. This finds the start of the visual line that the
  6648. // given line is part of (usually that is the line itself).
  6649. function visualLine(line) {
  6650. var merged;
  6651. while (merged = collapsedSpanAtStart(line))
  6652. { line = merged.find(-1, true).line; }
  6653. return line
  6654. }
  6655. function visualLineEnd(line) {
  6656. var merged;
  6657. while (merged = collapsedSpanAtEnd(line))
  6658. { line = merged.find(1, true).line; }
  6659. return line
  6660. }
  6661. // Returns an array of logical lines that continue the visual line
  6662. // started by the argument, or undefined if there are no such lines.
  6663. function visualLineContinued(line) {
  6664. var merged, lines;
  6665. while (merged = collapsedSpanAtEnd(line)) {
  6666. line = merged.find(1, true).line
  6667. ;(lines || (lines = [])).push(line);
  6668. }
  6669. return lines
  6670. }
  6671. // Get the line number of the start of the visual line that the
  6672. // given line number is part of.
  6673. function visualLineNo(doc, lineN) {
  6674. var line = getLine(doc, lineN), vis = visualLine(line);
  6675. if (line == vis) { return lineN }
  6676. return lineNo(vis)
  6677. }
  6678. // Get the line number of the start of the next visual line after
  6679. // the given line.
  6680. function visualLineEndNo(doc, lineN) {
  6681. if (lineN > doc.lastLine()) { return lineN }
  6682. var line = getLine(doc, lineN), merged;
  6683. if (!lineIsHidden(doc, line)) { return lineN }
  6684. while (merged = collapsedSpanAtEnd(line))
  6685. { line = merged.find(1, true).line; }
  6686. return lineNo(line) + 1
  6687. }
  6688. // Compute whether a line is hidden. Lines count as hidden when they
  6689. // are part of a visual line that starts with another line, or when
  6690. // they are entirely covered by collapsed, non-widget span.
  6691. function lineIsHidden(doc, line) {
  6692. var sps = sawCollapsedSpans && line.markedSpans;
  6693. if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) {
  6694. sp = sps[i];
  6695. if (!sp.marker.collapsed) { continue }
  6696. if (sp.from == null) { return true }
  6697. if (sp.marker.widgetNode) { continue }
  6698. if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp))
  6699. { return true }
  6700. } }
  6701. }
  6702. function lineIsHiddenInner(doc, line, span) {
  6703. if (span.to == null) {
  6704. var end = span.marker.find(1, true);
  6705. return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker))
  6706. }
  6707. if (span.marker.inclusiveRight && span.to == line.text.length)
  6708. { return true }
  6709. for (var sp = (void 0), i = 0; i < line.markedSpans.length; ++i) {
  6710. sp = line.markedSpans[i];
  6711. if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to &&
  6712. (sp.to == null || sp.to != span.from) &&
  6713. (sp.marker.inclusiveLeft || span.marker.inclusiveRight) &&
  6714. lineIsHiddenInner(doc, line, sp)) { return true }
  6715. }
  6716. }
  6717. // Find the height above the given line.
  6718. function heightAtLine(lineObj) {
  6719. lineObj = visualLine(lineObj);
  6720. var h = 0, chunk = lineObj.parent;
  6721. for (var i = 0; i < chunk.lines.length; ++i) {
  6722. var line = chunk.lines[i];
  6723. if (line == lineObj) { break }
  6724. else { h += line.height; }
  6725. }
  6726. for (var p = chunk.parent; p; chunk = p, p = chunk.parent) {
  6727. for (var i$1 = 0; i$1 < p.children.length; ++i$1) {
  6728. var cur = p.children[i$1];
  6729. if (cur == chunk) { break }
  6730. else { h += cur.height; }
  6731. }
  6732. }
  6733. return h
  6734. }
  6735. // Compute the character length of a line, taking into account
  6736. // collapsed ranges (see markText) that might hide parts, and join
  6737. // other lines onto it.
  6738. function lineLength(line) {
  6739. if (line.height == 0) { return 0 }
  6740. var len = line.text.length, merged, cur = line;
  6741. while (merged = collapsedSpanAtStart(cur)) {
  6742. var found = merged.find(0, true);
  6743. cur = found.from.line;
  6744. len += found.from.ch - found.to.ch;
  6745. }
  6746. cur = line;
  6747. while (merged = collapsedSpanAtEnd(cur)) {
  6748. var found$1 = merged.find(0, true);
  6749. len -= cur.text.length - found$1.from.ch;
  6750. cur = found$1.to.line;
  6751. len += cur.text.length - found$1.to.ch;
  6752. }
  6753. return len
  6754. }
  6755. // Find the longest line in the document.
  6756. function findMaxLine(cm) {
  6757. var d = cm.display, doc = cm.doc;
  6758. d.maxLine = getLine(doc, doc.first);
  6759. d.maxLineLength = lineLength(d.maxLine);
  6760. d.maxLineChanged = true;
  6761. doc.iter(function (line) {
  6762. var len = lineLength(line);
  6763. if (len > d.maxLineLength) {
  6764. d.maxLineLength = len;
  6765. d.maxLine = line;
  6766. }
  6767. });
  6768. }
  6769. // BIDI HELPERS
  6770. function iterateBidiSections(order, from, to, f) {
  6771. if (!order) { return f(from, to, "ltr", 0) }
  6772. var found = false;
  6773. for (var i = 0; i < order.length; ++i) {
  6774. var part = order[i];
  6775. if (part.from < to && part.to > from || from == to && part.to == from) {
  6776. f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr", i);
  6777. found = true;
  6778. }
  6779. }
  6780. if (!found) { f(from, to, "ltr"); }
  6781. }
  6782. var bidiOther = null;
  6783. function getBidiPartAt(order, ch, sticky) {
  6784. var found;
  6785. bidiOther = null;
  6786. for (var i = 0; i < order.length; ++i) {
  6787. var cur = order[i];
  6788. if (cur.from < ch && cur.to > ch) { return i }
  6789. if (cur.to == ch) {
  6790. if (cur.from != cur.to && sticky == "before") { found = i; }
  6791. else { bidiOther = i; }
  6792. }
  6793. if (cur.from == ch) {
  6794. if (cur.from != cur.to && sticky != "before") { found = i; }
  6795. else { bidiOther = i; }
  6796. }
  6797. }
  6798. return found != null ? found : bidiOther
  6799. }
  6800. // Bidirectional ordering algorithm
  6801. // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm
  6802. // that this (partially) implements.
  6803. // One-char codes used for character types:
  6804. // L (L): Left-to-Right
  6805. // R (R): Right-to-Left
  6806. // r (AL): Right-to-Left Arabic
  6807. // 1 (EN): European Number
  6808. // + (ES): European Number Separator
  6809. // % (ET): European Number Terminator
  6810. // n (AN): Arabic Number
  6811. // , (CS): Common Number Separator
  6812. // m (NSM): Non-Spacing Mark
  6813. // b (BN): Boundary Neutral
  6814. // s (B): Paragraph Separator
  6815. // t (S): Segment Separator
  6816. // w (WS): Whitespace
  6817. // N (ON): Other Neutrals
  6818. // Returns null if characters are ordered as they appear
  6819. // (left-to-right), or an array of sections ({from, to, level}
  6820. // objects) in the order in which they occur visually.
  6821. var bidiOrdering = (function() {
  6822. // Character types for codepoints 0 to 0xff
  6823. var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN";
  6824. // Character types for codepoints 0x600 to 0x6f9
  6825. var arabicTypes = "nnnnnnNNr%%r,rNNmmmmmmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmmmnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmnNmmmmmmrrmmNmmmmrr1111111111";
  6826. function charType(code) {
  6827. if (code <= 0xf7) { return lowTypes.charAt(code) }
  6828. else if (0x590 <= code && code <= 0x5f4) { return "R" }
  6829. else if (0x600 <= code && code <= 0x6f9) { return arabicTypes.charAt(code - 0x600) }
  6830. else if (0x6ee <= code && code <= 0x8ac) { return "r" }
  6831. else if (0x2000 <= code && code <= 0x200b) { return "w" }
  6832. else if (code == 0x200c) { return "b" }
  6833. else { return "L" }
  6834. }
  6835. var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/;
  6836. var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/;
  6837. function BidiSpan(level, from, to) {
  6838. this.level = level;
  6839. this.from = from; this.to = to;
  6840. }
  6841. return function(str, direction) {
  6842. var outerType = direction == "ltr" ? "L" : "R";
  6843. if (str.length == 0 || direction == "ltr" && !bidiRE.test(str)) { return false }
  6844. var len = str.length, types = [];
  6845. for (var i = 0; i < len; ++i)
  6846. { types.push(charType(str.charCodeAt(i))); }
  6847. // W1. Examine each non-spacing mark (NSM) in the level run, and
  6848. // change the type of the NSM to the type of the previous
  6849. // character. If the NSM is at the start of the level run, it will
  6850. // get the type of sor.
  6851. for (var i$1 = 0, prev = outerType; i$1 < len; ++i$1) {
  6852. var type = types[i$1];
  6853. if (type == "m") { types[i$1] = prev; }
  6854. else { prev = type; }
  6855. }
  6856. // W2. Search backwards from each instance of a European number
  6857. // until the first strong type (R, L, AL, or sor) is found. If an
  6858. // AL is found, change the type of the European number to Arabic
  6859. // number.
  6860. // W3. Change all ALs to R.
  6861. for (var i$2 = 0, cur = outerType; i$2 < len; ++i$2) {
  6862. var type$1 = types[i$2];
  6863. if (type$1 == "1" && cur == "r") { types[i$2] = "n"; }
  6864. else if (isStrong.test(type$1)) { cur = type$1; if (type$1 == "r") { types[i$2] = "R"; } }
  6865. }
  6866. // W4. A single European separator between two European numbers
  6867. // changes to a European number. A single common separator between
  6868. // two numbers of the same type changes to that type.
  6869. for (var i$3 = 1, prev$1 = types[0]; i$3 < len - 1; ++i$3) {
  6870. var type$2 = types[i$3];
  6871. if (type$2 == "+" && prev$1 == "1" && types[i$3+1] == "1") { types[i$3] = "1"; }
  6872. else if (type$2 == "," && prev$1 == types[i$3+1] &&
  6873. (prev$1 == "1" || prev$1 == "n")) { types[i$3] = prev$1; }
  6874. prev$1 = type$2;
  6875. }
  6876. // W5. A sequence of European terminators adjacent to European
  6877. // numbers changes to all European numbers.
  6878. // W6. Otherwise, separators and terminators change to Other
  6879. // Neutral.
  6880. for (var i$4 = 0; i$4 < len; ++i$4) {
  6881. var type$3 = types[i$4];
  6882. if (type$3 == ",") { types[i$4] = "N"; }
  6883. else if (type$3 == "%") {
  6884. var end = (void 0);
  6885. for (end = i$4 + 1; end < len && types[end] == "%"; ++end) {}
  6886. var replace = (i$4 && types[i$4-1] == "!") || (end < len && types[end] == "1") ? "1" : "N";
  6887. for (var j = i$4; j < end; ++j) { types[j] = replace; }
  6888. i$4 = end - 1;
  6889. }
  6890. }
  6891. // W7. Search backwards from each instance of a European number
  6892. // until the first strong type (R, L, or sor) is found. If an L is
  6893. // found, then change the type of the European number to L.
  6894. for (var i$5 = 0, cur$1 = outerType; i$5 < len; ++i$5) {
  6895. var type$4 = types[i$5];
  6896. if (cur$1 == "L" && type$4 == "1") { types[i$5] = "L"; }
  6897. else if (isStrong.test(type$4)) { cur$1 = type$4; }
  6898. }
  6899. // N1. A sequence of neutrals takes the direction of the
  6900. // surrounding strong text if the text on both sides has the same
  6901. // direction. European and Arabic numbers act as if they were R in
  6902. // terms of their influence on neutrals. Start-of-level-run (sor)
  6903. // and end-of-level-run (eor) are used at level run boundaries.
  6904. // N2. Any remaining neutrals take the embedding direction.
  6905. for (var i$6 = 0; i$6 < len; ++i$6) {
  6906. if (isNeutral.test(types[i$6])) {
  6907. var end$1 = (void 0);
  6908. for (end$1 = i$6 + 1; end$1 < len && isNeutral.test(types[end$1]); ++end$1) {}
  6909. var before = (i$6 ? types[i$6-1] : outerType) == "L";
  6910. var after = (end$1 < len ? types[end$1] : outerType) == "L";
  6911. var replace$1 = before == after ? (before ? "L" : "R") : outerType;
  6912. for (var j$1 = i$6; j$1 < end$1; ++j$1) { types[j$1] = replace$1; }
  6913. i$6 = end$1 - 1;
  6914. }
  6915. }
  6916. // Here we depart from the documented algorithm, in order to avoid
  6917. // building up an actual levels array. Since there are only three
  6918. // levels (0, 1, 2) in an implementation that doesn't take
  6919. // explicit embedding into account, we can build up the order on
  6920. // the fly, without following the level-based algorithm.
  6921. var order = [], m;
  6922. for (var i$7 = 0; i$7 < len;) {
  6923. if (countsAsLeft.test(types[i$7])) {
  6924. var start = i$7;
  6925. for (++i$7; i$7 < len && countsAsLeft.test(types[i$7]); ++i$7) {}
  6926. order.push(new BidiSpan(0, start, i$7));
  6927. } else {
  6928. var pos = i$7, at = order.length;
  6929. for (++i$7; i$7 < len && types[i$7] != "L"; ++i$7) {}
  6930. for (var j$2 = pos; j$2 < i$7;) {
  6931. if (countsAsNum.test(types[j$2])) {
  6932. if (pos < j$2) { order.splice(at, 0, new BidiSpan(1, pos, j$2)); }
  6933. var nstart = j$2;
  6934. for (++j$2; j$2 < i$7 && countsAsNum.test(types[j$2]); ++j$2) {}
  6935. order.splice(at, 0, new BidiSpan(2, nstart, j$2));
  6936. pos = j$2;
  6937. } else { ++j$2; }
  6938. }
  6939. if (pos < i$7) { order.splice(at, 0, new BidiSpan(1, pos, i$7)); }
  6940. }
  6941. }
  6942. if (direction == "ltr") {
  6943. if (order[0].level == 1 && (m = str.match(/^\s+/))) {
  6944. order[0].from = m[0].length;
  6945. order.unshift(new BidiSpan(0, 0, m[0].length));
  6946. }
  6947. if (lst(order).level == 1 && (m = str.match(/\s+$/))) {
  6948. lst(order).to -= m[0].length;
  6949. order.push(new BidiSpan(0, len - m[0].length, len));
  6950. }
  6951. }
  6952. return direction == "rtl" ? order.reverse() : order
  6953. }
  6954. })();
  6955. // Get the bidi ordering for the given line (and cache it). Returns
  6956. // false for lines that are fully left-to-right, and an array of
  6957. // BidiSpan objects otherwise.
  6958. function getOrder(line, direction) {
  6959. var order = line.order;
  6960. if (order == null) { order = line.order = bidiOrdering(line.text, direction); }
  6961. return order
  6962. }
  6963. // EVENT HANDLING
  6964. // Lightweight event framework. on/off also work on DOM nodes,
  6965. // registering native DOM handlers.
  6966. var noHandlers = [];
  6967. var on = function(emitter, type, f) {
  6968. if (emitter.addEventListener) {
  6969. emitter.addEventListener(type, f, false);
  6970. } else if (emitter.attachEvent) {
  6971. emitter.attachEvent("on" + type, f);
  6972. } else {
  6973. var map$$1 = emitter._handlers || (emitter._handlers = {});
  6974. map$$1[type] = (map$$1[type] || noHandlers).concat(f);
  6975. }
  6976. };
  6977. function getHandlers(emitter, type) {
  6978. return emitter._handlers && emitter._handlers[type] || noHandlers
  6979. }
  6980. function off(emitter, type, f) {
  6981. if (emitter.removeEventListener) {
  6982. emitter.removeEventListener(type, f, false);
  6983. } else if (emitter.detachEvent) {
  6984. emitter.detachEvent("on" + type, f);
  6985. } else {
  6986. var map$$1 = emitter._handlers, arr = map$$1 && map$$1[type];
  6987. if (arr) {
  6988. var index = indexOf(arr, f);
  6989. if (index > -1)
  6990. { map$$1[type] = arr.slice(0, index).concat(arr.slice(index + 1)); }
  6991. }
  6992. }
  6993. }
  6994. function signal(emitter, type /*, values...*/) {
  6995. var handlers = getHandlers(emitter, type);
  6996. if (!handlers.length) { return }
  6997. var args = Array.prototype.slice.call(arguments, 2);
  6998. for (var i = 0; i < handlers.length; ++i) { handlers[i].apply(null, args); }
  6999. }
  7000. // The DOM events that CodeMirror handles can be overridden by
  7001. // registering a (non-DOM) handler on the editor for the event name,
  7002. // and preventDefault-ing the event in that handler.
  7003. function signalDOMEvent(cm, e, override) {
  7004. if (typeof e == "string")
  7005. { e = {type: e, preventDefault: function() { this.defaultPrevented = true; }}; }
  7006. signal(cm, override || e.type, cm, e);
  7007. return e_defaultPrevented(e) || e.codemirrorIgnore
  7008. }
  7009. function signalCursorActivity(cm) {
  7010. var arr = cm._handlers && cm._handlers.cursorActivity;
  7011. if (!arr) { return }
  7012. var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = []);
  7013. for (var i = 0; i < arr.length; ++i) { if (indexOf(set, arr[i]) == -1)
  7014. { set.push(arr[i]); } }
  7015. }
  7016. function hasHandler(emitter, type) {
  7017. return getHandlers(emitter, type).length > 0
  7018. }
  7019. // Add on and off methods to a constructor's prototype, to make
  7020. // registering events on such objects more convenient.
  7021. function eventMixin(ctor) {
  7022. ctor.prototype.on = function(type, f) {on(this, type, f);};
  7023. ctor.prototype.off = function(type, f) {off(this, type, f);};
  7024. }
  7025. // Due to the fact that we still support jurassic IE versions, some
  7026. // compatibility wrappers are needed.
  7027. function e_preventDefault(e) {
  7028. if (e.preventDefault) { e.preventDefault(); }
  7029. else { e.returnValue = false; }
  7030. }
  7031. function e_stopPropagation(e) {
  7032. if (e.stopPropagation) { e.stopPropagation(); }
  7033. else { e.cancelBubble = true; }
  7034. }
  7035. function e_defaultPrevented(e) {
  7036. return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false
  7037. }
  7038. function e_stop(e) {e_preventDefault(e); e_stopPropagation(e);}
  7039. function e_target(e) {return e.target || e.srcElement}
  7040. function e_button(e) {
  7041. var b = e.which;
  7042. if (b == null) {
  7043. if (e.button & 1) { b = 1; }
  7044. else if (e.button & 2) { b = 3; }
  7045. else if (e.button & 4) { b = 2; }
  7046. }
  7047. if (mac && e.ctrlKey && b == 1) { b = 3; }
  7048. return b
  7049. }
  7050. // Detect drag-and-drop
  7051. var dragAndDrop = function() {
  7052. // There is *some* kind of drag-and-drop support in IE6-8, but I
  7053. // couldn't get it to work yet.
  7054. if (ie && ie_version < 9) { return false }
  7055. var div = elt('div');
  7056. return "draggable" in div || "dragDrop" in div
  7057. }();
  7058. var zwspSupported;
  7059. function zeroWidthElement(measure) {
  7060. if (zwspSupported == null) {
  7061. var test = elt("span", "\u200b");
  7062. removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")]));
  7063. if (measure.firstChild.offsetHeight != 0)
  7064. { zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8); }
  7065. }
  7066. var node = zwspSupported ? elt("span", "\u200b") :
  7067. elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px");
  7068. node.setAttribute("cm-text", "");
  7069. return node
  7070. }
  7071. // Feature-detect IE's crummy client rect reporting for bidi text
  7072. var badBidiRects;
  7073. function hasBadBidiRects(measure) {
  7074. if (badBidiRects != null) { return badBidiRects }
  7075. var txt = removeChildrenAndAdd(measure, document.createTextNode("A\u062eA"));
  7076. var r0 = range(txt, 0, 1).getBoundingClientRect();
  7077. var r1 = range(txt, 1, 2).getBoundingClientRect();
  7078. removeChildren(measure);
  7079. if (!r0 || r0.left == r0.right) { return false } // Safari returns null in some cases (#2780)
  7080. return badBidiRects = (r1.right - r0.right < 3)
  7081. }
  7082. // See if "".split is the broken IE version, if so, provide an
  7083. // alternative way to split lines.
  7084. var splitLinesAuto = "\n\nb".split(/\n/).length != 3 ? function (string) {
  7085. var pos = 0, result = [], l = string.length;
  7086. while (pos <= l) {
  7087. var nl = string.indexOf("\n", pos);
  7088. if (nl == -1) { nl = string.length; }
  7089. var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl);
  7090. var rt = line.indexOf("\r");
  7091. if (rt != -1) {
  7092. result.push(line.slice(0, rt));
  7093. pos += rt + 1;
  7094. } else {
  7095. result.push(line);
  7096. pos = nl + 1;
  7097. }
  7098. }
  7099. return result
  7100. } : function (string) { return string.split(/\r\n?|\n/); };
  7101. var hasSelection = window.getSelection ? function (te) {
  7102. try { return te.selectionStart != te.selectionEnd }
  7103. catch(e) { return false }
  7104. } : function (te) {
  7105. var range$$1;
  7106. try {range$$1 = te.ownerDocument.selection.createRange();}
  7107. catch(e) {}
  7108. if (!range$$1 || range$$1.parentElement() != te) { return false }
  7109. return range$$1.compareEndPoints("StartToEnd", range$$1) != 0
  7110. };
  7111. var hasCopyEvent = (function () {
  7112. var e = elt("div");
  7113. if ("oncopy" in e) { return true }
  7114. e.setAttribute("oncopy", "return;");
  7115. return typeof e.oncopy == "function"
  7116. })();
  7117. var badZoomedRects = null;
  7118. function hasBadZoomedRects(measure) {
  7119. if (badZoomedRects != null) { return badZoomedRects }
  7120. var node = removeChildrenAndAdd(measure, elt("span", "x"));
  7121. var normal = node.getBoundingClientRect();
  7122. var fromRange = range(node, 0, 1).getBoundingClientRect();
  7123. return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1
  7124. }
  7125. // Known modes, by name and by MIME
  7126. var modes = {};
  7127. var mimeModes = {};
  7128. // Extra arguments are stored as the mode's dependencies, which is
  7129. // used by (legacy) mechanisms like loadmode.js to automatically
  7130. // load a mode. (Preferred mechanism is the require/define calls.)
  7131. function defineMode(name, mode) {
  7132. if (arguments.length > 2)
  7133. { mode.dependencies = Array.prototype.slice.call(arguments, 2); }
  7134. modes[name] = mode;
  7135. }
  7136. function defineMIME(mime, spec) {
  7137. mimeModes[mime] = spec;
  7138. }
  7139. // Given a MIME type, a {name, ...options} config object, or a name
  7140. // string, return a mode config object.
  7141. function resolveMode(spec) {
  7142. if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) {
  7143. spec = mimeModes[spec];
  7144. } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) {
  7145. var found = mimeModes[spec.name];
  7146. if (typeof found == "string") { found = {name: found}; }
  7147. spec = createObj(found, spec);
  7148. spec.name = found.name;
  7149. } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) {
  7150. return resolveMode("application/xml")
  7151. } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+json$/.test(spec)) {
  7152. return resolveMode("application/json")
  7153. }
  7154. if (typeof spec == "string") { return {name: spec} }
  7155. else { return spec || {name: "null"} }
  7156. }
  7157. // Given a mode spec (anything that resolveMode accepts), find and
  7158. // initialize an actual mode object.
  7159. function getMode(options, spec) {
  7160. spec = resolveMode(spec);
  7161. var mfactory = modes[spec.name];
  7162. if (!mfactory) { return getMode(options, "text/plain") }
  7163. var modeObj = mfactory(options, spec);
  7164. if (modeExtensions.hasOwnProperty(spec.name)) {
  7165. var exts = modeExtensions[spec.name];
  7166. for (var prop in exts) {
  7167. if (!exts.hasOwnProperty(prop)) { continue }
  7168. if (modeObj.hasOwnProperty(prop)) { modeObj["_" + prop] = modeObj[prop]; }
  7169. modeObj[prop] = exts[prop];
  7170. }
  7171. }
  7172. modeObj.name = spec.name;
  7173. if (spec.helperType) { modeObj.helperType = spec.helperType; }
  7174. if (spec.modeProps) { for (var prop$1 in spec.modeProps)
  7175. { modeObj[prop$1] = spec.modeProps[prop$1]; } }
  7176. return modeObj
  7177. }
  7178. // This can be used to attach properties to mode objects from
  7179. // outside the actual mode definition.
  7180. var modeExtensions = {};
  7181. function extendMode(mode, properties) {
  7182. var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {});
  7183. copyObj(properties, exts);
  7184. }
  7185. function copyState(mode, state) {
  7186. if (state === true) { return state }
  7187. if (mode.copyState) { return mode.copyState(state) }
  7188. var nstate = {};
  7189. for (var n in state) {
  7190. var val = state[n];
  7191. if (val instanceof Array) { val = val.concat([]); }
  7192. nstate[n] = val;
  7193. }
  7194. return nstate
  7195. }
  7196. // Given a mode and a state (for that mode), find the inner mode and
  7197. // state at the position that the state refers to.
  7198. function innerMode(mode, state) {
  7199. var info;
  7200. while (mode.innerMode) {
  7201. info = mode.innerMode(state);
  7202. if (!info || info.mode == mode) { break }
  7203. state = info.state;
  7204. mode = info.mode;
  7205. }
  7206. return info || {mode: mode, state: state}
  7207. }
  7208. function startState(mode, a1, a2) {
  7209. return mode.startState ? mode.startState(a1, a2) : true
  7210. }
  7211. // STRING STREAM
  7212. // Fed to the mode parsers, provides helper functions to make
  7213. // parsers more succinct.
  7214. var StringStream = function(string, tabSize, lineOracle) {
  7215. this.pos = this.start = 0;
  7216. this.string = string;
  7217. this.tabSize = tabSize || 8;
  7218. this.lastColumnPos = this.lastColumnValue = 0;
  7219. this.lineStart = 0;
  7220. this.lineOracle = lineOracle;
  7221. };
  7222. StringStream.prototype.eol = function () {return this.pos >= this.string.length};
  7223. StringStream.prototype.sol = function () {return this.pos == this.lineStart};
  7224. StringStream.prototype.peek = function () {return this.string.charAt(this.pos) || undefined};
  7225. StringStream.prototype.next = function () {
  7226. if (this.pos < this.string.length)
  7227. { return this.string.charAt(this.pos++) }
  7228. };
  7229. StringStream.prototype.eat = function (match) {
  7230. var ch = this.string.charAt(this.pos);
  7231. var ok;
  7232. if (typeof match == "string") { ok = ch == match; }
  7233. else { ok = ch && (match.test ? match.test(ch) : match(ch)); }
  7234. if (ok) {++this.pos; return ch}
  7235. };
  7236. StringStream.prototype.eatWhile = function (match) {
  7237. var start = this.pos;
  7238. while (this.eat(match)){}
  7239. return this.pos > start
  7240. };
  7241. StringStream.prototype.eatSpace = function () {
  7242. var this$1 = this;
  7243. var start = this.pos;
  7244. while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) { ++this$1.pos; }
  7245. return this.pos > start
  7246. };
  7247. StringStream.prototype.skipToEnd = function () {this.pos = this.string.length;};
  7248. StringStream.prototype.skipTo = function (ch) {
  7249. var found = this.string.indexOf(ch, this.pos);
  7250. if (found > -1) {this.pos = found; return true}
  7251. };
  7252. StringStream.prototype.backUp = function (n) {this.pos -= n;};
  7253. StringStream.prototype.column = function () {
  7254. if (this.lastColumnPos < this.start) {
  7255. this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue);
  7256. this.lastColumnPos = this.start;
  7257. }
  7258. return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0)
  7259. };
  7260. StringStream.prototype.indentation = function () {
  7261. return countColumn(this.string, null, this.tabSize) -
  7262. (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0)
  7263. };
  7264. StringStream.prototype.match = function (pattern, consume, caseInsensitive) {
  7265. if (typeof pattern == "string") {
  7266. var cased = function (str) { return caseInsensitive ? str.toLowerCase() : str; };
  7267. var substr = this.string.substr(this.pos, pattern.length);
  7268. if (cased(substr) == cased(pattern)) {
  7269. if (consume !== false) { this.pos += pattern.length; }
  7270. return true
  7271. }
  7272. } else {
  7273. var match = this.string.slice(this.pos).match(pattern);
  7274. if (match && match.index > 0) { return null }
  7275. if (match && consume !== false) { this.pos += match[0].length; }
  7276. return match
  7277. }
  7278. };
  7279. StringStream.prototype.current = function (){return this.string.slice(this.start, this.pos)};
  7280. StringStream.prototype.hideFirstChars = function (n, inner) {
  7281. this.lineStart += n;
  7282. try { return inner() }
  7283. finally { this.lineStart -= n; }
  7284. };
  7285. StringStream.prototype.lookAhead = function (n) {
  7286. var oracle = this.lineOracle;
  7287. return oracle && oracle.lookAhead(n)
  7288. };
  7289. StringStream.prototype.baseToken = function () {
  7290. var oracle = this.lineOracle;
  7291. return oracle && oracle.baseToken(this.pos)
  7292. };
  7293. var SavedContext = function(state, lookAhead) {
  7294. this.state = state;
  7295. this.lookAhead = lookAhead;
  7296. };
  7297. var Context = function(doc, state, line, lookAhead) {
  7298. this.state = state;
  7299. this.doc = doc;
  7300. this.line = line;
  7301. this.maxLookAhead = lookAhead || 0;
  7302. this.baseTokens = null;
  7303. this.baseTokenPos = 1;
  7304. };
  7305. Context.prototype.lookAhead = function (n) {
  7306. var line = this.doc.getLine(this.line + n);
  7307. if (line != null && n > this.maxLookAhead) { this.maxLookAhead = n; }
  7308. return line
  7309. };
  7310. Context.prototype.baseToken = function (n) {
  7311. var this$1 = this;
  7312. if (!this.baseTokens) { return null }
  7313. while (this.baseTokens[this.baseTokenPos] <= n)
  7314. { this$1.baseTokenPos += 2; }
  7315. var type = this.baseTokens[this.baseTokenPos + 1];
  7316. return {type: type && type.replace(/( |^)overlay .*/, ""),
  7317. size: this.baseTokens[this.baseTokenPos] - n}
  7318. };
  7319. Context.prototype.nextLine = function () {
  7320. this.line++;
  7321. if (this.maxLookAhead > 0) { this.maxLookAhead--; }
  7322. };
  7323. Context.fromSaved = function (doc, saved, line) {
  7324. if (saved instanceof SavedContext)
  7325. { return new Context(doc, copyState(doc.mode, saved.state), line, saved.lookAhead) }
  7326. else
  7327. { return new Context(doc, copyState(doc.mode, saved), line) }
  7328. };
  7329. Context.prototype.save = function (copy) {
  7330. var state = copy !== false ? copyState(this.doc.mode, this.state) : this.state;
  7331. return this.maxLookAhead > 0 ? new SavedContext(state, this.maxLookAhead) : state
  7332. };
  7333. // Compute a style array (an array starting with a mode generation
  7334. // -- for invalidation -- followed by pairs of end positions and
  7335. // style strings), which is used to highlight the tokens on the
  7336. // line.
  7337. function highlightLine(cm, line, context, forceToEnd) {
  7338. // A styles array always starts with a number identifying the
  7339. // mode/overlays that it is based on (for easy invalidation).
  7340. var st = [cm.state.modeGen], lineClasses = {};
  7341. // Compute the base array of styles
  7342. runMode(cm, line.text, cm.doc.mode, context, function (end, style) { return st.push(end, style); },
  7343. lineClasses, forceToEnd);
  7344. var state = context.state;
  7345. // Run overlays, adjust style array.
  7346. var loop = function ( o ) {
  7347. context.baseTokens = st;
  7348. var overlay = cm.state.overlays[o], i = 1, at = 0;
  7349. context.state = true;
  7350. runMode(cm, line.text, overlay.mode, context, function (end, style) {
  7351. var start = i;
  7352. // Ensure there's a token end at the current position, and that i points at it
  7353. while (at < end) {
  7354. var i_end = st[i];
  7355. if (i_end > end)
  7356. { st.splice(i, 1, end, st[i+1], i_end); }
  7357. i += 2;
  7358. at = Math.min(end, i_end);
  7359. }
  7360. if (!style) { return }
  7361. if (overlay.opaque) {
  7362. st.splice(start, i - start, end, "overlay " + style);
  7363. i = start + 2;
  7364. } else {
  7365. for (; start < i; start += 2) {
  7366. var cur = st[start+1];
  7367. st[start+1] = (cur ? cur + " " : "") + "overlay " + style;
  7368. }
  7369. }
  7370. }, lineClasses);
  7371. context.state = state;
  7372. context.baseTokens = null;
  7373. context.baseTokenPos = 1;
  7374. };
  7375. for (var o = 0; o < cm.state.overlays.length; ++o) loop( o );
  7376. return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null}
  7377. }
  7378. function getLineStyles(cm, line, updateFrontier) {
  7379. if (!line.styles || line.styles[0] != cm.state.modeGen) {
  7380. var context = getContextBefore(cm, lineNo(line));
  7381. var resetState = line.text.length > cm.options.maxHighlightLength && copyState(cm.doc.mode, context.state);
  7382. var result = highlightLine(cm, line, context);
  7383. if (resetState) { context.state = resetState; }
  7384. line.stateAfter = context.save(!resetState);
  7385. line.styles = result.styles;
  7386. if (result.classes) { line.styleClasses = result.classes; }
  7387. else if (line.styleClasses) { line.styleClasses = null; }
  7388. if (updateFrontier === cm.doc.highlightFrontier)
  7389. { cm.doc.modeFrontier = Math.max(cm.doc.modeFrontier, ++cm.doc.highlightFrontier); }
  7390. }
  7391. return line.styles
  7392. }
  7393. function getContextBefore(cm, n, precise) {
  7394. var doc = cm.doc, display = cm.display;
  7395. if (!doc.mode.startState) { return new Context(doc, true, n) }
  7396. var start = findStartLine(cm, n, precise);
  7397. var saved = start > doc.first && getLine(doc, start - 1).stateAfter;
  7398. var context = saved ? Context.fromSaved(doc, saved, start) : new Context(doc, startState(doc.mode), start);
  7399. doc.iter(start, n, function (line) {
  7400. processLine(cm, line.text, context);
  7401. var pos = context.line;
  7402. line.stateAfter = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo ? context.save() : null;
  7403. context.nextLine();
  7404. });
  7405. if (precise) { doc.modeFrontier = context.line; }
  7406. return context
  7407. }
  7408. // Lightweight form of highlight -- proceed over this line and
  7409. // update state, but don't save a style array. Used for lines that
  7410. // aren't currently visible.
  7411. function processLine(cm, text, context, startAt) {
  7412. var mode = cm.doc.mode;
  7413. var stream = new StringStream(text, cm.options.tabSize, context);
  7414. stream.start = stream.pos = startAt || 0;
  7415. if (text == "") { callBlankLine(mode, context.state); }
  7416. while (!stream.eol()) {
  7417. readToken(mode, stream, context.state);
  7418. stream.start = stream.pos;
  7419. }
  7420. }
  7421. function callBlankLine(mode, state) {
  7422. if (mode.blankLine) { return mode.blankLine(state) }
  7423. if (!mode.innerMode) { return }
  7424. var inner = innerMode(mode, state);
  7425. if (inner.mode.blankLine) { return inner.mode.blankLine(inner.state) }
  7426. }
  7427. function readToken(mode, stream, state, inner) {
  7428. for (var i = 0; i < 10; i++) {
  7429. if (inner) { inner[0] = innerMode(mode, state).mode; }
  7430. var style = mode.token(stream, state);
  7431. if (stream.pos > stream.start) { return style }
  7432. }
  7433. throw new Error("Mode " + mode.name + " failed to advance stream.")
  7434. }
  7435. var Token = function(stream, type, state) {
  7436. this.start = stream.start; this.end = stream.pos;
  7437. this.string = stream.current();
  7438. this.type = type || null;
  7439. this.state = state;
  7440. };
  7441. // Utility for getTokenAt and getLineTokens
  7442. function takeToken(cm, pos, precise, asArray) {
  7443. var doc = cm.doc, mode = doc.mode, style;
  7444. pos = clipPos(doc, pos);
  7445. var line = getLine(doc, pos.line), context = getContextBefore(cm, pos.line, precise);
  7446. var stream = new StringStream(line.text, cm.options.tabSize, context), tokens;
  7447. if (asArray) { tokens = []; }
  7448. while ((asArray || stream.pos < pos.ch) && !stream.eol()) {
  7449. stream.start = stream.pos;
  7450. style = readToken(mode, stream, context.state);
  7451. if (asArray) { tokens.push(new Token(stream, style, copyState(doc.mode, context.state))); }
  7452. }
  7453. return asArray ? tokens : new Token(stream, style, context.state)
  7454. }
  7455. function extractLineClasses(type, output) {
  7456. if (type) { for (;;) {
  7457. var lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/);
  7458. if (!lineClass) { break }
  7459. type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length);
  7460. var prop = lineClass[1] ? "bgClass" : "textClass";
  7461. if (output[prop] == null)
  7462. { output[prop] = lineClass[2]; }
  7463. else if (!(new RegExp("(?:^|\s)" + lineClass[2] + "(?:$|\s)")).test(output[prop]))
  7464. { output[prop] += " " + lineClass[2]; }
  7465. } }
  7466. return type
  7467. }
  7468. // Run the given mode's parser over a line, calling f for each token.
  7469. function runMode(cm, text, mode, context, f, lineClasses, forceToEnd) {
  7470. var flattenSpans = mode.flattenSpans;
  7471. if (flattenSpans == null) { flattenSpans = cm.options.flattenSpans; }
  7472. var curStart = 0, curStyle = null;
  7473. var stream = new StringStream(text, cm.options.tabSize, context), style;
  7474. var inner = cm.options.addModeClass && [null];
  7475. if (text == "") { extractLineClasses(callBlankLine(mode, context.state), lineClasses); }
  7476. while (!stream.eol()) {
  7477. if (stream.pos > cm.options.maxHighlightLength) {
  7478. flattenSpans = false;
  7479. if (forceToEnd) { processLine(cm, text, context, stream.pos); }
  7480. stream.pos = text.length;
  7481. style = null;
  7482. } else {
  7483. style = extractLineClasses(readToken(mode, stream, context.state, inner), lineClasses);
  7484. }
  7485. if (inner) {
  7486. var mName = inner[0].name;
  7487. if (mName) { style = "m-" + (style ? mName + " " + style : mName); }
  7488. }
  7489. if (!flattenSpans || curStyle != style) {
  7490. while (curStart < stream.start) {
  7491. curStart = Math.min(stream.start, curStart + 5000);
  7492. f(curStart, curStyle);
  7493. }
  7494. curStyle = style;
  7495. }
  7496. stream.start = stream.pos;
  7497. }
  7498. while (curStart < stream.pos) {
  7499. // Webkit seems to refuse to render text nodes longer than 57444
  7500. // characters, and returns inaccurate measurements in nodes
  7501. // starting around 5000 chars.
  7502. var pos = Math.min(stream.pos, curStart + 5000);
  7503. f(pos, curStyle);
  7504. curStart = pos;
  7505. }
  7506. }
  7507. // Finds the line to start with when starting a parse. Tries to
  7508. // find a line with a stateAfter, so that it can start with a
  7509. // valid state. If that fails, it returns the line with the
  7510. // smallest indentation, which tends to need the least context to
  7511. // parse correctly.
  7512. function findStartLine(cm, n, precise) {
  7513. var minindent, minline, doc = cm.doc;
  7514. var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100);
  7515. for (var search = n; search > lim; --search) {
  7516. if (search <= doc.first) { return doc.first }
  7517. var line = getLine(doc, search - 1), after = line.stateAfter;
  7518. if (after && (!precise || search + (after instanceof SavedContext ? after.lookAhead : 0) <= doc.modeFrontier))
  7519. { return search }
  7520. var indented = countColumn(line.text, null, cm.options.tabSize);
  7521. if (minline == null || minindent > indented) {
  7522. minline = search - 1;
  7523. minindent = indented;
  7524. }
  7525. }
  7526. return minline
  7527. }
  7528. function retreatFrontier(doc, n) {
  7529. doc.modeFrontier = Math.min(doc.modeFrontier, n);
  7530. if (doc.highlightFrontier < n - 10) { return }
  7531. var start = doc.first;
  7532. for (var line = n - 1; line > start; line--) {
  7533. var saved = getLine(doc, line).stateAfter;
  7534. // change is on 3
  7535. // state on line 1 looked ahead 2 -- so saw 3
  7536. // test 1 + 2 < 3 should cover this
  7537. if (saved && (!(saved instanceof SavedContext) || line + saved.lookAhead < n)) {
  7538. start = line + 1;
  7539. break
  7540. }
  7541. }
  7542. doc.highlightFrontier = Math.min(doc.highlightFrontier, start);
  7543. }
  7544. // LINE DATA STRUCTURE
  7545. // Line objects. These hold state related to a line, including
  7546. // highlighting info (the styles array).
  7547. var Line = function(text, markedSpans, estimateHeight) {
  7548. this.text = text;
  7549. attachMarkedSpans(this, markedSpans);
  7550. this.height = estimateHeight ? estimateHeight(this) : 1;
  7551. };
  7552. Line.prototype.lineNo = function () { return lineNo(this) };
  7553. eventMixin(Line);
  7554. // Change the content (text, markers) of a line. Automatically
  7555. // invalidates cached information and tries to re-estimate the
  7556. // line's height.
  7557. function updateLine(line, text, markedSpans, estimateHeight) {
  7558. line.text = text;
  7559. if (line.stateAfter) { line.stateAfter = null; }
  7560. if (line.styles) { line.styles = null; }
  7561. if (line.order != null) { line.order = null; }
  7562. detachMarkedSpans(line);
  7563. attachMarkedSpans(line, markedSpans);
  7564. var estHeight = estimateHeight ? estimateHeight(line) : 1;
  7565. if (estHeight != line.height) { updateLineHeight(line, estHeight); }
  7566. }
  7567. // Detach a line from the document tree and its markers.
  7568. function cleanUpLine(line) {
  7569. line.parent = null;
  7570. detachMarkedSpans(line);
  7571. }
  7572. // Convert a style as returned by a mode (either null, or a string
  7573. // containing one or more styles) to a CSS style. This is cached,
  7574. // and also looks for line-wide styles.
  7575. var styleToClassCache = {};
  7576. var styleToClassCacheWithMode = {};
  7577. function interpretTokenStyle(style, options) {
  7578. if (!style || /^\s*$/.test(style)) { return null }
  7579. var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache;
  7580. return cache[style] ||
  7581. (cache[style] = style.replace(/\S+/g, "cm-$&"))
  7582. }
  7583. // Render the DOM representation of the text of a line. Also builds
  7584. // up a 'line map', which points at the DOM nodes that represent
  7585. // specific stretches of text, and is used by the measuring code.
  7586. // The returned object contains the DOM node, this map, and
  7587. // information about line-wide styles that were set by the mode.
  7588. function buildLineContent(cm, lineView) {
  7589. // The padding-right forces the element to have a 'border', which
  7590. // is needed on Webkit to be able to get line-level bounding
  7591. // rectangles for it (in measureChar).
  7592. var content = eltP("span", null, null, webkit ? "padding-right: .1px" : null);
  7593. var builder = {pre: eltP("pre", [content], "CodeMirror-line"), content: content,
  7594. col: 0, pos: 0, cm: cm,
  7595. trailingSpace: false,
  7596. splitSpaces: (ie || webkit) && cm.getOption("lineWrapping")};
  7597. lineView.measure = {};
  7598. // Iterate over the logical lines that make up this visual line.
  7599. for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) {
  7600. var line = i ? lineView.rest[i - 1] : lineView.line, order = (void 0);
  7601. builder.pos = 0;
  7602. builder.addToken = buildToken;
  7603. // Optionally wire in some hacks into the token-rendering
  7604. // algorithm, to deal with browser quirks.
  7605. if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line, cm.doc.direction)))
  7606. { builder.addToken = buildTokenBadBidi(builder.addToken, order); }
  7607. builder.map = [];
  7608. var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line);
  7609. insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate));
  7610. if (line.styleClasses) {
  7611. if (line.styleClasses.bgClass)
  7612. { builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || ""); }
  7613. if (line.styleClasses.textClass)
  7614. { builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || ""); }
  7615. }
  7616. // Ensure at least a single node is present, for measuring.
  7617. if (builder.map.length == 0)
  7618. { builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure))); }
  7619. // Store the map and a cache object for the current logical line
  7620. if (i == 0) {
  7621. lineView.measure.map = builder.map;
  7622. lineView.measure.cache = {};
  7623. } else {
  7624. (lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map)
  7625. ;(lineView.measure.caches || (lineView.measure.caches = [])).push({});
  7626. }
  7627. }
  7628. // See issue #2901
  7629. if (webkit) {
  7630. var last = builder.content.lastChild;
  7631. if (/\bcm-tab\b/.test(last.className) || (last.querySelector && last.querySelector(".cm-tab")))
  7632. { builder.content.className = "cm-tab-wrap-hack"; }
  7633. }
  7634. signal(cm, "renderLine", cm, lineView.line, builder.pre);
  7635. if (builder.pre.className)
  7636. { builder.textClass = joinClasses(builder.pre.className, builder.textClass || ""); }
  7637. return builder
  7638. }
  7639. function defaultSpecialCharPlaceholder(ch) {
  7640. var token = elt("span", "\u2022", "cm-invalidchar");
  7641. token.title = "\\u" + ch.charCodeAt(0).toString(16);
  7642. token.setAttribute("aria-label", token.title);
  7643. return token
  7644. }
  7645. // Build up the DOM representation for a single token, and add it to
  7646. // the line map. Takes care to render special characters separately.
  7647. function buildToken(builder, text, style, startStyle, endStyle, title, css) {
  7648. if (!text) { return }
  7649. var displayText = builder.splitSpaces ? splitSpaces(text, builder.trailingSpace) : text;
  7650. var special = builder.cm.state.specialChars, mustWrap = false;
  7651. var content;
  7652. if (!special.test(text)) {
  7653. builder.col += text.length;
  7654. content = document.createTextNode(displayText);
  7655. builder.map.push(builder.pos, builder.pos + text.length, content);
  7656. if (ie && ie_version < 9) { mustWrap = true; }
  7657. builder.pos += text.length;
  7658. } else {
  7659. content = document.createDocumentFragment();
  7660. var pos = 0;
  7661. while (true) {
  7662. special.lastIndex = pos;
  7663. var m = special.exec(text);
  7664. var skipped = m ? m.index - pos : text.length - pos;
  7665. if (skipped) {
  7666. var txt = document.createTextNode(displayText.slice(pos, pos + skipped));
  7667. if (ie && ie_version < 9) { content.appendChild(elt("span", [txt])); }
  7668. else { content.appendChild(txt); }
  7669. builder.map.push(builder.pos, builder.pos + skipped, txt);
  7670. builder.col += skipped;
  7671. builder.pos += skipped;
  7672. }
  7673. if (!m) { break }
  7674. pos += skipped + 1;
  7675. var txt$1 = (void 0);
  7676. if (m[0] == "\t") {
  7677. var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize;
  7678. txt$1 = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab"));
  7679. txt$1.setAttribute("role", "presentation");
  7680. txt$1.setAttribute("cm-text", "\t");
  7681. builder.col += tabWidth;
  7682. } else if (m[0] == "\r" || m[0] == "\n") {
  7683. txt$1 = content.appendChild(elt("span", m[0] == "\r" ? "\u240d" : "\u2424", "cm-invalidchar"));
  7684. txt$1.setAttribute("cm-text", m[0]);
  7685. builder.col += 1;
  7686. } else {
  7687. txt$1 = builder.cm.options.specialCharPlaceholder(m[0]);
  7688. txt$1.setAttribute("cm-text", m[0]);
  7689. if (ie && ie_version < 9) { content.appendChild(elt("span", [txt$1])); }
  7690. else { content.appendChild(txt$1); }
  7691. builder.col += 1;
  7692. }
  7693. builder.map.push(builder.pos, builder.pos + 1, txt$1);
  7694. builder.pos++;
  7695. }
  7696. }
  7697. builder.trailingSpace = displayText.charCodeAt(text.length - 1) == 32;
  7698. if (style || startStyle || endStyle || mustWrap || css) {
  7699. var fullStyle = style || "";
  7700. if (startStyle) { fullStyle += startStyle; }
  7701. if (endStyle) { fullStyle += endStyle; }
  7702. var token = elt("span", [content], fullStyle, css);
  7703. if (title) { token.title = title; }
  7704. return builder.content.appendChild(token)
  7705. }
  7706. builder.content.appendChild(content);
  7707. }
  7708. function splitSpaces(text, trailingBefore) {
  7709. if (text.length > 1 && !/ /.test(text)) { return text }
  7710. var spaceBefore = trailingBefore, result = "";
  7711. for (var i = 0; i < text.length; i++) {
  7712. var ch = text.charAt(i);
  7713. if (ch == " " && spaceBefore && (i == text.length - 1 || text.charCodeAt(i + 1) == 32))
  7714. { ch = "\u00a0"; }
  7715. result += ch;
  7716. spaceBefore = ch == " ";
  7717. }
  7718. return result
  7719. }
  7720. // Work around nonsense dimensions being reported for stretches of
  7721. // right-to-left text.
  7722. function buildTokenBadBidi(inner, order) {
  7723. return function (builder, text, style, startStyle, endStyle, title, css) {
  7724. style = style ? style + " cm-force-border" : "cm-force-border";
  7725. var start = builder.pos, end = start + text.length;
  7726. for (;;) {
  7727. // Find the part that overlaps with the start of this text
  7728. var part = (void 0);
  7729. for (var i = 0; i < order.length; i++) {
  7730. part = order[i];
  7731. if (part.to > start && part.from <= start) { break }
  7732. }
  7733. if (part.to >= end) { return inner(builder, text, style, startStyle, endStyle, title, css) }
  7734. inner(builder, text.slice(0, part.to - start), style, startStyle, null, title, css);
  7735. startStyle = null;
  7736. text = text.slice(part.to - start);
  7737. start = part.to;
  7738. }
  7739. }
  7740. }
  7741. function buildCollapsedSpan(builder, size, marker, ignoreWidget) {
  7742. var widget = !ignoreWidget && marker.widgetNode;
  7743. if (widget) { builder.map.push(builder.pos, builder.pos + size, widget); }
  7744. if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) {
  7745. if (!widget)
  7746. { widget = builder.content.appendChild(document.createElement("span")); }
  7747. widget.setAttribute("cm-marker", marker.id);
  7748. }
  7749. if (widget) {
  7750. builder.cm.display.input.setUneditable(widget);
  7751. builder.content.appendChild(widget);
  7752. }
  7753. builder.pos += size;
  7754. builder.trailingSpace = false;
  7755. }
  7756. // Outputs a number of spans to make up a line, taking highlighting
  7757. // and marked text into account.
  7758. function insertLineContent(line, builder, styles) {
  7759. var spans = line.markedSpans, allText = line.text, at = 0;
  7760. if (!spans) {
  7761. for (var i$1 = 1; i$1 < styles.length; i$1+=2)
  7762. { builder.addToken(builder, allText.slice(at, at = styles[i$1]), interpretTokenStyle(styles[i$1+1], builder.cm.options)); }
  7763. return
  7764. }
  7765. var len = allText.length, pos = 0, i = 1, text = "", style, css;
  7766. var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, title, collapsed;
  7767. for (;;) {
  7768. if (nextChange == pos) { // Update current marker set
  7769. spanStyle = spanEndStyle = spanStartStyle = title = css = "";
  7770. collapsed = null; nextChange = Infinity;
  7771. var foundBookmarks = [], endStyles = (void 0);
  7772. for (var j = 0; j < spans.length; ++j) {
  7773. var sp = spans[j], m = sp.marker;
  7774. if (m.type == "bookmark" && sp.from == pos && m.widgetNode) {
  7775. foundBookmarks.push(m);
  7776. } else if (sp.from <= pos && (sp.to == null || sp.to > pos || m.collapsed && sp.to == pos && sp.from == pos)) {
  7777. if (sp.to != null && sp.to != pos && nextChange > sp.to) {
  7778. nextChange = sp.to;
  7779. spanEndStyle = "";
  7780. }
  7781. if (m.className) { spanStyle += " " + m.className; }
  7782. if (m.css) { css = (css ? css + ";" : "") + m.css; }
  7783. if (m.startStyle && sp.from == pos) { spanStartStyle += " " + m.startStyle; }
  7784. if (m.endStyle && sp.to == nextChange) { (endStyles || (endStyles = [])).push(m.endStyle, sp.to); }
  7785. if (m.title && !title) { title = m.title; }
  7786. if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0))
  7787. { collapsed = sp; }
  7788. } else if (sp.from > pos && nextChange > sp.from) {
  7789. nextChange = sp.from;
  7790. }
  7791. }
  7792. if (endStyles) { for (var j$1 = 0; j$1 < endStyles.length; j$1 += 2)
  7793. { if (endStyles[j$1 + 1] == nextChange) { spanEndStyle += " " + endStyles[j$1]; } } }
  7794. if (!collapsed || collapsed.from == pos) { for (var j$2 = 0; j$2 < foundBookmarks.length; ++j$2)
  7795. { buildCollapsedSpan(builder, 0, foundBookmarks[j$2]); } }
  7796. if (collapsed && (collapsed.from || 0) == pos) {
  7797. buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos,
  7798. collapsed.marker, collapsed.from == null);
  7799. if (collapsed.to == null) { return }
  7800. if (collapsed.to == pos) { collapsed = false; }
  7801. }
  7802. }
  7803. if (pos >= len) { break }
  7804. var upto = Math.min(len, nextChange);
  7805. while (true) {
  7806. if (text) {
  7807. var end = pos + text.length;
  7808. if (!collapsed) {
  7809. var tokenText = end > upto ? text.slice(0, upto - pos) : text;
  7810. builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle,
  7811. spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", title, css);
  7812. }
  7813. if (end >= upto) {text = text.slice(upto - pos); pos = upto; break}
  7814. pos = end;
  7815. spanStartStyle = "";
  7816. }
  7817. text = allText.slice(at, at = styles[i++]);
  7818. style = interpretTokenStyle(styles[i++], builder.cm.options);
  7819. }
  7820. }
  7821. }
  7822. // These objects are used to represent the visible (currently drawn)
  7823. // part of the document. A LineView may correspond to multiple
  7824. // logical lines, if those are connected by collapsed ranges.
  7825. function LineView(doc, line, lineN) {
  7826. // The starting line
  7827. this.line = line;
  7828. // Continuing lines, if any
  7829. this.rest = visualLineContinued(line);
  7830. // Number of logical lines in this visual line
  7831. this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1;
  7832. this.node = this.text = null;
  7833. this.hidden = lineIsHidden(doc, line);
  7834. }
  7835. // Create a range of LineView objects for the given lines.
  7836. function buildViewArray(cm, from, to) {
  7837. var array = [], nextPos;
  7838. for (var pos = from; pos < to; pos = nextPos) {
  7839. var view = new LineView(cm.doc, getLine(cm.doc, pos), pos);
  7840. nextPos = pos + view.size;
  7841. array.push(view);
  7842. }
  7843. return array
  7844. }
  7845. var operationGroup = null;
  7846. function pushOperation(op) {
  7847. if (operationGroup) {
  7848. operationGroup.ops.push(op);
  7849. } else {
  7850. op.ownsGroup = operationGroup = {
  7851. ops: [op],
  7852. delayedCallbacks: []
  7853. };
  7854. }
  7855. }
  7856. function fireCallbacksForOps(group) {
  7857. // Calls delayed callbacks and cursorActivity handlers until no
  7858. // new ones appear
  7859. var callbacks = group.delayedCallbacks, i = 0;
  7860. do {
  7861. for (; i < callbacks.length; i++)
  7862. { callbacks[i].call(null); }
  7863. for (var j = 0; j < group.ops.length; j++) {
  7864. var op = group.ops[j];
  7865. if (op.cursorActivityHandlers)
  7866. { while (op.cursorActivityCalled < op.cursorActivityHandlers.length)
  7867. { op.cursorActivityHandlers[op.cursorActivityCalled++].call(null, op.cm); } }
  7868. }
  7869. } while (i < callbacks.length)
  7870. }
  7871. function finishOperation(op, endCb) {
  7872. var group = op.ownsGroup;
  7873. if (!group) { return }
  7874. try { fireCallbacksForOps(group); }
  7875. finally {
  7876. operationGroup = null;
  7877. endCb(group);
  7878. }
  7879. }
  7880. var orphanDelayedCallbacks = null;
  7881. // Often, we want to signal events at a point where we are in the
  7882. // middle of some work, but don't want the handler to start calling
  7883. // other methods on the editor, which might be in an inconsistent
  7884. // state or simply not expect any other events to happen.
  7885. // signalLater looks whether there are any handlers, and schedules
  7886. // them to be executed when the last operation ends, or, if no
  7887. // operation is active, when a timeout fires.
  7888. function signalLater(emitter, type /*, values...*/) {
  7889. var arr = getHandlers(emitter, type);
  7890. if (!arr.length) { return }
  7891. var args = Array.prototype.slice.call(arguments, 2), list;
  7892. if (operationGroup) {
  7893. list = operationGroup.delayedCallbacks;
  7894. } else if (orphanDelayedCallbacks) {
  7895. list = orphanDelayedCallbacks;
  7896. } else {
  7897. list = orphanDelayedCallbacks = [];
  7898. setTimeout(fireOrphanDelayed, 0);
  7899. }
  7900. var loop = function ( i ) {
  7901. list.push(function () { return arr[i].apply(null, args); });
  7902. };
  7903. for (var i = 0; i < arr.length; ++i)
  7904. loop( i );
  7905. }
  7906. function fireOrphanDelayed() {
  7907. var delayed = orphanDelayedCallbacks;
  7908. orphanDelayedCallbacks = null;
  7909. for (var i = 0; i < delayed.length; ++i) { delayed[i](); }
  7910. }
  7911. // When an aspect of a line changes, a string is added to
  7912. // lineView.changes. This updates the relevant part of the line's
  7913. // DOM structure.
  7914. function updateLineForChanges(cm, lineView, lineN, dims) {
  7915. for (var j = 0; j < lineView.changes.length; j++) {
  7916. var type = lineView.changes[j];
  7917. if (type == "text") { updateLineText(cm, lineView); }
  7918. else if (type == "gutter") { updateLineGutter(cm, lineView, lineN, dims); }
  7919. else if (type == "class") { updateLineClasses(cm, lineView); }
  7920. else if (type == "widget") { updateLineWidgets(cm, lineView, dims); }
  7921. }
  7922. lineView.changes = null;
  7923. }
  7924. // Lines with gutter elements, widgets or a background class need to
  7925. // be wrapped, and have the extra elements added to the wrapper div
  7926. function ensureLineWrapped(lineView) {
  7927. if (lineView.node == lineView.text) {
  7928. lineView.node = elt("div", null, null, "position: relative");
  7929. if (lineView.text.parentNode)
  7930. { lineView.text.parentNode.replaceChild(lineView.node, lineView.text); }
  7931. lineView.node.appendChild(lineView.text);
  7932. if (ie && ie_version < 8) { lineView.node.style.zIndex = 2; }
  7933. }
  7934. return lineView.node
  7935. }
  7936. function updateLineBackground(cm, lineView) {
  7937. var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass;
  7938. if (cls) { cls += " CodeMirror-linebackground"; }
  7939. if (lineView.background) {
  7940. if (cls) { lineView.background.className = cls; }
  7941. else { lineView.background.parentNode.removeChild(lineView.background); lineView.background = null; }
  7942. } else if (cls) {
  7943. var wrap = ensureLineWrapped(lineView);
  7944. lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild);
  7945. cm.display.input.setUneditable(lineView.background);
  7946. }
  7947. }
  7948. // Wrapper around buildLineContent which will reuse the structure
  7949. // in display.externalMeasured when possible.
  7950. function getLineContent(cm, lineView) {
  7951. var ext = cm.display.externalMeasured;
  7952. if (ext && ext.line == lineView.line) {
  7953. cm.display.externalMeasured = null;
  7954. lineView.measure = ext.measure;
  7955. return ext.built
  7956. }
  7957. return buildLineContent(cm, lineView)
  7958. }
  7959. // Redraw the line's text. Interacts with the background and text
  7960. // classes because the mode may output tokens that influence these
  7961. // classes.
  7962. function updateLineText(cm, lineView) {
  7963. var cls = lineView.text.className;
  7964. var built = getLineContent(cm, lineView);
  7965. if (lineView.text == lineView.node) { lineView.node = built.pre; }
  7966. lineView.text.parentNode.replaceChild(built.pre, lineView.text);
  7967. lineView.text = built.pre;
  7968. if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) {
  7969. lineView.bgClass = built.bgClass;
  7970. lineView.textClass = built.textClass;
  7971. updateLineClasses(cm, lineView);
  7972. } else if (cls) {
  7973. lineView.text.className = cls;
  7974. }
  7975. }
  7976. function updateLineClasses(cm, lineView) {
  7977. updateLineBackground(cm, lineView);
  7978. if (lineView.line.wrapClass)
  7979. { ensureLineWrapped(lineView).className = lineView.line.wrapClass; }
  7980. else if (lineView.node != lineView.text)
  7981. { lineView.node.className = ""; }
  7982. var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass;
  7983. lineView.text.className = textClass || "";
  7984. }
  7985. function updateLineGutter(cm, lineView, lineN, dims) {
  7986. if (lineView.gutter) {
  7987. lineView.node.removeChild(lineView.gutter);
  7988. lineView.gutter = null;
  7989. }
  7990. if (lineView.gutterBackground) {
  7991. lineView.node.removeChild(lineView.gutterBackground);
  7992. lineView.gutterBackground = null;
  7993. }
  7994. if (lineView.line.gutterClass) {
  7995. var wrap = ensureLineWrapped(lineView);
  7996. lineView.gutterBackground = elt("div", null, "CodeMirror-gutter-background " + lineView.line.gutterClass,
  7997. ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px; width: " + (dims.gutterTotalWidth) + "px"));
  7998. cm.display.input.setUneditable(lineView.gutterBackground);
  7999. wrap.insertBefore(lineView.gutterBackground, lineView.text);
  8000. }
  8001. var markers = lineView.line.gutterMarkers;
  8002. if (cm.options.lineNumbers || markers) {
  8003. var wrap$1 = ensureLineWrapped(lineView);
  8004. var gutterWrap = lineView.gutter = elt("div", null, "CodeMirror-gutter-wrapper", ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px"));
  8005. cm.display.input.setUneditable(gutterWrap);
  8006. wrap$1.insertBefore(gutterWrap, lineView.text);
  8007. if (lineView.line.gutterClass)
  8008. { gutterWrap.className += " " + lineView.line.gutterClass; }
  8009. if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"]))
  8010. { lineView.lineNumber = gutterWrap.appendChild(
  8011. elt("div", lineNumberFor(cm.options, lineN),
  8012. "CodeMirror-linenumber CodeMirror-gutter-elt",
  8013. ("left: " + (dims.gutterLeft["CodeMirror-linenumbers"]) + "px; width: " + (cm.display.lineNumInnerWidth) + "px"))); }
  8014. if (markers) { for (var k = 0; k < cm.options.gutters.length; ++k) {
  8015. var id = cm.options.gutters[k], found = markers.hasOwnProperty(id) && markers[id];
  8016. if (found)
  8017. { gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt",
  8018. ("left: " + (dims.gutterLeft[id]) + "px; width: " + (dims.gutterWidth[id]) + "px"))); }
  8019. } }
  8020. }
  8021. }
  8022. function updateLineWidgets(cm, lineView, dims) {
  8023. if (lineView.alignable) { lineView.alignable = null; }
  8024. for (var node = lineView.node.firstChild, next = (void 0); node; node = next) {
  8025. next = node.nextSibling;
  8026. if (node.className == "CodeMirror-linewidget")
  8027. { lineView.node.removeChild(node); }
  8028. }
  8029. insertLineWidgets(cm, lineView, dims);
  8030. }
  8031. // Build a line's DOM representation from scratch
  8032. function buildLineElement(cm, lineView, lineN, dims) {
  8033. var built = getLineContent(cm, lineView);
  8034. lineView.text = lineView.node = built.pre;
  8035. if (built.bgClass) { lineView.bgClass = built.bgClass; }
  8036. if (built.textClass) { lineView.textClass = built.textClass; }
  8037. updateLineClasses(cm, lineView);
  8038. updateLineGutter(cm, lineView, lineN, dims);
  8039. insertLineWidgets(cm, lineView, dims);
  8040. return lineView.node
  8041. }
  8042. // A lineView may contain multiple logical lines (when merged by
  8043. // collapsed spans). The widgets for all of them need to be drawn.
  8044. function insertLineWidgets(cm, lineView, dims) {
  8045. insertLineWidgetsFor(cm, lineView.line, lineView, dims, true);
  8046. if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++)
  8047. { insertLineWidgetsFor(cm, lineView.rest[i], lineView, dims, false); } }
  8048. }
  8049. function insertLineWidgetsFor(cm, line, lineView, dims, allowAbove) {
  8050. if (!line.widgets) { return }
  8051. var wrap = ensureLineWrapped(lineView);
  8052. for (var i = 0, ws = line.widgets; i < ws.length; ++i) {
  8053. var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget");
  8054. if (!widget.handleMouseEvents) { node.setAttribute("cm-ignore-events", "true"); }
  8055. positionLineWidget(widget, node, lineView, dims);
  8056. cm.display.input.setUneditable(node);
  8057. if (allowAbove && widget.above)
  8058. { wrap.insertBefore(node, lineView.gutter || lineView.text); }
  8059. else
  8060. { wrap.appendChild(node); }
  8061. signalLater(widget, "redraw");
  8062. }
  8063. }
  8064. function positionLineWidget(widget, node, lineView, dims) {
  8065. if (widget.noHScroll) {
  8066. (lineView.alignable || (lineView.alignable = [])).push(node);
  8067. var width = dims.wrapperWidth;
  8068. node.style.left = dims.fixedPos + "px";
  8069. if (!widget.coverGutter) {
  8070. width -= dims.gutterTotalWidth;
  8071. node.style.paddingLeft = dims.gutterTotalWidth + "px";
  8072. }
  8073. node.style.width = width + "px";
  8074. }
  8075. if (widget.coverGutter) {
  8076. node.style.zIndex = 5;
  8077. node.style.position = "relative";
  8078. if (!widget.noHScroll) { node.style.marginLeft = -dims.gutterTotalWidth + "px"; }
  8079. }
  8080. }
  8081. function widgetHeight(widget) {
  8082. if (widget.height != null) { return widget.height }
  8083. var cm = widget.doc.cm;
  8084. if (!cm) { return 0 }
  8085. if (!contains(document.body, widget.node)) {
  8086. var parentStyle = "position: relative;";
  8087. if (widget.coverGutter)
  8088. { parentStyle += "margin-left: -" + cm.display.gutters.offsetWidth + "px;"; }
  8089. if (widget.noHScroll)
  8090. { parentStyle += "width: " + cm.display.wrapper.clientWidth + "px;"; }
  8091. removeChildrenAndAdd(cm.display.measure, elt("div", [widget.node], null, parentStyle));
  8092. }
  8093. return widget.height = widget.node.parentNode.offsetHeight
  8094. }
  8095. // Return true when the given mouse event happened in a widget
  8096. function eventInWidget(display, e) {
  8097. for (var n = e_target(e); n != display.wrapper; n = n.parentNode) {
  8098. if (!n || (n.nodeType == 1 && n.getAttribute("cm-ignore-events") == "true") ||
  8099. (n.parentNode == display.sizer && n != display.mover))
  8100. { return true }
  8101. }
  8102. }
  8103. // POSITION MEASUREMENT
  8104. function paddingTop(display) {return display.lineSpace.offsetTop}
  8105. function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight}
  8106. function paddingH(display) {
  8107. if (display.cachedPaddingH) { return display.cachedPaddingH }
  8108. var e = removeChildrenAndAdd(display.measure, elt("pre", "x"));
  8109. var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle;
  8110. var data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)};
  8111. if (!isNaN(data.left) && !isNaN(data.right)) { display.cachedPaddingH = data; }
  8112. return data
  8113. }
  8114. function scrollGap(cm) { return scrollerGap - cm.display.nativeBarWidth }
  8115. function displayWidth(cm) {
  8116. return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth
  8117. }
  8118. function displayHeight(cm) {
  8119. return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight
  8120. }
  8121. // Ensure the lineView.wrapping.heights array is populated. This is
  8122. // an array of bottom offsets for the lines that make up a drawn
  8123. // line. When lineWrapping is on, there might be more than one
  8124. // height.
  8125. function ensureLineHeights(cm, lineView, rect) {
  8126. var wrapping = cm.options.lineWrapping;
  8127. var curWidth = wrapping && displayWidth(cm);
  8128. if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) {
  8129. var heights = lineView.measure.heights = [];
  8130. if (wrapping) {
  8131. lineView.measure.width = curWidth;
  8132. var rects = lineView.text.firstChild.getClientRects();
  8133. for (var i = 0; i < rects.length - 1; i++) {
  8134. var cur = rects[i], next = rects[i + 1];
  8135. if (Math.abs(cur.bottom - next.bottom) > 2)
  8136. { heights.push((cur.bottom + next.top) / 2 - rect.top); }
  8137. }
  8138. }
  8139. heights.push(rect.bottom - rect.top);
  8140. }
  8141. }
  8142. // Find a line map (mapping character offsets to text nodes) and a
  8143. // measurement cache for the given line number. (A line view might
  8144. // contain multiple lines when collapsed ranges are present.)
  8145. function mapFromLineView(lineView, line, lineN) {
  8146. if (lineView.line == line)
  8147. { return {map: lineView.measure.map, cache: lineView.measure.cache} }
  8148. for (var i = 0; i < lineView.rest.length; i++)
  8149. { if (lineView.rest[i] == line)
  8150. { return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i]} } }
  8151. for (var i$1 = 0; i$1 < lineView.rest.length; i$1++)
  8152. { if (lineNo(lineView.rest[i$1]) > lineN)
  8153. { return {map: lineView.measure.maps[i$1], cache: lineView.measure.caches[i$1], before: true} } }
  8154. }
  8155. // Render a line into the hidden node display.externalMeasured. Used
  8156. // when measurement is needed for a line that's not in the viewport.
  8157. function updateExternalMeasurement(cm, line) {
  8158. line = visualLine(line);
  8159. var lineN = lineNo(line);
  8160. var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN);
  8161. view.lineN = lineN;
  8162. var built = view.built = buildLineContent(cm, view);
  8163. view.text = built.pre;
  8164. removeChildrenAndAdd(cm.display.lineMeasure, built.pre);
  8165. return view
  8166. }
  8167. // Get a {top, bottom, left, right} box (in line-local coordinates)
  8168. // for a given character.
  8169. function measureChar(cm, line, ch, bias) {
  8170. return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias)
  8171. }
  8172. // Find a line view that corresponds to the given line number.
  8173. function findViewForLine(cm, lineN) {
  8174. if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo)
  8175. { return cm.display.view[findViewIndex(cm, lineN)] }
  8176. var ext = cm.display.externalMeasured;
  8177. if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size)
  8178. { return ext }
  8179. }
  8180. // Measurement can be split in two steps, the set-up work that
  8181. // applies to the whole line, and the measurement of the actual
  8182. // character. Functions like coordsChar, that need to do a lot of
  8183. // measurements in a row, can thus ensure that the set-up work is
  8184. // only done once.
  8185. function prepareMeasureForLine(cm, line) {
  8186. var lineN = lineNo(line);
  8187. var view = findViewForLine(cm, lineN);
  8188. if (view && !view.text) {
  8189. view = null;
  8190. } else if (view && view.changes) {
  8191. updateLineForChanges(cm, view, lineN, getDimensions(cm));
  8192. cm.curOp.forceUpdate = true;
  8193. }
  8194. if (!view)
  8195. { view = updateExternalMeasurement(cm, line); }
  8196. var info = mapFromLineView(view, line, lineN);
  8197. return {
  8198. line: line, view: view, rect: null,
  8199. map: info.map, cache: info.cache, before: info.before,
  8200. hasHeights: false
  8201. }
  8202. }
  8203. // Given a prepared measurement object, measures the position of an
  8204. // actual character (or fetches it from the cache).
  8205. function measureCharPrepared(cm, prepared, ch, bias, varHeight) {
  8206. if (prepared.before) { ch = -1; }
  8207. var key = ch + (bias || ""), found;
  8208. if (prepared.cache.hasOwnProperty(key)) {
  8209. found = prepared.cache[key];
  8210. } else {
  8211. if (!prepared.rect)
  8212. { prepared.rect = prepared.view.text.getBoundingClientRect(); }
  8213. if (!prepared.hasHeights) {
  8214. ensureLineHeights(cm, prepared.view, prepared.rect);
  8215. prepared.hasHeights = true;
  8216. }
  8217. found = measureCharInner(cm, prepared, ch, bias);
  8218. if (!found.bogus) { prepared.cache[key] = found; }
  8219. }
  8220. return {left: found.left, right: found.right,
  8221. top: varHeight ? found.rtop : found.top,
  8222. bottom: varHeight ? found.rbottom : found.bottom}
  8223. }
  8224. var nullRect = {left: 0, right: 0, top: 0, bottom: 0};
  8225. function nodeAndOffsetInLineMap(map$$1, ch, bias) {
  8226. var node, start, end, collapse, mStart, mEnd;
  8227. // First, search the line map for the text node corresponding to,
  8228. // or closest to, the target character.
  8229. for (var i = 0; i < map$$1.length; i += 3) {
  8230. mStart = map$$1[i];
  8231. mEnd = map$$1[i + 1];
  8232. if (ch < mStart) {
  8233. start = 0; end = 1;
  8234. collapse = "left";
  8235. } else if (ch < mEnd) {
  8236. start = ch - mStart;
  8237. end = start + 1;
  8238. } else if (i == map$$1.length - 3 || ch == mEnd && map$$1[i + 3] > ch) {
  8239. end = mEnd - mStart;
  8240. start = end - 1;
  8241. if (ch >= mEnd) { collapse = "right"; }
  8242. }
  8243. if (start != null) {
  8244. node = map$$1[i + 2];
  8245. if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right"))
  8246. { collapse = bias; }
  8247. if (bias == "left" && start == 0)
  8248. { while (i && map$$1[i - 2] == map$$1[i - 3] && map$$1[i - 1].insertLeft) {
  8249. node = map$$1[(i -= 3) + 2];
  8250. collapse = "left";
  8251. } }
  8252. if (bias == "right" && start == mEnd - mStart)
  8253. { while (i < map$$1.length - 3 && map$$1[i + 3] == map$$1[i + 4] && !map$$1[i + 5].insertLeft) {
  8254. node = map$$1[(i += 3) + 2];
  8255. collapse = "right";
  8256. } }
  8257. break
  8258. }
  8259. }
  8260. return {node: node, start: start, end: end, collapse: collapse, coverStart: mStart, coverEnd: mEnd}
  8261. }
  8262. function getUsefulRect(rects, bias) {
  8263. var rect = nullRect;
  8264. if (bias == "left") { for (var i = 0; i < rects.length; i++) {
  8265. if ((rect = rects[i]).left != rect.right) { break }
  8266. } } else { for (var i$1 = rects.length - 1; i$1 >= 0; i$1--) {
  8267. if ((rect = rects[i$1]).left != rect.right) { break }
  8268. } }
  8269. return rect
  8270. }
  8271. function measureCharInner(cm, prepared, ch, bias) {
  8272. var place = nodeAndOffsetInLineMap(prepared.map, ch, bias);
  8273. var node = place.node, start = place.start, end = place.end, collapse = place.collapse;
  8274. var rect;
  8275. if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates.
  8276. for (var i$1 = 0; i$1 < 4; i$1++) { // Retry a maximum of 4 times when nonsense rectangles are returned
  8277. while (start && isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) { --start; }
  8278. while (place.coverStart + end < place.coverEnd && isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) { ++end; }
  8279. if (ie && ie_version < 9 && start == 0 && end == place.coverEnd - place.coverStart)
  8280. { rect = node.parentNode.getBoundingClientRect(); }
  8281. else
  8282. { rect = getUsefulRect(range(node, start, end).getClientRects(), bias); }
  8283. if (rect.left || rect.right || start == 0) { break }
  8284. end = start;
  8285. start = start - 1;
  8286. collapse = "right";
  8287. }
  8288. if (ie && ie_version < 11) { rect = maybeUpdateRectForZooming(cm.display.measure, rect); }
  8289. } else { // If it is a widget, simply get the box for the whole widget.
  8290. if (start > 0) { collapse = bias = "right"; }
  8291. var rects;
  8292. if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1)
  8293. { rect = rects[bias == "right" ? rects.length - 1 : 0]; }
  8294. else
  8295. { rect = node.getBoundingClientRect(); }
  8296. }
  8297. if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) {
  8298. var rSpan = node.parentNode.getClientRects()[0];
  8299. if (rSpan)
  8300. { rect = {left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom}; }
  8301. else
  8302. { rect = nullRect; }
  8303. }
  8304. var rtop = rect.top - prepared.rect.top, rbot = rect.bottom - prepared.rect.top;
  8305. var mid = (rtop + rbot) / 2;
  8306. var heights = prepared.view.measure.heights;
  8307. var i = 0;
  8308. for (; i < heights.length - 1; i++)
  8309. { if (mid < heights[i]) { break } }
  8310. var top = i ? heights[i - 1] : 0, bot = heights[i];
  8311. var result = {left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left,
  8312. right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left,
  8313. top: top, bottom: bot};
  8314. if (!rect.left && !rect.right) { result.bogus = true; }
  8315. if (!cm.options.singleCursorHeightPerLine) { result.rtop = rtop; result.rbottom = rbot; }
  8316. return result
  8317. }
  8318. // Work around problem with bounding client rects on ranges being
  8319. // returned incorrectly when zoomed on IE10 and below.
  8320. function maybeUpdateRectForZooming(measure, rect) {
  8321. if (!window.screen || screen.logicalXDPI == null ||
  8322. screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure))
  8323. { return rect }
  8324. var scaleX = screen.logicalXDPI / screen.deviceXDPI;
  8325. var scaleY = screen.logicalYDPI / screen.deviceYDPI;
  8326. return {left: rect.left * scaleX, right: rect.right * scaleX,
  8327. top: rect.top * scaleY, bottom: rect.bottom * scaleY}
  8328. }
  8329. function clearLineMeasurementCacheFor(lineView) {
  8330. if (lineView.measure) {
  8331. lineView.measure.cache = {};
  8332. lineView.measure.heights = null;
  8333. if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++)
  8334. { lineView.measure.caches[i] = {}; } }
  8335. }
  8336. }
  8337. function clearLineMeasurementCache(cm) {
  8338. cm.display.externalMeasure = null;
  8339. removeChildren(cm.display.lineMeasure);
  8340. for (var i = 0; i < cm.display.view.length; i++)
  8341. { clearLineMeasurementCacheFor(cm.display.view[i]); }
  8342. }
  8343. function clearCaches(cm) {
  8344. clearLineMeasurementCache(cm);
  8345. cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null;
  8346. if (!cm.options.lineWrapping) { cm.display.maxLineChanged = true; }
  8347. cm.display.lineNumChars = null;
  8348. }
  8349. function pageScrollX() {
  8350. // Work around https://bugs.chromium.org/p/chromium/issues/detail?id=489206
  8351. // which causes page_Offset and bounding client rects to use
  8352. // different reference viewports and invalidate our calculations.
  8353. if (chrome && android) { return -(document.body.getBoundingClientRect().left - parseInt(getComputedStyle(document.body).marginLeft)) }
  8354. return window.pageXOffset || (document.documentElement || document.body).scrollLeft
  8355. }
  8356. function pageScrollY() {
  8357. if (chrome && android) { return -(document.body.getBoundingClientRect().top - parseInt(getComputedStyle(document.body).marginTop)) }
  8358. return window.pageYOffset || (document.documentElement || document.body).scrollTop
  8359. }
  8360. function widgetTopHeight(lineObj) {
  8361. var height = 0;
  8362. if (lineObj.widgets) { for (var i = 0; i < lineObj.widgets.length; ++i) { if (lineObj.widgets[i].above)
  8363. { height += widgetHeight(lineObj.widgets[i]); } } }
  8364. return height
  8365. }
  8366. // Converts a {top, bottom, left, right} box from line-local
  8367. // coordinates into another coordinate system. Context may be one of
  8368. // "line", "div" (display.lineDiv), "local"./null (editor), "window",
  8369. // or "page".
  8370. function intoCoordSystem(cm, lineObj, rect, context, includeWidgets) {
  8371. if (!includeWidgets) {
  8372. var height = widgetTopHeight(lineObj);
  8373. rect.top += height; rect.bottom += height;
  8374. }
  8375. if (context == "line") { return rect }
  8376. if (!context) { context = "local"; }
  8377. var yOff = heightAtLine(lineObj);
  8378. if (context == "local") { yOff += paddingTop(cm.display); }
  8379. else { yOff -= cm.display.viewOffset; }
  8380. if (context == "page" || context == "window") {
  8381. var lOff = cm.display.lineSpace.getBoundingClientRect();
  8382. yOff += lOff.top + (context == "window" ? 0 : pageScrollY());
  8383. var xOff = lOff.left + (context == "window" ? 0 : pageScrollX());
  8384. rect.left += xOff; rect.right += xOff;
  8385. }
  8386. rect.top += yOff; rect.bottom += yOff;
  8387. return rect
  8388. }
  8389. // Coverts a box from "div" coords to another coordinate system.
  8390. // Context may be "window", "page", "div", or "local"./null.
  8391. function fromCoordSystem(cm, coords, context) {
  8392. if (context == "div") { return coords }
  8393. var left = coords.left, top = coords.top;
  8394. // First move into "page" coordinate system
  8395. if (context == "page") {
  8396. left -= pageScrollX();
  8397. top -= pageScrollY();
  8398. } else if (context == "local" || !context) {
  8399. var localBox = cm.display.sizer.getBoundingClientRect();
  8400. left += localBox.left;
  8401. top += localBox.top;
  8402. }
  8403. var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect();
  8404. return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top}
  8405. }
  8406. function charCoords(cm, pos, context, lineObj, bias) {
  8407. if (!lineObj) { lineObj = getLine(cm.doc, pos.line); }
  8408. return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context)
  8409. }
  8410. // Returns a box for a given cursor position, which may have an
  8411. // 'other' property containing the position of the secondary cursor
  8412. // on a bidi boundary.
  8413. // A cursor Pos(line, char, "before") is on the same visual line as `char - 1`
  8414. // and after `char - 1` in writing order of `char - 1`
  8415. // A cursor Pos(line, char, "after") is on the same visual line as `char`
  8416. // and before `char` in writing order of `char`
  8417. // Examples (upper-case letters are RTL, lower-case are LTR):
  8418. // Pos(0, 1, ...)
  8419. // before after
  8420. // ab a|b a|b
  8421. // aB a|B aB|
  8422. // Ab |Ab A|b
  8423. // AB B|A B|A
  8424. // Every position after the last character on a line is considered to stick
  8425. // to the last character on the line.
  8426. function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) {
  8427. lineObj = lineObj || getLine(cm.doc, pos.line);
  8428. if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj); }
  8429. function get(ch, right) {
  8430. var m = measureCharPrepared(cm, preparedMeasure, ch, right ? "right" : "left", varHeight);
  8431. if (right) { m.left = m.right; } else { m.right = m.left; }
  8432. return intoCoordSystem(cm, lineObj, m, context)
  8433. }
  8434. var order = getOrder(lineObj, cm.doc.direction), ch = pos.ch, sticky = pos.sticky;
  8435. if (ch >= lineObj.text.length) {
  8436. ch = lineObj.text.length;
  8437. sticky = "before";
  8438. } else if (ch <= 0) {
  8439. ch = 0;
  8440. sticky = "after";
  8441. }
  8442. if (!order) { return get(sticky == "before" ? ch - 1 : ch, sticky == "before") }
  8443. function getBidi(ch, partPos, invert) {
  8444. var part = order[partPos], right = part.level == 1;
  8445. return get(invert ? ch - 1 : ch, right != invert)
  8446. }
  8447. var partPos = getBidiPartAt(order, ch, sticky);
  8448. var other = bidiOther;
  8449. var val = getBidi(ch, partPos, sticky == "before");
  8450. if (other != null) { val.other = getBidi(ch, other, sticky != "before"); }
  8451. return val
  8452. }
  8453. // Used to cheaply estimate the coordinates for a position. Used for
  8454. // intermediate scroll updates.
  8455. function estimateCoords(cm, pos) {
  8456. var left = 0;
  8457. pos = clipPos(cm.doc, pos);
  8458. if (!cm.options.lineWrapping) { left = charWidth(cm.display) * pos.ch; }
  8459. var lineObj = getLine(cm.doc, pos.line);
  8460. var top = heightAtLine(lineObj) + paddingTop(cm.display);
  8461. return {left: left, right: left, top: top, bottom: top + lineObj.height}
  8462. }
  8463. // Positions returned by coordsChar contain some extra information.
  8464. // xRel is the relative x position of the input coordinates compared
  8465. // to the found position (so xRel > 0 means the coordinates are to
  8466. // the right of the character position, for example). When outside
  8467. // is true, that means the coordinates lie outside the line's
  8468. // vertical range.
  8469. function PosWithInfo(line, ch, sticky, outside, xRel) {
  8470. var pos = Pos(line, ch, sticky);
  8471. pos.xRel = xRel;
  8472. if (outside) { pos.outside = true; }
  8473. return pos
  8474. }
  8475. // Compute the character position closest to the given coordinates.
  8476. // Input must be lineSpace-local ("div" coordinate system).
  8477. function coordsChar(cm, x, y) {
  8478. var doc = cm.doc;
  8479. y += cm.display.viewOffset;
  8480. if (y < 0) { return PosWithInfo(doc.first, 0, null, true, -1) }
  8481. var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1;
  8482. if (lineN > last)
  8483. { return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, null, true, 1) }
  8484. if (x < 0) { x = 0; }
  8485. var lineObj = getLine(doc, lineN);
  8486. for (;;) {
  8487. var found = coordsCharInner(cm, lineObj, lineN, x, y);
  8488. var merged = collapsedSpanAtEnd(lineObj);
  8489. var mergedPos = merged && merged.find(0, true);
  8490. if (merged && (found.ch > mergedPos.from.ch || found.ch == mergedPos.from.ch && found.xRel > 0))
  8491. { lineN = lineNo(lineObj = mergedPos.to.line); }
  8492. else
  8493. { return found }
  8494. }
  8495. }
  8496. function wrappedLineExtent(cm, lineObj, preparedMeasure, y) {
  8497. y -= widgetTopHeight(lineObj);
  8498. var end = lineObj.text.length;
  8499. var begin = findFirst(function (ch) { return measureCharPrepared(cm, preparedMeasure, ch - 1).bottom <= y; }, end, 0);
  8500. end = findFirst(function (ch) { return measureCharPrepared(cm, preparedMeasure, ch).top > y; }, begin, end);
  8501. return {begin: begin, end: end}
  8502. }
  8503. function wrappedLineExtentChar(cm, lineObj, preparedMeasure, target) {
  8504. if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj); }
  8505. var targetTop = intoCoordSystem(cm, lineObj, measureCharPrepared(cm, preparedMeasure, target), "line").top;
  8506. return wrappedLineExtent(cm, lineObj, preparedMeasure, targetTop)
  8507. }
  8508. // Returns true if the given side of a box is after the given
  8509. // coordinates, in top-to-bottom, left-to-right order.
  8510. function boxIsAfter(box, x, y, left) {
  8511. return box.bottom <= y ? false : box.top > y ? true : (left ? box.left : box.right) > x
  8512. }
  8513. function coordsCharInner(cm, lineObj, lineNo$$1, x, y) {
  8514. // Move y into line-local coordinate space
  8515. y -= heightAtLine(lineObj);
  8516. var preparedMeasure = prepareMeasureForLine(cm, lineObj);
  8517. // When directly calling `measureCharPrepared`, we have to adjust
  8518. // for the widgets at this line.
  8519. var widgetHeight$$1 = widgetTopHeight(lineObj);
  8520. var begin = 0, end = lineObj.text.length, ltr = true;
  8521. var order = getOrder(lineObj, cm.doc.direction);
  8522. // If the line isn't plain left-to-right text, first figure out
  8523. // which bidi section the coordinates fall into.
  8524. if (order) {
  8525. var part = (cm.options.lineWrapping ? coordsBidiPartWrapped : coordsBidiPart)
  8526. (cm, lineObj, lineNo$$1, preparedMeasure, order, x, y);
  8527. ltr = part.level != 1;
  8528. // The awkward -1 offsets are needed because findFirst (called
  8529. // on these below) will treat its first bound as inclusive,
  8530. // second as exclusive, but we want to actually address the
  8531. // characters in the part's range
  8532. begin = ltr ? part.from : part.to - 1;
  8533. end = ltr ? part.to : part.from - 1;
  8534. }
  8535. // A binary search to find the first character whose bounding box
  8536. // starts after the coordinates. If we run across any whose box wrap
  8537. // the coordinates, store that.
  8538. var chAround = null, boxAround = null;
  8539. var ch = findFirst(function (ch) {
  8540. var box = measureCharPrepared(cm, preparedMeasure, ch);
  8541. box.top += widgetHeight$$1; box.bottom += widgetHeight$$1;
  8542. if (!boxIsAfter(box, x, y, false)) { return false }
  8543. if (box.top <= y && box.left <= x) {
  8544. chAround = ch;
  8545. boxAround = box;
  8546. }
  8547. return true
  8548. }, begin, end);
  8549. var baseX, sticky, outside = false;
  8550. // If a box around the coordinates was found, use that
  8551. if (boxAround) {
  8552. // Distinguish coordinates nearer to the left or right side of the box
  8553. var atLeft = x - boxAround.left < boxAround.right - x, atStart = atLeft == ltr;
  8554. ch = chAround + (atStart ? 0 : 1);
  8555. sticky = atStart ? "after" : "before";
  8556. baseX = atLeft ? boxAround.left : boxAround.right;
  8557. } else {
  8558. // (Adjust for extended bound, if necessary.)
  8559. if (!ltr && (ch == end || ch == begin)) { ch++; }
  8560. // To determine which side to associate with, get the box to the
  8561. // left of the character and compare it's vertical position to the
  8562. // coordinates
  8563. sticky = ch == 0 ? "after" : ch == lineObj.text.length ? "before" :
  8564. (measureCharPrepared(cm, preparedMeasure, ch - (ltr ? 1 : 0)).bottom + widgetHeight$$1 <= y) == ltr ?
  8565. "after" : "before";
  8566. // Now get accurate coordinates for this place, in order to get a
  8567. // base X position
  8568. var coords = cursorCoords(cm, Pos(lineNo$$1, ch, sticky), "line", lineObj, preparedMeasure);
  8569. baseX = coords.left;
  8570. outside = y < coords.top || y >= coords.bottom;
  8571. }
  8572. ch = skipExtendingChars(lineObj.text, ch, 1);
  8573. return PosWithInfo(lineNo$$1, ch, sticky, outside, x - baseX)
  8574. }
  8575. function coordsBidiPart(cm, lineObj, lineNo$$1, preparedMeasure, order, x, y) {
  8576. // Bidi parts are sorted left-to-right, and in a non-line-wrapping
  8577. // situation, we can take this ordering to correspond to the visual
  8578. // ordering. This finds the first part whose end is after the given
  8579. // coordinates.
  8580. var index = findFirst(function (i) {
  8581. var part = order[i], ltr = part.level != 1;
  8582. return boxIsAfter(cursorCoords(cm, Pos(lineNo$$1, ltr ? part.to : part.from, ltr ? "before" : "after"),
  8583. "line", lineObj, preparedMeasure), x, y, true)
  8584. }, 0, order.length - 1);
  8585. var part = order[index];
  8586. // If this isn't the first part, the part's start is also after
  8587. // the coordinates, and the coordinates aren't on the same line as
  8588. // that start, move one part back.
  8589. if (index > 0) {
  8590. var ltr = part.level != 1;
  8591. var start = cursorCoords(cm, Pos(lineNo$$1, ltr ? part.from : part.to, ltr ? "after" : "before"),
  8592. "line", lineObj, preparedMeasure);
  8593. if (boxIsAfter(start, x, y, true) && start.top > y)
  8594. { part = order[index - 1]; }
  8595. }
  8596. return part
  8597. }
  8598. function coordsBidiPartWrapped(cm, lineObj, _lineNo, preparedMeasure, order, x, y) {
  8599. // In a wrapped line, rtl text on wrapping boundaries can do things
  8600. // that don't correspond to the ordering in our `order` array at
  8601. // all, so a binary search doesn't work, and we want to return a
  8602. // part that only spans one line so that the binary search in
  8603. // coordsCharInner is safe. As such, we first find the extent of the
  8604. // wrapped line, and then do a flat search in which we discard any
  8605. // spans that aren't on the line.
  8606. var ref = wrappedLineExtent(cm, lineObj, preparedMeasure, y);
  8607. var begin = ref.begin;
  8608. var end = ref.end;
  8609. if (/\s/.test(lineObj.text.charAt(end - 1))) { end--; }
  8610. var part = null, closestDist = null;
  8611. for (var i = 0; i < order.length; i++) {
  8612. var p = order[i];
  8613. if (p.from >= end || p.to <= begin) { continue }
  8614. var ltr = p.level != 1;
  8615. var endX = measureCharPrepared(cm, preparedMeasure, ltr ? Math.min(end, p.to) - 1 : Math.max(begin, p.from)).right;
  8616. // Weigh against spans ending before this, so that they are only
  8617. // picked if nothing ends after
  8618. var dist = endX < x ? x - endX + 1e9 : endX - x;
  8619. if (!part || closestDist > dist) {
  8620. part = p;
  8621. closestDist = dist;
  8622. }
  8623. }
  8624. if (!part) { part = order[order.length - 1]; }
  8625. // Clip the part to the wrapped line.
  8626. if (part.from < begin) { part = {from: begin, to: part.to, level: part.level}; }
  8627. if (part.to > end) { part = {from: part.from, to: end, level: part.level}; }
  8628. return part
  8629. }
  8630. var measureText;
  8631. // Compute the default text height.
  8632. function textHeight(display) {
  8633. if (display.cachedTextHeight != null) { return display.cachedTextHeight }
  8634. if (measureText == null) {
  8635. measureText = elt("pre");
  8636. // Measure a bunch of lines, for browsers that compute
  8637. // fractional heights.
  8638. for (var i = 0; i < 49; ++i) {
  8639. measureText.appendChild(document.createTextNode("x"));
  8640. measureText.appendChild(elt("br"));
  8641. }
  8642. measureText.appendChild(document.createTextNode("x"));
  8643. }
  8644. removeChildrenAndAdd(display.measure, measureText);
  8645. var height = measureText.offsetHeight / 50;
  8646. if (height > 3) { display.cachedTextHeight = height; }
  8647. removeChildren(display.measure);
  8648. return height || 1
  8649. }
  8650. // Compute the default character width.
  8651. function charWidth(display) {
  8652. if (display.cachedCharWidth != null) { return display.cachedCharWidth }
  8653. var anchor = elt("span", "xxxxxxxxxx");
  8654. var pre = elt("pre", [anchor]);
  8655. removeChildrenAndAdd(display.measure, pre);
  8656. var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10;
  8657. if (width > 2) { display.cachedCharWidth = width; }
  8658. return width || 10
  8659. }
  8660. // Do a bulk-read of the DOM positions and sizes needed to draw the
  8661. // view, so that we don't interleave reading and writing to the DOM.
  8662. function getDimensions(cm) {
  8663. var d = cm.display, left = {}, width = {};
  8664. var gutterLeft = d.gutters.clientLeft;
  8665. for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) {
  8666. left[cm.options.gutters[i]] = n.offsetLeft + n.clientLeft + gutterLeft;
  8667. width[cm.options.gutters[i]] = n.clientWidth;
  8668. }
  8669. return {fixedPos: compensateForHScroll(d),
  8670. gutterTotalWidth: d.gutters.offsetWidth,
  8671. gutterLeft: left,
  8672. gutterWidth: width,
  8673. wrapperWidth: d.wrapper.clientWidth}
  8674. }
  8675. // Computes display.scroller.scrollLeft + display.gutters.offsetWidth,
  8676. // but using getBoundingClientRect to get a sub-pixel-accurate
  8677. // result.
  8678. function compensateForHScroll(display) {
  8679. return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left
  8680. }
  8681. // Returns a function that estimates the height of a line, to use as
  8682. // first approximation until the line becomes visible (and is thus
  8683. // properly measurable).
  8684. function estimateHeight(cm) {
  8685. var th = textHeight(cm.display), wrapping = cm.options.lineWrapping;
  8686. var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3);
  8687. return function (line) {
  8688. if (lineIsHidden(cm.doc, line)) { return 0 }
  8689. var widgetsHeight = 0;
  8690. if (line.widgets) { for (var i = 0; i < line.widgets.length; i++) {
  8691. if (line.widgets[i].height) { widgetsHeight += line.widgets[i].height; }
  8692. } }
  8693. if (wrapping)
  8694. { return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th }
  8695. else
  8696. { return widgetsHeight + th }
  8697. }
  8698. }
  8699. function estimateLineHeights(cm) {
  8700. var doc = cm.doc, est = estimateHeight(cm);
  8701. doc.iter(function (line) {
  8702. var estHeight = est(line);
  8703. if (estHeight != line.height) { updateLineHeight(line, estHeight); }
  8704. });
  8705. }
  8706. // Given a mouse event, find the corresponding position. If liberal
  8707. // is false, it checks whether a gutter or scrollbar was clicked,
  8708. // and returns null if it was. forRect is used by rectangular
  8709. // selections, and tries to estimate a character position even for
  8710. // coordinates beyond the right of the text.
  8711. function posFromMouse(cm, e, liberal, forRect) {
  8712. var display = cm.display;
  8713. if (!liberal && e_target(e).getAttribute("cm-not-content") == "true") { return null }
  8714. var x, y, space = display.lineSpace.getBoundingClientRect();
  8715. // Fails unpredictably on IE[67] when mouse is dragged around quickly.
  8716. try { x = e.clientX - space.left; y = e.clientY - space.top; }
  8717. catch (e) { return null }
  8718. var coords = coordsChar(cm, x, y), line;
  8719. if (forRect && coords.xRel == 1 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) {
  8720. var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length;
  8721. coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff));
  8722. }
  8723. return coords
  8724. }
  8725. // Find the view element corresponding to a given line. Return null
  8726. // when the line isn't visible.
  8727. function findViewIndex(cm, n) {
  8728. if (n >= cm.display.viewTo) { return null }
  8729. n -= cm.display.viewFrom;
  8730. if (n < 0) { return null }
  8731. var view = cm.display.view;
  8732. for (var i = 0; i < view.length; i++) {
  8733. n -= view[i].size;
  8734. if (n < 0) { return i }
  8735. }
  8736. }
  8737. function updateSelection(cm) {
  8738. cm.display.input.showSelection(cm.display.input.prepareSelection());
  8739. }
  8740. function prepareSelection(cm, primary) {
  8741. if ( primary === void 0 ) primary = true;
  8742. var doc = cm.doc, result = {};
  8743. var curFragment = result.cursors = document.createDocumentFragment();
  8744. var selFragment = result.selection = document.createDocumentFragment();
  8745. for (var i = 0; i < doc.sel.ranges.length; i++) {
  8746. if (!primary && i == doc.sel.primIndex) { continue }
  8747. var range$$1 = doc.sel.ranges[i];
  8748. if (range$$1.from().line >= cm.display.viewTo || range$$1.to().line < cm.display.viewFrom) { continue }
  8749. var collapsed = range$$1.empty();
  8750. if (collapsed || cm.options.showCursorWhenSelecting)
  8751. { drawSelectionCursor(cm, range$$1.head, curFragment); }
  8752. if (!collapsed)
  8753. { drawSelectionRange(cm, range$$1, selFragment); }
  8754. }
  8755. return result
  8756. }
  8757. // Draws a cursor for the given range
  8758. function drawSelectionCursor(cm, head, output) {
  8759. var pos = cursorCoords(cm, head, "div", null, null, !cm.options.singleCursorHeightPerLine);
  8760. var cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor"));
  8761. cursor.style.left = pos.left + "px";
  8762. cursor.style.top = pos.top + "px";
  8763. cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px";
  8764. if (pos.other) {
  8765. // Secondary cursor, shown when on a 'jump' in bi-directional text
  8766. var otherCursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor"));
  8767. otherCursor.style.display = "";
  8768. otherCursor.style.left = pos.other.left + "px";
  8769. otherCursor.style.top = pos.other.top + "px";
  8770. otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px";
  8771. }
  8772. }
  8773. function cmpCoords(a, b) { return a.top - b.top || a.left - b.left }
  8774. // Draws the given range as a highlighted selection
  8775. function drawSelectionRange(cm, range$$1, output) {
  8776. var display = cm.display, doc = cm.doc;
  8777. var fragment = document.createDocumentFragment();
  8778. var padding = paddingH(cm.display), leftSide = padding.left;
  8779. var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right;
  8780. var docLTR = doc.direction == "ltr";
  8781. function add(left, top, width, bottom) {
  8782. if (top < 0) { top = 0; }
  8783. top = Math.round(top);
  8784. bottom = Math.round(bottom);
  8785. 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")));
  8786. }
  8787. function drawForLine(line, fromArg, toArg) {
  8788. var lineObj = getLine(doc, line);
  8789. var lineLen = lineObj.text.length;
  8790. var start, end;
  8791. function coords(ch, bias) {
  8792. return charCoords(cm, Pos(line, ch), "div", lineObj, bias)
  8793. }
  8794. function wrapX(pos, dir, side) {
  8795. var extent = wrappedLineExtentChar(cm, lineObj, null, pos);
  8796. var prop = (dir == "ltr") == (side == "after") ? "left" : "right";
  8797. var ch = side == "after" ? extent.begin : extent.end - (/\s/.test(lineObj.text.charAt(extent.end - 1)) ? 2 : 1);
  8798. return coords(ch, prop)[prop]
  8799. }
  8800. var order = getOrder(lineObj, doc.direction);
  8801. iterateBidiSections(order, fromArg || 0, toArg == null ? lineLen : toArg, function (from, to, dir, i) {
  8802. var ltr = dir == "ltr";
  8803. var fromPos = coords(from, ltr ? "left" : "right");
  8804. var toPos = coords(to - 1, ltr ? "right" : "left");
  8805. var openStart = fromArg == null && from == 0, openEnd = toArg == null && to == lineLen;
  8806. var first = i == 0, last = !order || i == order.length - 1;
  8807. if (toPos.top - fromPos.top <= 3) { // Single line
  8808. var openLeft = (docLTR ? openStart : openEnd) && first;
  8809. var openRight = (docLTR ? openEnd : openStart) && last;
  8810. var left = openLeft ? leftSide : (ltr ? fromPos : toPos).left;
  8811. var right = openRight ? rightSide : (ltr ? toPos : fromPos).right;
  8812. add(left, fromPos.top, right - left, fromPos.bottom);
  8813. } else { // Multiple lines
  8814. var topLeft, topRight, botLeft, botRight;
  8815. if (ltr) {
  8816. topLeft = docLTR && openStart && first ? leftSide : fromPos.left;
  8817. topRight = docLTR ? rightSide : wrapX(from, dir, "before");
  8818. botLeft = docLTR ? leftSide : wrapX(to, dir, "after");
  8819. botRight = docLTR && openEnd && last ? rightSide : toPos.right;
  8820. } else {
  8821. topLeft = !docLTR ? leftSide : wrapX(from, dir, "before");
  8822. topRight = !docLTR && openStart && first ? rightSide : fromPos.right;
  8823. botLeft = !docLTR && openEnd && last ? leftSide : toPos.left;
  8824. botRight = !docLTR ? rightSide : wrapX(to, dir, "after");
  8825. }
  8826. add(topLeft, fromPos.top, topRight - topLeft, fromPos.bottom);
  8827. if (fromPos.bottom < toPos.top) { add(leftSide, fromPos.bottom, null, toPos.top); }
  8828. add(botLeft, toPos.top, botRight - botLeft, toPos.bottom);
  8829. }
  8830. if (!start || cmpCoords(fromPos, start) < 0) { start = fromPos; }
  8831. if (cmpCoords(toPos, start) < 0) { start = toPos; }
  8832. if (!end || cmpCoords(fromPos, end) < 0) { end = fromPos; }
  8833. if (cmpCoords(toPos, end) < 0) { end = toPos; }
  8834. });
  8835. return {start: start, end: end}
  8836. }
  8837. var sFrom = range$$1.from(), sTo = range$$1.to();
  8838. if (sFrom.line == sTo.line) {
  8839. drawForLine(sFrom.line, sFrom.ch, sTo.ch);
  8840. } else {
  8841. var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line);
  8842. var singleVLine = visualLine(fromLine) == visualLine(toLine);
  8843. var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end;
  8844. var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start;
  8845. if (singleVLine) {
  8846. if (leftEnd.top < rightStart.top - 2) {
  8847. add(leftEnd.right, leftEnd.top, null, leftEnd.bottom);
  8848. add(leftSide, rightStart.top, rightStart.left, rightStart.bottom);
  8849. } else {
  8850. add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom);
  8851. }
  8852. }
  8853. if (leftEnd.bottom < rightStart.top)
  8854. { add(leftSide, leftEnd.bottom, null, rightStart.top); }
  8855. }
  8856. output.appendChild(fragment);
  8857. }
  8858. // Cursor-blinking
  8859. function restartBlink(cm) {
  8860. if (!cm.state.focused) { return }
  8861. var display = cm.display;
  8862. clearInterval(display.blinker);
  8863. var on = true;
  8864. display.cursorDiv.style.visibility = "";
  8865. if (cm.options.cursorBlinkRate > 0)
  8866. { display.blinker = setInterval(function () { return display.cursorDiv.style.visibility = (on = !on) ? "" : "hidden"; },
  8867. cm.options.cursorBlinkRate); }
  8868. else if (cm.options.cursorBlinkRate < 0)
  8869. { display.cursorDiv.style.visibility = "hidden"; }
  8870. }
  8871. function ensureFocus(cm) {
  8872. if (!cm.state.focused) { cm.display.input.focus(); onFocus(cm); }
  8873. }
  8874. function delayBlurEvent(cm) {
  8875. cm.state.delayingBlurEvent = true;
  8876. setTimeout(function () { if (cm.state.delayingBlurEvent) {
  8877. cm.state.delayingBlurEvent = false;
  8878. onBlur(cm);
  8879. } }, 100);
  8880. }
  8881. function onFocus(cm, e) {
  8882. if (cm.state.delayingBlurEvent) { cm.state.delayingBlurEvent = false; }
  8883. if (cm.options.readOnly == "nocursor") { return }
  8884. if (!cm.state.focused) {
  8885. signal(cm, "focus", cm, e);
  8886. cm.state.focused = true;
  8887. addClass(cm.display.wrapper, "CodeMirror-focused");
  8888. // This test prevents this from firing when a context
  8889. // menu is closed (since the input reset would kill the
  8890. // select-all detection hack)
  8891. if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) {
  8892. cm.display.input.reset();
  8893. if (webkit) { setTimeout(function () { return cm.display.input.reset(true); }, 20); } // Issue #1730
  8894. }
  8895. cm.display.input.receivedFocus();
  8896. }
  8897. restartBlink(cm);
  8898. }
  8899. function onBlur(cm, e) {
  8900. if (cm.state.delayingBlurEvent) { return }
  8901. if (cm.state.focused) {
  8902. signal(cm, "blur", cm, e);
  8903. cm.state.focused = false;
  8904. rmClass(cm.display.wrapper, "CodeMirror-focused");
  8905. }
  8906. clearInterval(cm.display.blinker);
  8907. setTimeout(function () { if (!cm.state.focused) { cm.display.shift = false; } }, 150);
  8908. }
  8909. // Read the actual heights of the rendered lines, and update their
  8910. // stored heights to match.
  8911. function updateHeightsInViewport(cm) {
  8912. var display = cm.display;
  8913. var prevBottom = display.lineDiv.offsetTop;
  8914. for (var i = 0; i < display.view.length; i++) {
  8915. var cur = display.view[i], height = (void 0);
  8916. if (cur.hidden) { continue }
  8917. if (ie && ie_version < 8) {
  8918. var bot = cur.node.offsetTop + cur.node.offsetHeight;
  8919. height = bot - prevBottom;
  8920. prevBottom = bot;
  8921. } else {
  8922. var box = cur.node.getBoundingClientRect();
  8923. height = box.bottom - box.top;
  8924. }
  8925. var diff = cur.line.height - height;
  8926. if (height < 2) { height = textHeight(display); }
  8927. if (diff > .005 || diff < -.005) {
  8928. updateLineHeight(cur.line, height);
  8929. updateWidgetHeight(cur.line);
  8930. if (cur.rest) { for (var j = 0; j < cur.rest.length; j++)
  8931. { updateWidgetHeight(cur.rest[j]); } }
  8932. }
  8933. }
  8934. }
  8935. // Read and store the height of line widgets associated with the
  8936. // given line.
  8937. function updateWidgetHeight(line) {
  8938. if (line.widgets) { for (var i = 0; i < line.widgets.length; ++i) {
  8939. var w = line.widgets[i], parent = w.node.parentNode;
  8940. if (parent) { w.height = parent.offsetHeight; }
  8941. } }
  8942. }
  8943. // Compute the lines that are visible in a given viewport (defaults
  8944. // the the current scroll position). viewport may contain top,
  8945. // height, and ensure (see op.scrollToPos) properties.
  8946. function visibleLines(display, doc, viewport) {
  8947. var top = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop;
  8948. top = Math.floor(top - paddingTop(display));
  8949. var bottom = viewport && viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight;
  8950. var from = lineAtHeight(doc, top), to = lineAtHeight(doc, bottom);
  8951. // Ensure is a {from: {line, ch}, to: {line, ch}} object, and
  8952. // forces those lines into the viewport (if possible).
  8953. if (viewport && viewport.ensure) {
  8954. var ensureFrom = viewport.ensure.from.line, ensureTo = viewport.ensure.to.line;
  8955. if (ensureFrom < from) {
  8956. from = ensureFrom;
  8957. to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight);
  8958. } else if (Math.min(ensureTo, doc.lastLine()) >= to) {
  8959. from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight);
  8960. to = ensureTo;
  8961. }
  8962. }
  8963. return {from: from, to: Math.max(to, from + 1)}
  8964. }
  8965. // Re-align line numbers and gutter marks to compensate for
  8966. // horizontal scrolling.
  8967. function alignHorizontally(cm) {
  8968. var display = cm.display, view = display.view;
  8969. if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) { return }
  8970. var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft;
  8971. var gutterW = display.gutters.offsetWidth, left = comp + "px";
  8972. for (var i = 0; i < view.length; i++) { if (!view[i].hidden) {
  8973. if (cm.options.fixedGutter) {
  8974. if (view[i].gutter)
  8975. { view[i].gutter.style.left = left; }
  8976. if (view[i].gutterBackground)
  8977. { view[i].gutterBackground.style.left = left; }
  8978. }
  8979. var align = view[i].alignable;
  8980. if (align) { for (var j = 0; j < align.length; j++)
  8981. { align[j].style.left = left; } }
  8982. } }
  8983. if (cm.options.fixedGutter)
  8984. { display.gutters.style.left = (comp + gutterW) + "px"; }
  8985. }
  8986. // Used to ensure that the line number gutter is still the right
  8987. // size for the current document size. Returns true when an update
  8988. // is needed.
  8989. function maybeUpdateLineNumberWidth(cm) {
  8990. if (!cm.options.lineNumbers) { return false }
  8991. var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display;
  8992. if (last.length != display.lineNumChars) {
  8993. var test = display.measure.appendChild(elt("div", [elt("div", last)],
  8994. "CodeMirror-linenumber CodeMirror-gutter-elt"));
  8995. var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW;
  8996. display.lineGutter.style.width = "";
  8997. display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding) + 1;
  8998. display.lineNumWidth = display.lineNumInnerWidth + padding;
  8999. display.lineNumChars = display.lineNumInnerWidth ? last.length : -1;
  9000. display.lineGutter.style.width = display.lineNumWidth + "px";
  9001. updateGutterSpace(cm);
  9002. return true
  9003. }
  9004. return false
  9005. }
  9006. // SCROLLING THINGS INTO VIEW
  9007. // If an editor sits on the top or bottom of the window, partially
  9008. // scrolled out of view, this ensures that the cursor is visible.
  9009. function maybeScrollWindow(cm, rect) {
  9010. if (signalDOMEvent(cm, "scrollCursorIntoView")) { return }
  9011. var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null;
  9012. if (rect.top + box.top < 0) { doScroll = true; }
  9013. else if (rect.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) { doScroll = false; }
  9014. if (doScroll != null && !phantom) {
  9015. 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;"));
  9016. cm.display.lineSpace.appendChild(scrollNode);
  9017. scrollNode.scrollIntoView(doScroll);
  9018. cm.display.lineSpace.removeChild(scrollNode);
  9019. }
  9020. }
  9021. // Scroll a given position into view (immediately), verifying that
  9022. // it actually became visible (as line heights are accurately
  9023. // measured, the position of something may 'drift' during drawing).
  9024. function scrollPosIntoView(cm, pos, end, margin) {
  9025. if (margin == null) { margin = 0; }
  9026. var rect;
  9027. if (!cm.options.lineWrapping && pos == end) {
  9028. // Set pos and end to the cursor positions around the character pos sticks to
  9029. // If pos.sticky == "before", that is around pos.ch - 1, otherwise around pos.ch
  9030. // If pos == Pos(_, 0, "before"), pos and end are unchanged
  9031. pos = pos.ch ? Pos(pos.line, pos.sticky == "before" ? pos.ch - 1 : pos.ch, "after") : pos;
  9032. end = pos.sticky == "before" ? Pos(pos.line, pos.ch + 1, "before") : pos;
  9033. }
  9034. for (var limit = 0; limit < 5; limit++) {
  9035. var changed = false;
  9036. var coords = cursorCoords(cm, pos);
  9037. var endCoords = !end || end == pos ? coords : cursorCoords(cm, end);
  9038. rect = {left: Math.min(coords.left, endCoords.left),
  9039. top: Math.min(coords.top, endCoords.top) - margin,
  9040. right: Math.max(coords.left, endCoords.left),
  9041. bottom: Math.max(coords.bottom, endCoords.bottom) + margin};
  9042. var scrollPos = calculateScrollPos(cm, rect);
  9043. var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft;
  9044. if (scrollPos.scrollTop != null) {
  9045. updateScrollTop(cm, scrollPos.scrollTop);
  9046. if (Math.abs(cm.doc.scrollTop - startTop) > 1) { changed = true; }
  9047. }
  9048. if (scrollPos.scrollLeft != null) {
  9049. setScrollLeft(cm, scrollPos.scrollLeft);
  9050. if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) { changed = true; }
  9051. }
  9052. if (!changed) { break }
  9053. }
  9054. return rect
  9055. }
  9056. // Scroll a given set of coordinates into view (immediately).
  9057. function scrollIntoView(cm, rect) {
  9058. var scrollPos = calculateScrollPos(cm, rect);
  9059. if (scrollPos.scrollTop != null) { updateScrollTop(cm, scrollPos.scrollTop); }
  9060. if (scrollPos.scrollLeft != null) { setScrollLeft(cm, scrollPos.scrollLeft); }
  9061. }
  9062. // Calculate a new scroll position needed to scroll the given
  9063. // rectangle into view. Returns an object with scrollTop and
  9064. // scrollLeft properties. When these are undefined, the
  9065. // vertical/horizontal position does not need to be adjusted.
  9066. function calculateScrollPos(cm, rect) {
  9067. var display = cm.display, snapMargin = textHeight(cm.display);
  9068. if (rect.top < 0) { rect.top = 0; }
  9069. var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop;
  9070. var screen = displayHeight(cm), result = {};
  9071. if (rect.bottom - rect.top > screen) { rect.bottom = rect.top + screen; }
  9072. var docBottom = cm.doc.height + paddingVert(display);
  9073. var atTop = rect.top < snapMargin, atBottom = rect.bottom > docBottom - snapMargin;
  9074. if (rect.top < screentop) {
  9075. result.scrollTop = atTop ? 0 : rect.top;
  9076. } else if (rect.bottom > screentop + screen) {
  9077. var newTop = Math.min(rect.top, (atBottom ? docBottom : rect.bottom) - screen);
  9078. if (newTop != screentop) { result.scrollTop = newTop; }
  9079. }
  9080. var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft;
  9081. var screenw = displayWidth(cm) - (cm.options.fixedGutter ? display.gutters.offsetWidth : 0);
  9082. var tooWide = rect.right - rect.left > screenw;
  9083. if (tooWide) { rect.right = rect.left + screenw; }
  9084. if (rect.left < 10)
  9085. { result.scrollLeft = 0; }
  9086. else if (rect.left < screenleft)
  9087. { result.scrollLeft = Math.max(0, rect.left - (tooWide ? 0 : 10)); }
  9088. else if (rect.right > screenw + screenleft - 3)
  9089. { result.scrollLeft = rect.right + (tooWide ? 0 : 10) - screenw; }
  9090. return result
  9091. }
  9092. // Store a relative adjustment to the scroll position in the current
  9093. // operation (to be applied when the operation finishes).
  9094. function addToScrollTop(cm, top) {
  9095. if (top == null) { return }
  9096. resolveScrollToPos(cm);
  9097. cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top;
  9098. }
  9099. // Make sure that at the end of the operation the current cursor is
  9100. // shown.
  9101. function ensureCursorVisible(cm) {
  9102. resolveScrollToPos(cm);
  9103. var cur = cm.getCursor();
  9104. cm.curOp.scrollToPos = {from: cur, to: cur, margin: cm.options.cursorScrollMargin};
  9105. }
  9106. function scrollToCoords(cm, x, y) {
  9107. if (x != null || y != null) { resolveScrollToPos(cm); }
  9108. if (x != null) { cm.curOp.scrollLeft = x; }
  9109. if (y != null) { cm.curOp.scrollTop = y; }
  9110. }
  9111. function scrollToRange(cm, range$$1) {
  9112. resolveScrollToPos(cm);
  9113. cm.curOp.scrollToPos = range$$1;
  9114. }
  9115. // When an operation has its scrollToPos property set, and another
  9116. // scroll action is applied before the end of the operation, this
  9117. // 'simulates' scrolling that position into view in a cheap way, so
  9118. // that the effect of intermediate scroll commands is not ignored.
  9119. function resolveScrollToPos(cm) {
  9120. var range$$1 = cm.curOp.scrollToPos;
  9121. if (range$$1) {
  9122. cm.curOp.scrollToPos = null;
  9123. var from = estimateCoords(cm, range$$1.from), to = estimateCoords(cm, range$$1.to);
  9124. scrollToCoordsRange(cm, from, to, range$$1.margin);
  9125. }
  9126. }
  9127. function scrollToCoordsRange(cm, from, to, margin) {
  9128. var sPos = calculateScrollPos(cm, {
  9129. left: Math.min(from.left, to.left),
  9130. top: Math.min(from.top, to.top) - margin,
  9131. right: Math.max(from.right, to.right),
  9132. bottom: Math.max(from.bottom, to.bottom) + margin
  9133. });
  9134. scrollToCoords(cm, sPos.scrollLeft, sPos.scrollTop);
  9135. }
  9136. // Sync the scrollable area and scrollbars, ensure the viewport
  9137. // covers the visible area.
  9138. function updateScrollTop(cm, val) {
  9139. if (Math.abs(cm.doc.scrollTop - val) < 2) { return }
  9140. if (!gecko) { updateDisplaySimple(cm, {top: val}); }
  9141. setScrollTop(cm, val, true);
  9142. if (gecko) { updateDisplaySimple(cm); }
  9143. startWorker(cm, 100);
  9144. }
  9145. function setScrollTop(cm, val, forceScroll) {
  9146. val = Math.min(cm.display.scroller.scrollHeight - cm.display.scroller.clientHeight, val);
  9147. if (cm.display.scroller.scrollTop == val && !forceScroll) { return }
  9148. cm.doc.scrollTop = val;
  9149. cm.display.scrollbars.setScrollTop(val);
  9150. if (cm.display.scroller.scrollTop != val) { cm.display.scroller.scrollTop = val; }
  9151. }
  9152. // Sync scroller and scrollbar, ensure the gutter elements are
  9153. // aligned.
  9154. function setScrollLeft(cm, val, isScroller, forceScroll) {
  9155. val = Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth);
  9156. if ((isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) && !forceScroll) { return }
  9157. cm.doc.scrollLeft = val;
  9158. alignHorizontally(cm);
  9159. if (cm.display.scroller.scrollLeft != val) { cm.display.scroller.scrollLeft = val; }
  9160. cm.display.scrollbars.setScrollLeft(val);
  9161. }
  9162. // SCROLLBARS
  9163. // Prepare DOM reads needed to update the scrollbars. Done in one
  9164. // shot to minimize update/measure roundtrips.
  9165. function measureForScrollbars(cm) {
  9166. var d = cm.display, gutterW = d.gutters.offsetWidth;
  9167. var docH = Math.round(cm.doc.height + paddingVert(cm.display));
  9168. return {
  9169. clientHeight: d.scroller.clientHeight,
  9170. viewHeight: d.wrapper.clientHeight,
  9171. scrollWidth: d.scroller.scrollWidth, clientWidth: d.scroller.clientWidth,
  9172. viewWidth: d.wrapper.clientWidth,
  9173. barLeft: cm.options.fixedGutter ? gutterW : 0,
  9174. docHeight: docH,
  9175. scrollHeight: docH + scrollGap(cm) + d.barHeight,
  9176. nativeBarWidth: d.nativeBarWidth,
  9177. gutterWidth: gutterW
  9178. }
  9179. }
  9180. var NativeScrollbars = function(place, scroll, cm) {
  9181. this.cm = cm;
  9182. var vert = this.vert = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar");
  9183. var horiz = this.horiz = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar");
  9184. place(vert); place(horiz);
  9185. on(vert, "scroll", function () {
  9186. if (vert.clientHeight) { scroll(vert.scrollTop, "vertical"); }
  9187. });
  9188. on(horiz, "scroll", function () {
  9189. if (horiz.clientWidth) { scroll(horiz.scrollLeft, "horizontal"); }
  9190. });
  9191. this.checkedZeroWidth = false;
  9192. // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8).
  9193. if (ie && ie_version < 8) { this.horiz.style.minHeight = this.vert.style.minWidth = "18px"; }
  9194. };
  9195. NativeScrollbars.prototype.update = function (measure) {
  9196. var needsH = measure.scrollWidth > measure.clientWidth + 1;
  9197. var needsV = measure.scrollHeight > measure.clientHeight + 1;
  9198. var sWidth = measure.nativeBarWidth;
  9199. if (needsV) {
  9200. this.vert.style.display = "block";
  9201. this.vert.style.bottom = needsH ? sWidth + "px" : "0";
  9202. var totalHeight = measure.viewHeight - (needsH ? sWidth : 0);
  9203. // A bug in IE8 can cause this value to be negative, so guard it.
  9204. this.vert.firstChild.style.height =
  9205. Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + "px";
  9206. } else {
  9207. this.vert.style.display = "";
  9208. this.vert.firstChild.style.height = "0";
  9209. }
  9210. if (needsH) {
  9211. this.horiz.style.display = "block";
  9212. this.horiz.style.right = needsV ? sWidth + "px" : "0";
  9213. this.horiz.style.left = measure.barLeft + "px";
  9214. var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0);
  9215. this.horiz.firstChild.style.width =
  9216. Math.max(0, measure.scrollWidth - measure.clientWidth + totalWidth) + "px";
  9217. } else {
  9218. this.horiz.style.display = "";
  9219. this.horiz.firstChild.style.width = "0";
  9220. }
  9221. if (!this.checkedZeroWidth && measure.clientHeight > 0) {
  9222. if (sWidth == 0) { this.zeroWidthHack(); }
  9223. this.checkedZeroWidth = true;
  9224. }
  9225. return {right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0}
  9226. };
  9227. NativeScrollbars.prototype.setScrollLeft = function (pos) {
  9228. if (this.horiz.scrollLeft != pos) { this.horiz.scrollLeft = pos; }
  9229. if (this.disableHoriz) { this.enableZeroWidthBar(this.horiz, this.disableHoriz, "horiz"); }
  9230. };
  9231. NativeScrollbars.prototype.setScrollTop = function (pos) {
  9232. if (this.vert.scrollTop != pos) { this.vert.scrollTop = pos; }
  9233. if (this.disableVert) { this.enableZeroWidthBar(this.vert, this.disableVert, "vert"); }
  9234. };
  9235. NativeScrollbars.prototype.zeroWidthHack = function () {
  9236. var w = mac && !mac_geMountainLion ? "12px" : "18px";
  9237. this.horiz.style.height = this.vert.style.width = w;
  9238. this.horiz.style.pointerEvents = this.vert.style.pointerEvents = "none";
  9239. this.disableHoriz = new Delayed;
  9240. this.disableVert = new Delayed;
  9241. };
  9242. NativeScrollbars.prototype.enableZeroWidthBar = function (bar, delay, type) {
  9243. bar.style.pointerEvents = "auto";
  9244. function maybeDisable() {
  9245. // To find out whether the scrollbar is still visible, we
  9246. // check whether the element under the pixel in the bottom
  9247. // right corner of the scrollbar box is the scrollbar box
  9248. // itself (when the bar is still visible) or its filler child
  9249. // (when the bar is hidden). If it is still visible, we keep
  9250. // it enabled, if it's hidden, we disable pointer events.
  9251. var box = bar.getBoundingClientRect();
  9252. var elt$$1 = type == "vert" ? document.elementFromPoint(box.right - 1, (box.top + box.bottom) / 2)
  9253. : document.elementFromPoint((box.right + box.left) / 2, box.bottom - 1);
  9254. if (elt$$1 != bar) { bar.style.pointerEvents = "none"; }
  9255. else { delay.set(1000, maybeDisable); }
  9256. }
  9257. delay.set(1000, maybeDisable);
  9258. };
  9259. NativeScrollbars.prototype.clear = function () {
  9260. var parent = this.horiz.parentNode;
  9261. parent.removeChild(this.horiz);
  9262. parent.removeChild(this.vert);
  9263. };
  9264. var NullScrollbars = function () {};
  9265. NullScrollbars.prototype.update = function () { return {bottom: 0, right: 0} };
  9266. NullScrollbars.prototype.setScrollLeft = function () {};
  9267. NullScrollbars.prototype.setScrollTop = function () {};
  9268. NullScrollbars.prototype.clear = function () {};
  9269. function updateScrollbars(cm, measure) {
  9270. if (!measure) { measure = measureForScrollbars(cm); }
  9271. var startWidth = cm.display.barWidth, startHeight = cm.display.barHeight;
  9272. updateScrollbarsInner(cm, measure);
  9273. for (var i = 0; i < 4 && startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i++) {
  9274. if (startWidth != cm.display.barWidth && cm.options.lineWrapping)
  9275. { updateHeightsInViewport(cm); }
  9276. updateScrollbarsInner(cm, measureForScrollbars(cm));
  9277. startWidth = cm.display.barWidth; startHeight = cm.display.barHeight;
  9278. }
  9279. }
  9280. // Re-synchronize the fake scrollbars with the actual size of the
  9281. // content.
  9282. function updateScrollbarsInner(cm, measure) {
  9283. var d = cm.display;
  9284. var sizes = d.scrollbars.update(measure);
  9285. d.sizer.style.paddingRight = (d.barWidth = sizes.right) + "px";
  9286. d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + "px";
  9287. d.heightForcer.style.borderBottom = sizes.bottom + "px solid transparent";
  9288. if (sizes.right && sizes.bottom) {
  9289. d.scrollbarFiller.style.display = "block";
  9290. d.scrollbarFiller.style.height = sizes.bottom + "px";
  9291. d.scrollbarFiller.style.width = sizes.right + "px";
  9292. } else { d.scrollbarFiller.style.display = ""; }
  9293. if (sizes.bottom && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) {
  9294. d.gutterFiller.style.display = "block";
  9295. d.gutterFiller.style.height = sizes.bottom + "px";
  9296. d.gutterFiller.style.width = measure.gutterWidth + "px";
  9297. } else { d.gutterFiller.style.display = ""; }
  9298. }
  9299. var scrollbarModel = {"native": NativeScrollbars, "null": NullScrollbars};
  9300. function initScrollbars(cm) {
  9301. if (cm.display.scrollbars) {
  9302. cm.display.scrollbars.clear();
  9303. if (cm.display.scrollbars.addClass)
  9304. { rmClass(cm.display.wrapper, cm.display.scrollbars.addClass); }
  9305. }
  9306. cm.display.scrollbars = new scrollbarModel[cm.options.scrollbarStyle](function (node) {
  9307. cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller);
  9308. // Prevent clicks in the scrollbars from killing focus
  9309. on(node, "mousedown", function () {
  9310. if (cm.state.focused) { setTimeout(function () { return cm.display.input.focus(); }, 0); }
  9311. });
  9312. node.setAttribute("cm-not-content", "true");
  9313. }, function (pos, axis) {
  9314. if (axis == "horizontal") { setScrollLeft(cm, pos); }
  9315. else { updateScrollTop(cm, pos); }
  9316. }, cm);
  9317. if (cm.display.scrollbars.addClass)
  9318. { addClass(cm.display.wrapper, cm.display.scrollbars.addClass); }
  9319. }
  9320. // Operations are used to wrap a series of changes to the editor
  9321. // state in such a way that each change won't have to update the
  9322. // cursor and display (which would be awkward, slow, and
  9323. // error-prone). Instead, display updates are batched and then all
  9324. // combined and executed at once.
  9325. var nextOpId = 0;
  9326. // Start a new operation.
  9327. function startOperation(cm) {
  9328. cm.curOp = {
  9329. cm: cm,
  9330. viewChanged: false, // Flag that indicates that lines might need to be redrawn
  9331. startHeight: cm.doc.height, // Used to detect need to update scrollbar
  9332. forceUpdate: false, // Used to force a redraw
  9333. updateInput: null, // Whether to reset the input textarea
  9334. typing: false, // Whether this reset should be careful to leave existing text (for compositing)
  9335. changeObjs: null, // Accumulated changes, for firing change events
  9336. cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on
  9337. cursorActivityCalled: 0, // Tracks which cursorActivity handlers have been called already
  9338. selectionChanged: false, // Whether the selection needs to be redrawn
  9339. updateMaxLine: false, // Set when the widest line needs to be determined anew
  9340. scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet
  9341. scrollToPos: null, // Used to scroll to a specific position
  9342. focus: false,
  9343. id: ++nextOpId // Unique ID
  9344. };
  9345. pushOperation(cm.curOp);
  9346. }
  9347. // Finish an operation, updating the display and signalling delayed events
  9348. function endOperation(cm) {
  9349. var op = cm.curOp;
  9350. finishOperation(op, function (group) {
  9351. for (var i = 0; i < group.ops.length; i++)
  9352. { group.ops[i].cm.curOp = null; }
  9353. endOperations(group);
  9354. });
  9355. }
  9356. // The DOM updates done when an operation finishes are batched so
  9357. // that the minimum number of relayouts are required.
  9358. function endOperations(group) {
  9359. var ops = group.ops;
  9360. for (var i = 0; i < ops.length; i++) // Read DOM
  9361. { endOperation_R1(ops[i]); }
  9362. for (var i$1 = 0; i$1 < ops.length; i$1++) // Write DOM (maybe)
  9363. { endOperation_W1(ops[i$1]); }
  9364. for (var i$2 = 0; i$2 < ops.length; i$2++) // Read DOM
  9365. { endOperation_R2(ops[i$2]); }
  9366. for (var i$3 = 0; i$3 < ops.length; i$3++) // Write DOM (maybe)
  9367. { endOperation_W2(ops[i$3]); }
  9368. for (var i$4 = 0; i$4 < ops.length; i$4++) // Read DOM
  9369. { endOperation_finish(ops[i$4]); }
  9370. }
  9371. function endOperation_R1(op) {
  9372. var cm = op.cm, display = cm.display;
  9373. maybeClipScrollbars(cm);
  9374. if (op.updateMaxLine) { findMaxLine(cm); }
  9375. op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null ||
  9376. op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom ||
  9377. op.scrollToPos.to.line >= display.viewTo) ||
  9378. display.maxLineChanged && cm.options.lineWrapping;
  9379. op.update = op.mustUpdate &&
  9380. new DisplayUpdate(cm, op.mustUpdate && {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate);
  9381. }
  9382. function endOperation_W1(op) {
  9383. op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update);
  9384. }
  9385. function endOperation_R2(op) {
  9386. var cm = op.cm, display = cm.display;
  9387. if (op.updatedDisplay) { updateHeightsInViewport(cm); }
  9388. op.barMeasure = measureForScrollbars(cm);
  9389. // If the max line changed since it was last measured, measure it,
  9390. // and ensure the document's width matches it.
  9391. // updateDisplay_W2 will use these properties to do the actual resizing
  9392. if (display.maxLineChanged && !cm.options.lineWrapping) {
  9393. op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3;
  9394. cm.display.sizerWidth = op.adjustWidthTo;
  9395. op.barMeasure.scrollWidth =
  9396. Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth);
  9397. op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm));
  9398. }
  9399. if (op.updatedDisplay || op.selectionChanged)
  9400. { op.preparedSelection = display.input.prepareSelection(); }
  9401. }
  9402. function endOperation_W2(op) {
  9403. var cm = op.cm;
  9404. if (op.adjustWidthTo != null) {
  9405. cm.display.sizer.style.minWidth = op.adjustWidthTo + "px";
  9406. if (op.maxScrollLeft < cm.doc.scrollLeft)
  9407. { setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true); }
  9408. cm.display.maxLineChanged = false;
  9409. }
  9410. var takeFocus = op.focus && op.focus == activeElt();
  9411. if (op.preparedSelection)
  9412. { cm.display.input.showSelection(op.preparedSelection, takeFocus); }
  9413. if (op.updatedDisplay || op.startHeight != cm.doc.height)
  9414. { updateScrollbars(cm, op.barMeasure); }
  9415. if (op.updatedDisplay)
  9416. { setDocumentHeight(cm, op.barMeasure); }
  9417. if (op.selectionChanged) { restartBlink(cm); }
  9418. if (cm.state.focused && op.updateInput)
  9419. { cm.display.input.reset(op.typing); }
  9420. if (takeFocus) { ensureFocus(op.cm); }
  9421. }
  9422. function endOperation_finish(op) {
  9423. var cm = op.cm, display = cm.display, doc = cm.doc;
  9424. if (op.updatedDisplay) { postUpdateDisplay(cm, op.update); }
  9425. // Abort mouse wheel delta measurement, when scrolling explicitly
  9426. if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos))
  9427. { display.wheelStartX = display.wheelStartY = null; }
  9428. // Propagate the scroll position to the actual DOM scroller
  9429. if (op.scrollTop != null) { setScrollTop(cm, op.scrollTop, op.forceScroll); }
  9430. if (op.scrollLeft != null) { setScrollLeft(cm, op.scrollLeft, true, true); }
  9431. // If we need to scroll a specific position into view, do so.
  9432. if (op.scrollToPos) {
  9433. var rect = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from),
  9434. clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin);
  9435. maybeScrollWindow(cm, rect);
  9436. }
  9437. // Fire events for markers that are hidden/unidden by editing or
  9438. // undoing
  9439. var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers;
  9440. if (hidden) { for (var i = 0; i < hidden.length; ++i)
  9441. { if (!hidden[i].lines.length) { signal(hidden[i], "hide"); } } }
  9442. if (unhidden) { for (var i$1 = 0; i$1 < unhidden.length; ++i$1)
  9443. { if (unhidden[i$1].lines.length) { signal(unhidden[i$1], "unhide"); } } }
  9444. if (display.wrapper.offsetHeight)
  9445. { doc.scrollTop = cm.display.scroller.scrollTop; }
  9446. // Fire change events, and delayed event handlers
  9447. if (op.changeObjs)
  9448. { signal(cm, "changes", cm, op.changeObjs); }
  9449. if (op.update)
  9450. { op.update.finish(); }
  9451. }
  9452. // Run the given function in an operation
  9453. function runInOp(cm, f) {
  9454. if (cm.curOp) { return f() }
  9455. startOperation(cm);
  9456. try { return f() }
  9457. finally { endOperation(cm); }
  9458. }
  9459. // Wraps a function in an operation. Returns the wrapped function.
  9460. function operation(cm, f) {
  9461. return function() {
  9462. if (cm.curOp) { return f.apply(cm, arguments) }
  9463. startOperation(cm);
  9464. try { return f.apply(cm, arguments) }
  9465. finally { endOperation(cm); }
  9466. }
  9467. }
  9468. // Used to add methods to editor and doc instances, wrapping them in
  9469. // operations.
  9470. function methodOp(f) {
  9471. return function() {
  9472. if (this.curOp) { return f.apply(this, arguments) }
  9473. startOperation(this);
  9474. try { return f.apply(this, arguments) }
  9475. finally { endOperation(this); }
  9476. }
  9477. }
  9478. function docMethodOp(f) {
  9479. return function() {
  9480. var cm = this.cm;
  9481. if (!cm || cm.curOp) { return f.apply(this, arguments) }
  9482. startOperation(cm);
  9483. try { return f.apply(this, arguments) }
  9484. finally { endOperation(cm); }
  9485. }
  9486. }
  9487. // Updates the display.view data structure for a given change to the
  9488. // document. From and to are in pre-change coordinates. Lendiff is
  9489. // the amount of lines added or subtracted by the change. This is
  9490. // used for changes that span multiple lines, or change the way
  9491. // lines are divided into visual lines. regLineChange (below)
  9492. // registers single-line changes.
  9493. function regChange(cm, from, to, lendiff) {
  9494. if (from == null) { from = cm.doc.first; }
  9495. if (to == null) { to = cm.doc.first + cm.doc.size; }
  9496. if (!lendiff) { lendiff = 0; }
  9497. var display = cm.display;
  9498. if (lendiff && to < display.viewTo &&
  9499. (display.updateLineNumbers == null || display.updateLineNumbers > from))
  9500. { display.updateLineNumbers = from; }
  9501. cm.curOp.viewChanged = true;
  9502. if (from >= display.viewTo) { // Change after
  9503. if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo)
  9504. { resetView(cm); }
  9505. } else if (to <= display.viewFrom) { // Change before
  9506. if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) {
  9507. resetView(cm);
  9508. } else {
  9509. display.viewFrom += lendiff;
  9510. display.viewTo += lendiff;
  9511. }
  9512. } else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap
  9513. resetView(cm);
  9514. } else if (from <= display.viewFrom) { // Top overlap
  9515. var cut = viewCuttingPoint(cm, to, to + lendiff, 1);
  9516. if (cut) {
  9517. display.view = display.view.slice(cut.index);
  9518. display.viewFrom = cut.lineN;
  9519. display.viewTo += lendiff;
  9520. } else {
  9521. resetView(cm);
  9522. }
  9523. } else if (to >= display.viewTo) { // Bottom overlap
  9524. var cut$1 = viewCuttingPoint(cm, from, from, -1);
  9525. if (cut$1) {
  9526. display.view = display.view.slice(0, cut$1.index);
  9527. display.viewTo = cut$1.lineN;
  9528. } else {
  9529. resetView(cm);
  9530. }
  9531. } else { // Gap in the middle
  9532. var cutTop = viewCuttingPoint(cm, from, from, -1);
  9533. var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1);
  9534. if (cutTop && cutBot) {
  9535. display.view = display.view.slice(0, cutTop.index)
  9536. .concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN))
  9537. .concat(display.view.slice(cutBot.index));
  9538. display.viewTo += lendiff;
  9539. } else {
  9540. resetView(cm);
  9541. }
  9542. }
  9543. var ext = display.externalMeasured;
  9544. if (ext) {
  9545. if (to < ext.lineN)
  9546. { ext.lineN += lendiff; }
  9547. else if (from < ext.lineN + ext.size)
  9548. { display.externalMeasured = null; }
  9549. }
  9550. }
  9551. // Register a change to a single line. Type must be one of "text",
  9552. // "gutter", "class", "widget"
  9553. function regLineChange(cm, line, type) {
  9554. cm.curOp.viewChanged = true;
  9555. var display = cm.display, ext = cm.display.externalMeasured;
  9556. if (ext && line >= ext.lineN && line < ext.lineN + ext.size)
  9557. { display.externalMeasured = null; }
  9558. if (line < display.viewFrom || line >= display.viewTo) { return }
  9559. var lineView = display.view[findViewIndex(cm, line)];
  9560. if (lineView.node == null) { return }
  9561. var arr = lineView.changes || (lineView.changes = []);
  9562. if (indexOf(arr, type) == -1) { arr.push(type); }
  9563. }
  9564. // Clear the view.
  9565. function resetView(cm) {
  9566. cm.display.viewFrom = cm.display.viewTo = cm.doc.first;
  9567. cm.display.view = [];
  9568. cm.display.viewOffset = 0;
  9569. }
  9570. function viewCuttingPoint(cm, oldN, newN, dir) {
  9571. var index = findViewIndex(cm, oldN), diff, view = cm.display.view;
  9572. if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size)
  9573. { return {index: index, lineN: newN} }
  9574. var n = cm.display.viewFrom;
  9575. for (var i = 0; i < index; i++)
  9576. { n += view[i].size; }
  9577. if (n != oldN) {
  9578. if (dir > 0) {
  9579. if (index == view.length - 1) { return null }
  9580. diff = (n + view[index].size) - oldN;
  9581. index++;
  9582. } else {
  9583. diff = n - oldN;
  9584. }
  9585. oldN += diff; newN += diff;
  9586. }
  9587. while (visualLineNo(cm.doc, newN) != newN) {
  9588. if (index == (dir < 0 ? 0 : view.length - 1)) { return null }
  9589. newN += dir * view[index - (dir < 0 ? 1 : 0)].size;
  9590. index += dir;
  9591. }
  9592. return {index: index, lineN: newN}
  9593. }
  9594. // Force the view to cover a given range, adding empty view element
  9595. // or clipping off existing ones as needed.
  9596. function adjustView(cm, from, to) {
  9597. var display = cm.display, view = display.view;
  9598. if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) {
  9599. display.view = buildViewArray(cm, from, to);
  9600. display.viewFrom = from;
  9601. } else {
  9602. if (display.viewFrom > from)
  9603. { display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view); }
  9604. else if (display.viewFrom < from)
  9605. { display.view = display.view.slice(findViewIndex(cm, from)); }
  9606. display.viewFrom = from;
  9607. if (display.viewTo < to)
  9608. { display.view = display.view.concat(buildViewArray(cm, display.viewTo, to)); }
  9609. else if (display.viewTo > to)
  9610. { display.view = display.view.slice(0, findViewIndex(cm, to)); }
  9611. }
  9612. display.viewTo = to;
  9613. }
  9614. // Count the number of lines in the view whose DOM representation is
  9615. // out of date (or nonexistent).
  9616. function countDirtyView(cm) {
  9617. var view = cm.display.view, dirty = 0;
  9618. for (var i = 0; i < view.length; i++) {
  9619. var lineView = view[i];
  9620. if (!lineView.hidden && (!lineView.node || lineView.changes)) { ++dirty; }
  9621. }
  9622. return dirty
  9623. }
  9624. // HIGHLIGHT WORKER
  9625. function startWorker(cm, time) {
  9626. if (cm.doc.highlightFrontier < cm.display.viewTo)
  9627. { cm.state.highlight.set(time, bind(highlightWorker, cm)); }
  9628. }
  9629. function highlightWorker(cm) {
  9630. var doc = cm.doc;
  9631. if (doc.highlightFrontier >= cm.display.viewTo) { return }
  9632. var end = +new Date + cm.options.workTime;
  9633. var context = getContextBefore(cm, doc.highlightFrontier);
  9634. var changedLines = [];
  9635. doc.iter(context.line, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function (line) {
  9636. if (context.line >= cm.display.viewFrom) { // Visible
  9637. var oldStyles = line.styles;
  9638. var resetState = line.text.length > cm.options.maxHighlightLength ? copyState(doc.mode, context.state) : null;
  9639. var highlighted = highlightLine(cm, line, context, true);
  9640. if (resetState) { context.state = resetState; }
  9641. line.styles = highlighted.styles;
  9642. var oldCls = line.styleClasses, newCls = highlighted.classes;
  9643. if (newCls) { line.styleClasses = newCls; }
  9644. else if (oldCls) { line.styleClasses = null; }
  9645. var ischange = !oldStyles || oldStyles.length != line.styles.length ||
  9646. oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass);
  9647. for (var i = 0; !ischange && i < oldStyles.length; ++i) { ischange = oldStyles[i] != line.styles[i]; }
  9648. if (ischange) { changedLines.push(context.line); }
  9649. line.stateAfter = context.save();
  9650. context.nextLine();
  9651. } else {
  9652. if (line.text.length <= cm.options.maxHighlightLength)
  9653. { processLine(cm, line.text, context); }
  9654. line.stateAfter = context.line % 5 == 0 ? context.save() : null;
  9655. context.nextLine();
  9656. }
  9657. if (+new Date > end) {
  9658. startWorker(cm, cm.options.workDelay);
  9659. return true
  9660. }
  9661. });
  9662. doc.highlightFrontier = context.line;
  9663. doc.modeFrontier = Math.max(doc.modeFrontier, context.line);
  9664. if (changedLines.length) { runInOp(cm, function () {
  9665. for (var i = 0; i < changedLines.length; i++)
  9666. { regLineChange(cm, changedLines[i], "text"); }
  9667. }); }
  9668. }
  9669. // DISPLAY DRAWING
  9670. var DisplayUpdate = function(cm, viewport, force) {
  9671. var display = cm.display;
  9672. this.viewport = viewport;
  9673. // Store some values that we'll need later (but don't want to force a relayout for)
  9674. this.visible = visibleLines(display, cm.doc, viewport);
  9675. this.editorIsHidden = !display.wrapper.offsetWidth;
  9676. this.wrapperHeight = display.wrapper.clientHeight;
  9677. this.wrapperWidth = display.wrapper.clientWidth;
  9678. this.oldDisplayWidth = displayWidth(cm);
  9679. this.force = force;
  9680. this.dims = getDimensions(cm);
  9681. this.events = [];
  9682. };
  9683. DisplayUpdate.prototype.signal = function (emitter, type) {
  9684. if (hasHandler(emitter, type))
  9685. { this.events.push(arguments); }
  9686. };
  9687. DisplayUpdate.prototype.finish = function () {
  9688. var this$1 = this;
  9689. for (var i = 0; i < this.events.length; i++)
  9690. { signal.apply(null, this$1.events[i]); }
  9691. };
  9692. function maybeClipScrollbars(cm) {
  9693. var display = cm.display;
  9694. if (!display.scrollbarsClipped && display.scroller.offsetWidth) {
  9695. display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth;
  9696. display.heightForcer.style.height = scrollGap(cm) + "px";
  9697. display.sizer.style.marginBottom = -display.nativeBarWidth + "px";
  9698. display.sizer.style.borderRightWidth = scrollGap(cm) + "px";
  9699. display.scrollbarsClipped = true;
  9700. }
  9701. }
  9702. function selectionSnapshot(cm) {
  9703. if (cm.hasFocus()) { return null }
  9704. var active = activeElt();
  9705. if (!active || !contains(cm.display.lineDiv, active)) { return null }
  9706. var result = {activeElt: active};
  9707. if (window.getSelection) {
  9708. var sel = window.getSelection();
  9709. if (sel.anchorNode && sel.extend && contains(cm.display.lineDiv, sel.anchorNode)) {
  9710. result.anchorNode = sel.anchorNode;
  9711. result.anchorOffset = sel.anchorOffset;
  9712. result.focusNode = sel.focusNode;
  9713. result.focusOffset = sel.focusOffset;
  9714. }
  9715. }
  9716. return result
  9717. }
  9718. function restoreSelection(snapshot) {
  9719. if (!snapshot || !snapshot.activeElt || snapshot.activeElt == activeElt()) { return }
  9720. snapshot.activeElt.focus();
  9721. if (snapshot.anchorNode && contains(document.body, snapshot.anchorNode) && contains(document.body, snapshot.focusNode)) {
  9722. var sel = window.getSelection(), range$$1 = document.createRange();
  9723. range$$1.setEnd(snapshot.anchorNode, snapshot.anchorOffset);
  9724. range$$1.collapse(false);
  9725. sel.removeAllRanges();
  9726. sel.addRange(range$$1);
  9727. sel.extend(snapshot.focusNode, snapshot.focusOffset);
  9728. }
  9729. }
  9730. // Does the actual updating of the line display. Bails out
  9731. // (returning false) when there is nothing to be done and forced is
  9732. // false.
  9733. function updateDisplayIfNeeded(cm, update) {
  9734. var display = cm.display, doc = cm.doc;
  9735. if (update.editorIsHidden) {
  9736. resetView(cm);
  9737. return false
  9738. }
  9739. // Bail out if the visible area is already rendered and nothing changed.
  9740. if (!update.force &&
  9741. update.visible.from >= display.viewFrom && update.visible.to <= display.viewTo &&
  9742. (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) &&
  9743. display.renderedView == display.view && countDirtyView(cm) == 0)
  9744. { return false }
  9745. if (maybeUpdateLineNumberWidth(cm)) {
  9746. resetView(cm);
  9747. update.dims = getDimensions(cm);
  9748. }
  9749. // Compute a suitable new viewport (from & to)
  9750. var end = doc.first + doc.size;
  9751. var from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first);
  9752. var to = Math.min(end, update.visible.to + cm.options.viewportMargin);
  9753. if (display.viewFrom < from && from - display.viewFrom < 20) { from = Math.max(doc.first, display.viewFrom); }
  9754. if (display.viewTo > to && display.viewTo - to < 20) { to = Math.min(end, display.viewTo); }
  9755. if (sawCollapsedSpans) {
  9756. from = visualLineNo(cm.doc, from);
  9757. to = visualLineEndNo(cm.doc, to);
  9758. }
  9759. var different = from != display.viewFrom || to != display.viewTo ||
  9760. display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth;
  9761. adjustView(cm, from, to);
  9762. display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom));
  9763. // Position the mover div to align with the current scroll position
  9764. cm.display.mover.style.top = display.viewOffset + "px";
  9765. var toUpdate = countDirtyView(cm);
  9766. if (!different && toUpdate == 0 && !update.force && display.renderedView == display.view &&
  9767. (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo))
  9768. { return false }
  9769. // For big changes, we hide the enclosing element during the
  9770. // update, since that speeds up the operations on most browsers.
  9771. var selSnapshot = selectionSnapshot(cm);
  9772. if (toUpdate > 4) { display.lineDiv.style.display = "none"; }
  9773. patchDisplay(cm, display.updateLineNumbers, update.dims);
  9774. if (toUpdate > 4) { display.lineDiv.style.display = ""; }
  9775. display.renderedView = display.view;
  9776. // There might have been a widget with a focused element that got
  9777. // hidden or updated, if so re-focus it.
  9778. restoreSelection(selSnapshot);
  9779. // Prevent selection and cursors from interfering with the scroll
  9780. // width and height.
  9781. removeChildren(display.cursorDiv);
  9782. removeChildren(display.selectionDiv);
  9783. display.gutters.style.height = display.sizer.style.minHeight = 0;
  9784. if (different) {
  9785. display.lastWrapHeight = update.wrapperHeight;
  9786. display.lastWrapWidth = update.wrapperWidth;
  9787. startWorker(cm, 400);
  9788. }
  9789. display.updateLineNumbers = null;
  9790. return true
  9791. }
  9792. function postUpdateDisplay(cm, update) {
  9793. var viewport = update.viewport;
  9794. for (var first = true;; first = false) {
  9795. if (!first || !cm.options.lineWrapping || update.oldDisplayWidth == displayWidth(cm)) {
  9796. // Clip forced viewport to actual scrollable area.
  9797. if (viewport && viewport.top != null)
  9798. { viewport = {top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top)}; }
  9799. // Updated line heights might result in the drawn area not
  9800. // actually covering the viewport. Keep looping until it does.
  9801. update.visible = visibleLines(cm.display, cm.doc, viewport);
  9802. if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo)
  9803. { break }
  9804. }
  9805. if (!updateDisplayIfNeeded(cm, update)) { break }
  9806. updateHeightsInViewport(cm);
  9807. var barMeasure = measureForScrollbars(cm);
  9808. updateSelection(cm);
  9809. updateScrollbars(cm, barMeasure);
  9810. setDocumentHeight(cm, barMeasure);
  9811. update.force = false;
  9812. }
  9813. update.signal(cm, "update", cm);
  9814. if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) {
  9815. update.signal(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo);
  9816. cm.display.reportedViewFrom = cm.display.viewFrom; cm.display.reportedViewTo = cm.display.viewTo;
  9817. }
  9818. }
  9819. function updateDisplaySimple(cm, viewport) {
  9820. var update = new DisplayUpdate(cm, viewport);
  9821. if (updateDisplayIfNeeded(cm, update)) {
  9822. updateHeightsInViewport(cm);
  9823. postUpdateDisplay(cm, update);
  9824. var barMeasure = measureForScrollbars(cm);
  9825. updateSelection(cm);
  9826. updateScrollbars(cm, barMeasure);
  9827. setDocumentHeight(cm, barMeasure);
  9828. update.finish();
  9829. }
  9830. }
  9831. // Sync the actual display DOM structure with display.view, removing
  9832. // nodes for lines that are no longer in view, and creating the ones
  9833. // that are not there yet, and updating the ones that are out of
  9834. // date.
  9835. function patchDisplay(cm, updateNumbersFrom, dims) {
  9836. var display = cm.display, lineNumbers = cm.options.lineNumbers;
  9837. var container = display.lineDiv, cur = container.firstChild;
  9838. function rm(node) {
  9839. var next = node.nextSibling;
  9840. // Works around a throw-scroll bug in OS X Webkit
  9841. if (webkit && mac && cm.display.currentWheelTarget == node)
  9842. { node.style.display = "none"; }
  9843. else
  9844. { node.parentNode.removeChild(node); }
  9845. return next
  9846. }
  9847. var view = display.view, lineN = display.viewFrom;
  9848. // Loop over the elements in the view, syncing cur (the DOM nodes
  9849. // in display.lineDiv) with the view as we go.
  9850. for (var i = 0; i < view.length; i++) {
  9851. var lineView = view[i];
  9852. if (lineView.hidden) {
  9853. } else if (!lineView.node || lineView.node.parentNode != container) { // Not drawn yet
  9854. var node = buildLineElement(cm, lineView, lineN, dims);
  9855. container.insertBefore(node, cur);
  9856. } else { // Already drawn
  9857. while (cur != lineView.node) { cur = rm(cur); }
  9858. var updateNumber = lineNumbers && updateNumbersFrom != null &&
  9859. updateNumbersFrom <= lineN && lineView.lineNumber;
  9860. if (lineView.changes) {
  9861. if (indexOf(lineView.changes, "gutter") > -1) { updateNumber = false; }
  9862. updateLineForChanges(cm, lineView, lineN, dims);
  9863. }
  9864. if (updateNumber) {
  9865. removeChildren(lineView.lineNumber);
  9866. lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN)));
  9867. }
  9868. cur = lineView.node.nextSibling;
  9869. }
  9870. lineN += lineView.size;
  9871. }
  9872. while (cur) { cur = rm(cur); }
  9873. }
  9874. function updateGutterSpace(cm) {
  9875. var width = cm.display.gutters.offsetWidth;
  9876. cm.display.sizer.style.marginLeft = width + "px";
  9877. }
  9878. function setDocumentHeight(cm, measure) {
  9879. cm.display.sizer.style.minHeight = measure.docHeight + "px";
  9880. cm.display.heightForcer.style.top = measure.docHeight + "px";
  9881. cm.display.gutters.style.height = (measure.docHeight + cm.display.barHeight + scrollGap(cm)) + "px";
  9882. }
  9883. // Rebuild the gutter elements, ensure the margin to the left of the
  9884. // code matches their width.
  9885. function updateGutters(cm) {
  9886. var gutters = cm.display.gutters, specs = cm.options.gutters;
  9887. removeChildren(gutters);
  9888. var i = 0;
  9889. for (; i < specs.length; ++i) {
  9890. var gutterClass = specs[i];
  9891. var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + gutterClass));
  9892. if (gutterClass == "CodeMirror-linenumbers") {
  9893. cm.display.lineGutter = gElt;
  9894. gElt.style.width = (cm.display.lineNumWidth || 1) + "px";
  9895. }
  9896. }
  9897. gutters.style.display = i ? "" : "none";
  9898. updateGutterSpace(cm);
  9899. }
  9900. // Make sure the gutters options contains the element
  9901. // "CodeMirror-linenumbers" when the lineNumbers option is true.
  9902. function setGuttersForLineNumbers(options) {
  9903. var found = indexOf(options.gutters, "CodeMirror-linenumbers");
  9904. if (found == -1 && options.lineNumbers) {
  9905. options.gutters = options.gutters.concat(["CodeMirror-linenumbers"]);
  9906. } else if (found > -1 && !options.lineNumbers) {
  9907. options.gutters = options.gutters.slice(0);
  9908. options.gutters.splice(found, 1);
  9909. }
  9910. }
  9911. // Since the delta values reported on mouse wheel events are
  9912. // unstandardized between browsers and even browser versions, and
  9913. // generally horribly unpredictable, this code starts by measuring
  9914. // the scroll effect that the first few mouse wheel events have,
  9915. // and, from that, detects the way it can convert deltas to pixel
  9916. // offsets afterwards.
  9917. //
  9918. // The reason we want to know the amount a wheel event will scroll
  9919. // is that it gives us a chance to update the display before the
  9920. // actual scrolling happens, reducing flickering.
  9921. var wheelSamples = 0;
  9922. var wheelPixelsPerUnit = null;
  9923. // Fill in a browser-detected starting value on browsers where we
  9924. // know one. These don't have to be accurate -- the result of them
  9925. // being wrong would just be a slight flicker on the first wheel
  9926. // scroll (if it is large enough).
  9927. if (ie) { wheelPixelsPerUnit = -.53; }
  9928. else if (gecko) { wheelPixelsPerUnit = 15; }
  9929. else if (chrome) { wheelPixelsPerUnit = -.7; }
  9930. else if (safari) { wheelPixelsPerUnit = -1/3; }
  9931. function wheelEventDelta(e) {
  9932. var dx = e.wheelDeltaX, dy = e.wheelDeltaY;
  9933. if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) { dx = e.detail; }
  9934. if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) { dy = e.detail; }
  9935. else if (dy == null) { dy = e.wheelDelta; }
  9936. return {x: dx, y: dy}
  9937. }
  9938. function wheelEventPixels(e) {
  9939. var delta = wheelEventDelta(e);
  9940. delta.x *= wheelPixelsPerUnit;
  9941. delta.y *= wheelPixelsPerUnit;
  9942. return delta
  9943. }
  9944. function onScrollWheel(cm, e) {
  9945. var delta = wheelEventDelta(e), dx = delta.x, dy = delta.y;
  9946. var display = cm.display, scroll = display.scroller;
  9947. // Quit if there's nothing to scroll here
  9948. var canScrollX = scroll.scrollWidth > scroll.clientWidth;
  9949. var canScrollY = scroll.scrollHeight > scroll.clientHeight;
  9950. if (!(dx && canScrollX || dy && canScrollY)) { return }
  9951. // Webkit browsers on OS X abort momentum scrolls when the target
  9952. // of the scroll event is removed from the scrollable element.
  9953. // This hack (see related code in patchDisplay) makes sure the
  9954. // element is kept around.
  9955. if (dy && mac && webkit) {
  9956. outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) {
  9957. for (var i = 0; i < view.length; i++) {
  9958. if (view[i].node == cur) {
  9959. cm.display.currentWheelTarget = cur;
  9960. break outer
  9961. }
  9962. }
  9963. }
  9964. }
  9965. // On some browsers, horizontal scrolling will cause redraws to
  9966. // happen before the gutter has been realigned, causing it to
  9967. // wriggle around in a most unseemly way. When we have an
  9968. // estimated pixels/delta value, we just handle horizontal
  9969. // scrolling entirely here. It'll be slightly off from native, but
  9970. // better than glitching out.
  9971. if (dx && !gecko && !presto && wheelPixelsPerUnit != null) {
  9972. if (dy && canScrollY)
  9973. { updateScrollTop(cm, Math.max(0, scroll.scrollTop + dy * wheelPixelsPerUnit)); }
  9974. setScrollLeft(cm, Math.max(0, scroll.scrollLeft + dx * wheelPixelsPerUnit));
  9975. // Only prevent default scrolling if vertical scrolling is
  9976. // actually possible. Otherwise, it causes vertical scroll
  9977. // jitter on OSX trackpads when deltaX is small and deltaY
  9978. // is large (issue #3579)
  9979. if (!dy || (dy && canScrollY))
  9980. { e_preventDefault(e); }
  9981. display.wheelStartX = null; // Abort measurement, if in progress
  9982. return
  9983. }
  9984. // 'Project' the visible viewport to cover the area that is being
  9985. // scrolled into view (if we know enough to estimate it).
  9986. if (dy && wheelPixelsPerUnit != null) {
  9987. var pixels = dy * wheelPixelsPerUnit;
  9988. var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight;
  9989. if (pixels < 0) { top = Math.max(0, top + pixels - 50); }
  9990. else { bot = Math.min(cm.doc.height, bot + pixels + 50); }
  9991. updateDisplaySimple(cm, {top: top, bottom: bot});
  9992. }
  9993. if (wheelSamples < 20) {
  9994. if (display.wheelStartX == null) {
  9995. display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop;
  9996. display.wheelDX = dx; display.wheelDY = dy;
  9997. setTimeout(function () {
  9998. if (display.wheelStartX == null) { return }
  9999. var movedX = scroll.scrollLeft - display.wheelStartX;
  10000. var movedY = scroll.scrollTop - display.wheelStartY;
  10001. var sample = (movedY && display.wheelDY && movedY / display.wheelDY) ||
  10002. (movedX && display.wheelDX && movedX / display.wheelDX);
  10003. display.wheelStartX = display.wheelStartY = null;
  10004. if (!sample) { return }
  10005. wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1);
  10006. ++wheelSamples;
  10007. }, 200);
  10008. } else {
  10009. display.wheelDX += dx; display.wheelDY += dy;
  10010. }
  10011. }
  10012. }
  10013. // Selection objects are immutable. A new one is created every time
  10014. // the selection changes. A selection is one or more non-overlapping
  10015. // (and non-touching) ranges, sorted, and an integer that indicates
  10016. // which one is the primary selection (the one that's scrolled into
  10017. // view, that getCursor returns, etc).
  10018. var Selection = function(ranges, primIndex) {
  10019. this.ranges = ranges;
  10020. this.primIndex = primIndex;
  10021. };
  10022. Selection.prototype.primary = function () { return this.ranges[this.primIndex] };
  10023. Selection.prototype.equals = function (other) {
  10024. var this$1 = this;
  10025. if (other == this) { return true }
  10026. if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) { return false }
  10027. for (var i = 0; i < this.ranges.length; i++) {
  10028. var here = this$1.ranges[i], there = other.ranges[i];
  10029. if (!equalCursorPos(here.anchor, there.anchor) || !equalCursorPos(here.head, there.head)) { return false }
  10030. }
  10031. return true
  10032. };
  10033. Selection.prototype.deepCopy = function () {
  10034. var this$1 = this;
  10035. var out = [];
  10036. for (var i = 0; i < this.ranges.length; i++)
  10037. { out[i] = new Range(copyPos(this$1.ranges[i].anchor), copyPos(this$1.ranges[i].head)); }
  10038. return new Selection(out, this.primIndex)
  10039. };
  10040. Selection.prototype.somethingSelected = function () {
  10041. var this$1 = this;
  10042. for (var i = 0; i < this.ranges.length; i++)
  10043. { if (!this$1.ranges[i].empty()) { return true } }
  10044. return false
  10045. };
  10046. Selection.prototype.contains = function (pos, end) {
  10047. var this$1 = this;
  10048. if (!end) { end = pos; }
  10049. for (var i = 0; i < this.ranges.length; i++) {
  10050. var range = this$1.ranges[i];
  10051. if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0)
  10052. { return i }
  10053. }
  10054. return -1
  10055. };
  10056. var Range = function(anchor, head) {
  10057. this.anchor = anchor; this.head = head;
  10058. };
  10059. Range.prototype.from = function () { return minPos(this.anchor, this.head) };
  10060. Range.prototype.to = function () { return maxPos(this.anchor, this.head) };
  10061. Range.prototype.empty = function () { return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch };
  10062. // Take an unsorted, potentially overlapping set of ranges, and
  10063. // build a selection out of it. 'Consumes' ranges array (modifying
  10064. // it).
  10065. function normalizeSelection(ranges, primIndex) {
  10066. var prim = ranges[primIndex];
  10067. ranges.sort(function (a, b) { return cmp(a.from(), b.from()); });
  10068. primIndex = indexOf(ranges, prim);
  10069. for (var i = 1; i < ranges.length; i++) {
  10070. var cur = ranges[i], prev = ranges[i - 1];
  10071. if (cmp(prev.to(), cur.from()) >= 0) {
  10072. var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to());
  10073. var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head;
  10074. if (i <= primIndex) { --primIndex; }
  10075. ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to));
  10076. }
  10077. }
  10078. return new Selection(ranges, primIndex)
  10079. }
  10080. function simpleSelection(anchor, head) {
  10081. return new Selection([new Range(anchor, head || anchor)], 0)
  10082. }
  10083. // Compute the position of the end of a change (its 'to' property
  10084. // refers to the pre-change end).
  10085. function changeEnd(change) {
  10086. if (!change.text) { return change.to }
  10087. return Pos(change.from.line + change.text.length - 1,
  10088. lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0))
  10089. }
  10090. // Adjust a position to refer to the post-change position of the
  10091. // same text, or the end of the change if the change covers it.
  10092. function adjustForChange(pos, change) {
  10093. if (cmp(pos, change.from) < 0) { return pos }
  10094. if (cmp(pos, change.to) <= 0) { return changeEnd(change) }
  10095. var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch;
  10096. if (pos.line == change.to.line) { ch += changeEnd(change).ch - change.to.ch; }
  10097. return Pos(line, ch)
  10098. }
  10099. function computeSelAfterChange(doc, change) {
  10100. var out = [];
  10101. for (var i = 0; i < doc.sel.ranges.length; i++) {
  10102. var range = doc.sel.ranges[i];
  10103. out.push(new Range(adjustForChange(range.anchor, change),
  10104. adjustForChange(range.head, change)));
  10105. }
  10106. return normalizeSelection(out, doc.sel.primIndex)
  10107. }
  10108. function offsetPos(pos, old, nw) {
  10109. if (pos.line == old.line)
  10110. { return Pos(nw.line, pos.ch - old.ch + nw.ch) }
  10111. else
  10112. { return Pos(nw.line + (pos.line - old.line), pos.ch) }
  10113. }
  10114. // Used by replaceSelections to allow moving the selection to the
  10115. // start or around the replaced test. Hint may be "start" or "around".
  10116. function computeReplacedSel(doc, changes, hint) {
  10117. var out = [];
  10118. var oldPrev = Pos(doc.first, 0), newPrev = oldPrev;
  10119. for (var i = 0; i < changes.length; i++) {
  10120. var change = changes[i];
  10121. var from = offsetPos(change.from, oldPrev, newPrev);
  10122. var to = offsetPos(changeEnd(change), oldPrev, newPrev);
  10123. oldPrev = change.to;
  10124. newPrev = to;
  10125. if (hint == "around") {
  10126. var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) < 0;
  10127. out[i] = new Range(inv ? to : from, inv ? from : to);
  10128. } else {
  10129. out[i] = new Range(from, from);
  10130. }
  10131. }
  10132. return new Selection(out, doc.sel.primIndex)
  10133. }
  10134. // Used to get the editor into a consistent state again when options change.
  10135. function loadMode(cm) {
  10136. cm.doc.mode = getMode(cm.options, cm.doc.modeOption);
  10137. resetModeState(cm);
  10138. }
  10139. function resetModeState(cm) {
  10140. cm.doc.iter(function (line) {
  10141. if (line.stateAfter) { line.stateAfter = null; }
  10142. if (line.styles) { line.styles = null; }
  10143. });
  10144. cm.doc.modeFrontier = cm.doc.highlightFrontier = cm.doc.first;
  10145. startWorker(cm, 100);
  10146. cm.state.modeGen++;
  10147. if (cm.curOp) { regChange(cm); }
  10148. }
  10149. // DOCUMENT DATA STRUCTURE
  10150. // By default, updates that start and end at the beginning of a line
  10151. // are treated specially, in order to make the association of line
  10152. // widgets and marker elements with the text behave more intuitive.
  10153. function isWholeLineUpdate(doc, change) {
  10154. return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" &&
  10155. (!doc.cm || doc.cm.options.wholeLineUpdateBefore)
  10156. }
  10157. // Perform a change on the document data structure.
  10158. function updateDoc(doc, change, markedSpans, estimateHeight$$1) {
  10159. function spansFor(n) {return markedSpans ? markedSpans[n] : null}
  10160. function update(line, text, spans) {
  10161. updateLine(line, text, spans, estimateHeight$$1);
  10162. signalLater(line, "change", line, change);
  10163. }
  10164. function linesFor(start, end) {
  10165. var result = [];
  10166. for (var i = start; i < end; ++i)
  10167. { result.push(new Line(text[i], spansFor(i), estimateHeight$$1)); }
  10168. return result
  10169. }
  10170. var from = change.from, to = change.to, text = change.text;
  10171. var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line);
  10172. var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line;
  10173. // Adjust the line structure
  10174. if (change.full) {
  10175. doc.insert(0, linesFor(0, text.length));
  10176. doc.remove(text.length, doc.size - text.length);
  10177. } else if (isWholeLineUpdate(doc, change)) {
  10178. // This is a whole-line replace. Treated specially to make
  10179. // sure line objects move the way they are supposed to.
  10180. var added = linesFor(0, text.length - 1);
  10181. update(lastLine, lastLine.text, lastSpans);
  10182. if (nlines) { doc.remove(from.line, nlines); }
  10183. if (added.length) { doc.insert(from.line, added); }
  10184. } else if (firstLine == lastLine) {
  10185. if (text.length == 1) {
  10186. update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans);
  10187. } else {
  10188. var added$1 = linesFor(1, text.length - 1);
  10189. added$1.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight$$1));
  10190. update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
  10191. doc.insert(from.line + 1, added$1);
  10192. }
  10193. } else if (text.length == 1) {
  10194. update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0));
  10195. doc.remove(from.line + 1, nlines);
  10196. } else {
  10197. update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
  10198. update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans);
  10199. var added$2 = linesFor(1, text.length - 1);
  10200. if (nlines > 1) { doc.remove(from.line + 1, nlines - 1); }
  10201. doc.insert(from.line + 1, added$2);
  10202. }
  10203. signalLater(doc, "change", doc, change);
  10204. }
  10205. // Call f for all linked documents.
  10206. function linkedDocs(doc, f, sharedHistOnly) {
  10207. function propagate(doc, skip, sharedHist) {
  10208. if (doc.linked) { for (var i = 0; i < doc.linked.length; ++i) {
  10209. var rel = doc.linked[i];
  10210. if (rel.doc == skip) { continue }
  10211. var shared = sharedHist && rel.sharedHist;
  10212. if (sharedHistOnly && !shared) { continue }
  10213. f(rel.doc, shared);
  10214. propagate(rel.doc, doc, shared);
  10215. } }
  10216. }
  10217. propagate(doc, null, true);
  10218. }
  10219. // Attach a document to an editor.
  10220. function attachDoc(cm, doc) {
  10221. if (doc.cm) { throw new Error("This document is already in use.") }
  10222. cm.doc = doc;
  10223. doc.cm = cm;
  10224. estimateLineHeights(cm);
  10225. loadMode(cm);
  10226. setDirectionClass(cm);
  10227. if (!cm.options.lineWrapping) { findMaxLine(cm); }
  10228. cm.options.mode = doc.modeOption;
  10229. regChange(cm);
  10230. }
  10231. function setDirectionClass(cm) {
  10232. (cm.doc.direction == "rtl" ? addClass : rmClass)(cm.display.lineDiv, "CodeMirror-rtl");
  10233. }
  10234. function directionChanged(cm) {
  10235. runInOp(cm, function () {
  10236. setDirectionClass(cm);
  10237. regChange(cm);
  10238. });
  10239. }
  10240. function History(startGen) {
  10241. // Arrays of change events and selections. Doing something adds an
  10242. // event to done and clears undo. Undoing moves events from done
  10243. // to undone, redoing moves them in the other direction.
  10244. this.done = []; this.undone = [];
  10245. this.undoDepth = Infinity;
  10246. // Used to track when changes can be merged into a single undo
  10247. // event
  10248. this.lastModTime = this.lastSelTime = 0;
  10249. this.lastOp = this.lastSelOp = null;
  10250. this.lastOrigin = this.lastSelOrigin = null;
  10251. // Used by the isClean() method
  10252. this.generation = this.maxGeneration = startGen || 1;
  10253. }
  10254. // Create a history change event from an updateDoc-style change
  10255. // object.
  10256. function historyChangeFromChange(doc, change) {
  10257. var histChange = {from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to)};
  10258. attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);
  10259. linkedDocs(doc, function (doc) { return attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1); }, true);
  10260. return histChange
  10261. }
  10262. // Pop all selection events off the end of a history array. Stop at
  10263. // a change event.
  10264. function clearSelectionEvents(array) {
  10265. while (array.length) {
  10266. var last = lst(array);
  10267. if (last.ranges) { array.pop(); }
  10268. else { break }
  10269. }
  10270. }
  10271. // Find the top change event in the history. Pop off selection
  10272. // events that are in the way.
  10273. function lastChangeEvent(hist, force) {
  10274. if (force) {
  10275. clearSelectionEvents(hist.done);
  10276. return lst(hist.done)
  10277. } else if (hist.done.length && !lst(hist.done).ranges) {
  10278. return lst(hist.done)
  10279. } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) {
  10280. hist.done.pop();
  10281. return lst(hist.done)
  10282. }
  10283. }
  10284. // Register a change in the history. Merges changes that are within
  10285. // a single operation, or are close together with an origin that
  10286. // allows merging (starting with "+") into a single event.
  10287. function addChangeToHistory(doc, change, selAfter, opId) {
  10288. var hist = doc.history;
  10289. hist.undone.length = 0;
  10290. var time = +new Date, cur;
  10291. var last;
  10292. if ((hist.lastOp == opId ||
  10293. hist.lastOrigin == change.origin && change.origin &&
  10294. ((change.origin.charAt(0) == "+" && doc.cm && hist.lastModTime > time - doc.cm.options.historyEventDelay) ||
  10295. change.origin.charAt(0) == "*")) &&
  10296. (cur = lastChangeEvent(hist, hist.lastOp == opId))) {
  10297. // Merge this change into the last event
  10298. last = lst(cur.changes);
  10299. if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) {
  10300. // Optimized case for simple insertion -- don't want to add
  10301. // new changesets for every character typed
  10302. last.to = changeEnd(change);
  10303. } else {
  10304. // Add new sub-event
  10305. cur.changes.push(historyChangeFromChange(doc, change));
  10306. }
  10307. } else {
  10308. // Can not be merged, start a new event.
  10309. var before = lst(hist.done);
  10310. if (!before || !before.ranges)
  10311. { pushSelectionToHistory(doc.sel, hist.done); }
  10312. cur = {changes: [historyChangeFromChange(doc, change)],
  10313. generation: hist.generation};
  10314. hist.done.push(cur);
  10315. while (hist.done.length > hist.undoDepth) {
  10316. hist.done.shift();
  10317. if (!hist.done[0].ranges) { hist.done.shift(); }
  10318. }
  10319. }
  10320. hist.done.push(selAfter);
  10321. hist.generation = ++hist.maxGeneration;
  10322. hist.lastModTime = hist.lastSelTime = time;
  10323. hist.lastOp = hist.lastSelOp = opId;
  10324. hist.lastOrigin = hist.lastSelOrigin = change.origin;
  10325. if (!last) { signal(doc, "historyAdded"); }
  10326. }
  10327. function selectionEventCanBeMerged(doc, origin, prev, sel) {
  10328. var ch = origin.charAt(0);
  10329. return ch == "*" ||
  10330. ch == "+" &&
  10331. prev.ranges.length == sel.ranges.length &&
  10332. prev.somethingSelected() == sel.somethingSelected() &&
  10333. new Date - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500)
  10334. }
  10335. // Called whenever the selection changes, sets the new selection as
  10336. // the pending selection in the history, and pushes the old pending
  10337. // selection into the 'done' array when it was significantly
  10338. // different (in number of selected ranges, emptiness, or time).
  10339. function addSelectionToHistory(doc, sel, opId, options) {
  10340. var hist = doc.history, origin = options && options.origin;
  10341. // A new event is started when the previous origin does not match
  10342. // the current, or the origins don't allow matching. Origins
  10343. // starting with * are always merged, those starting with + are
  10344. // merged when similar and close together in time.
  10345. if (opId == hist.lastSelOp ||
  10346. (origin && hist.lastSelOrigin == origin &&
  10347. (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin ||
  10348. selectionEventCanBeMerged(doc, origin, lst(hist.done), sel))))
  10349. { hist.done[hist.done.length - 1] = sel; }
  10350. else
  10351. { pushSelectionToHistory(sel, hist.done); }
  10352. hist.lastSelTime = +new Date;
  10353. hist.lastSelOrigin = origin;
  10354. hist.lastSelOp = opId;
  10355. if (options && options.clearRedo !== false)
  10356. { clearSelectionEvents(hist.undone); }
  10357. }
  10358. function pushSelectionToHistory(sel, dest) {
  10359. var top = lst(dest);
  10360. if (!(top && top.ranges && top.equals(sel)))
  10361. { dest.push(sel); }
  10362. }
  10363. // Used to store marked span information in the history.
  10364. function attachLocalSpans(doc, change, from, to) {
  10365. var existing = change["spans_" + doc.id], n = 0;
  10366. doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function (line) {
  10367. if (line.markedSpans)
  10368. { (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans; }
  10369. ++n;
  10370. });
  10371. }
  10372. // When un/re-doing restores text containing marked spans, those
  10373. // that have been explicitly cleared should not be restored.
  10374. function removeClearedSpans(spans) {
  10375. if (!spans) { return null }
  10376. var out;
  10377. for (var i = 0; i < spans.length; ++i) {
  10378. if (spans[i].marker.explicitlyCleared) { if (!out) { out = spans.slice(0, i); } }
  10379. else if (out) { out.push(spans[i]); }
  10380. }
  10381. return !out ? spans : out.length ? out : null
  10382. }
  10383. // Retrieve and filter the old marked spans stored in a change event.
  10384. function getOldSpans(doc, change) {
  10385. var found = change["spans_" + doc.id];
  10386. if (!found) { return null }
  10387. var nw = [];
  10388. for (var i = 0; i < change.text.length; ++i)
  10389. { nw.push(removeClearedSpans(found[i])); }
  10390. return nw
  10391. }
  10392. // Used for un/re-doing changes from the history. Combines the
  10393. // result of computing the existing spans with the set of spans that
  10394. // existed in the history (so that deleting around a span and then
  10395. // undoing brings back the span).
  10396. function mergeOldSpans(doc, change) {
  10397. var old = getOldSpans(doc, change);
  10398. var stretched = stretchSpansOverChange(doc, change);
  10399. if (!old) { return stretched }
  10400. if (!stretched) { return old }
  10401. for (var i = 0; i < old.length; ++i) {
  10402. var oldCur = old[i], stretchCur = stretched[i];
  10403. if (oldCur && stretchCur) {
  10404. spans: for (var j = 0; j < stretchCur.length; ++j) {
  10405. var span = stretchCur[j];
  10406. for (var k = 0; k < oldCur.length; ++k)
  10407. { if (oldCur[k].marker == span.marker) { continue spans } }
  10408. oldCur.push(span);
  10409. }
  10410. } else if (stretchCur) {
  10411. old[i] = stretchCur;
  10412. }
  10413. }
  10414. return old
  10415. }
  10416. // Used both to provide a JSON-safe object in .getHistory, and, when
  10417. // detaching a document, to split the history in two
  10418. function copyHistoryArray(events, newGroup, instantiateSel) {
  10419. var copy = [];
  10420. for (var i = 0; i < events.length; ++i) {
  10421. var event = events[i];
  10422. if (event.ranges) {
  10423. copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event);
  10424. continue
  10425. }
  10426. var changes = event.changes, newChanges = [];
  10427. copy.push({changes: newChanges});
  10428. for (var j = 0; j < changes.length; ++j) {
  10429. var change = changes[j], m = (void 0);
  10430. newChanges.push({from: change.from, to: change.to, text: change.text});
  10431. if (newGroup) { for (var prop in change) { if (m = prop.match(/^spans_(\d+)$/)) {
  10432. if (indexOf(newGroup, Number(m[1])) > -1) {
  10433. lst(newChanges)[prop] = change[prop];
  10434. delete change[prop];
  10435. }
  10436. } } }
  10437. }
  10438. }
  10439. return copy
  10440. }
  10441. // The 'scroll' parameter given to many of these indicated whether
  10442. // the new cursor position should be scrolled into view after
  10443. // modifying the selection.
  10444. // If shift is held or the extend flag is set, extends a range to
  10445. // include a given position (and optionally a second position).
  10446. // Otherwise, simply returns the range between the given positions.
  10447. // Used for cursor motion and such.
  10448. function extendRange(range, head, other, extend) {
  10449. if (extend) {
  10450. var anchor = range.anchor;
  10451. if (other) {
  10452. var posBefore = cmp(head, anchor) < 0;
  10453. if (posBefore != (cmp(other, anchor) < 0)) {
  10454. anchor = head;
  10455. head = other;
  10456. } else if (posBefore != (cmp(head, other) < 0)) {
  10457. head = other;
  10458. }
  10459. }
  10460. return new Range(anchor, head)
  10461. } else {
  10462. return new Range(other || head, head)
  10463. }
  10464. }
  10465. // Extend the primary selection range, discard the rest.
  10466. function extendSelection(doc, head, other, options, extend) {
  10467. if (extend == null) { extend = doc.cm && (doc.cm.display.shift || doc.extend); }
  10468. setSelection(doc, new Selection([extendRange(doc.sel.primary(), head, other, extend)], 0), options);
  10469. }
  10470. // Extend all selections (pos is an array of selections with length
  10471. // equal the number of selections)
  10472. function extendSelections(doc, heads, options) {
  10473. var out = [];
  10474. var extend = doc.cm && (doc.cm.display.shift || doc.extend);
  10475. for (var i = 0; i < doc.sel.ranges.length; i++)
  10476. { out[i] = extendRange(doc.sel.ranges[i], heads[i], null, extend); }
  10477. var newSel = normalizeSelection(out, doc.sel.primIndex);
  10478. setSelection(doc, newSel, options);
  10479. }
  10480. // Updates a single range in the selection.
  10481. function replaceOneSelection(doc, i, range, options) {
  10482. var ranges = doc.sel.ranges.slice(0);
  10483. ranges[i] = range;
  10484. setSelection(doc, normalizeSelection(ranges, doc.sel.primIndex), options);
  10485. }
  10486. // Reset the selection to a single range.
  10487. function setSimpleSelection(doc, anchor, head, options) {
  10488. setSelection(doc, simpleSelection(anchor, head), options);
  10489. }
  10490. // Give beforeSelectionChange handlers a change to influence a
  10491. // selection update.
  10492. function filterSelectionChange(doc, sel, options) {
  10493. var obj = {
  10494. ranges: sel.ranges,
  10495. update: function(ranges) {
  10496. var this$1 = this;
  10497. this.ranges = [];
  10498. for (var i = 0; i < ranges.length; i++)
  10499. { this$1.ranges[i] = new Range(clipPos(doc, ranges[i].anchor),
  10500. clipPos(doc, ranges[i].head)); }
  10501. },
  10502. origin: options && options.origin
  10503. };
  10504. signal(doc, "beforeSelectionChange", doc, obj);
  10505. if (doc.cm) { signal(doc.cm, "beforeSelectionChange", doc.cm, obj); }
  10506. if (obj.ranges != sel.ranges) { return normalizeSelection(obj.ranges, obj.ranges.length - 1) }
  10507. else { return sel }
  10508. }
  10509. function setSelectionReplaceHistory(doc, sel, options) {
  10510. var done = doc.history.done, last = lst(done);
  10511. if (last && last.ranges) {
  10512. done[done.length - 1] = sel;
  10513. setSelectionNoUndo(doc, sel, options);
  10514. } else {
  10515. setSelection(doc, sel, options);
  10516. }
  10517. }
  10518. // Set a new selection.
  10519. function setSelection(doc, sel, options) {
  10520. setSelectionNoUndo(doc, sel, options);
  10521. addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options);
  10522. }
  10523. function setSelectionNoUndo(doc, sel, options) {
  10524. if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange"))
  10525. { sel = filterSelectionChange(doc, sel, options); }
  10526. var bias = options && options.bias ||
  10527. (cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1);
  10528. setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true));
  10529. if (!(options && options.scroll === false) && doc.cm)
  10530. { ensureCursorVisible(doc.cm); }
  10531. }
  10532. function setSelectionInner(doc, sel) {
  10533. if (sel.equals(doc.sel)) { return }
  10534. doc.sel = sel;
  10535. if (doc.cm) {
  10536. doc.cm.curOp.updateInput = doc.cm.curOp.selectionChanged = true;
  10537. signalCursorActivity(doc.cm);
  10538. }
  10539. signalLater(doc, "cursorActivity", doc);
  10540. }
  10541. // Verify that the selection does not partially select any atomic
  10542. // marked ranges.
  10543. function reCheckSelection(doc) {
  10544. setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false));
  10545. }
  10546. // Return a selection that does not partially select any atomic
  10547. // ranges.
  10548. function skipAtomicInSelection(doc, sel, bias, mayClear) {
  10549. var out;
  10550. for (var i = 0; i < sel.ranges.length; i++) {
  10551. var range = sel.ranges[i];
  10552. var old = sel.ranges.length == doc.sel.ranges.length && doc.sel.ranges[i];
  10553. var newAnchor = skipAtomic(doc, range.anchor, old && old.anchor, bias, mayClear);
  10554. var newHead = skipAtomic(doc, range.head, old && old.head, bias, mayClear);
  10555. if (out || newAnchor != range.anchor || newHead != range.head) {
  10556. if (!out) { out = sel.ranges.slice(0, i); }
  10557. out[i] = new Range(newAnchor, newHead);
  10558. }
  10559. }
  10560. return out ? normalizeSelection(out, sel.primIndex) : sel
  10561. }
  10562. function skipAtomicInner(doc, pos, oldPos, dir, mayClear) {
  10563. var line = getLine(doc, pos.line);
  10564. if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) {
  10565. var sp = line.markedSpans[i], m = sp.marker;
  10566. if ((sp.from == null || (m.inclusiveLeft ? sp.from <= pos.ch : sp.from < pos.ch)) &&
  10567. (sp.to == null || (m.inclusiveRight ? sp.to >= pos.ch : sp.to > pos.ch))) {
  10568. if (mayClear) {
  10569. signal(m, "beforeCursorEnter");
  10570. if (m.explicitlyCleared) {
  10571. if (!line.markedSpans) { break }
  10572. else {--i; continue}
  10573. }
  10574. }
  10575. if (!m.atomic) { continue }
  10576. if (oldPos) {
  10577. var near = m.find(dir < 0 ? 1 : -1), diff = (void 0);
  10578. if (dir < 0 ? m.inclusiveRight : m.inclusiveLeft)
  10579. { near = movePos(doc, near, -dir, near && near.line == pos.line ? line : null); }
  10580. if (near && near.line == pos.line && (diff = cmp(near, oldPos)) && (dir < 0 ? diff < 0 : diff > 0))
  10581. { return skipAtomicInner(doc, near, pos, dir, mayClear) }
  10582. }
  10583. var far = m.find(dir < 0 ? -1 : 1);
  10584. if (dir < 0 ? m.inclusiveLeft : m.inclusiveRight)
  10585. { far = movePos(doc, far, dir, far.line == pos.line ? line : null); }
  10586. return far ? skipAtomicInner(doc, far, pos, dir, mayClear) : null
  10587. }
  10588. } }
  10589. return pos
  10590. }
  10591. // Ensure a given position is not inside an atomic range.
  10592. function skipAtomic(doc, pos, oldPos, bias, mayClear) {
  10593. var dir = bias || 1;
  10594. var found = skipAtomicInner(doc, pos, oldPos, dir, mayClear) ||
  10595. (!mayClear && skipAtomicInner(doc, pos, oldPos, dir, true)) ||
  10596. skipAtomicInner(doc, pos, oldPos, -dir, mayClear) ||
  10597. (!mayClear && skipAtomicInner(doc, pos, oldPos, -dir, true));
  10598. if (!found) {
  10599. doc.cantEdit = true;
  10600. return Pos(doc.first, 0)
  10601. }
  10602. return found
  10603. }
  10604. function movePos(doc, pos, dir, line) {
  10605. if (dir < 0 && pos.ch == 0) {
  10606. if (pos.line > doc.first) { return clipPos(doc, Pos(pos.line - 1)) }
  10607. else { return null }
  10608. } else if (dir > 0 && pos.ch == (line || getLine(doc, pos.line)).text.length) {
  10609. if (pos.line < doc.first + doc.size - 1) { return Pos(pos.line + 1, 0) }
  10610. else { return null }
  10611. } else {
  10612. return new Pos(pos.line, pos.ch + dir)
  10613. }
  10614. }
  10615. function selectAll(cm) {
  10616. cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll);
  10617. }
  10618. // UPDATING
  10619. // Allow "beforeChange" event handlers to influence a change
  10620. function filterChange(doc, change, update) {
  10621. var obj = {
  10622. canceled: false,
  10623. from: change.from,
  10624. to: change.to,
  10625. text: change.text,
  10626. origin: change.origin,
  10627. cancel: function () { return obj.canceled = true; }
  10628. };
  10629. if (update) { obj.update = function (from, to, text, origin) {
  10630. if (from) { obj.from = clipPos(doc, from); }
  10631. if (to) { obj.to = clipPos(doc, to); }
  10632. if (text) { obj.text = text; }
  10633. if (origin !== undefined) { obj.origin = origin; }
  10634. }; }
  10635. signal(doc, "beforeChange", doc, obj);
  10636. if (doc.cm) { signal(doc.cm, "beforeChange", doc.cm, obj); }
  10637. if (obj.canceled) { return null }
  10638. return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin}
  10639. }
  10640. // Apply a change to a document, and add it to the document's
  10641. // history, and propagating it to all linked documents.
  10642. function makeChange(doc, change, ignoreReadOnly) {
  10643. if (doc.cm) {
  10644. if (!doc.cm.curOp) { return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly) }
  10645. if (doc.cm.state.suppressEdits) { return }
  10646. }
  10647. if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) {
  10648. change = filterChange(doc, change, true);
  10649. if (!change) { return }
  10650. }
  10651. // Possibly split or suppress the update based on the presence
  10652. // of read-only spans in its range.
  10653. var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to);
  10654. if (split) {
  10655. for (var i = split.length - 1; i >= 0; --i)
  10656. { makeChangeInner(doc, {from: split[i].from, to: split[i].to, text: i ? [""] : change.text, origin: change.origin}); }
  10657. } else {
  10658. makeChangeInner(doc, change);
  10659. }
  10660. }
  10661. function makeChangeInner(doc, change) {
  10662. if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) { return }
  10663. var selAfter = computeSelAfterChange(doc, change);
  10664. addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN);
  10665. makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change));
  10666. var rebased = [];
  10667. linkedDocs(doc, function (doc, sharedHist) {
  10668. if (!sharedHist && indexOf(rebased, doc.history) == -1) {
  10669. rebaseHist(doc.history, change);
  10670. rebased.push(doc.history);
  10671. }
  10672. makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change));
  10673. });
  10674. }
  10675. // Revert a change stored in a document's history.
  10676. function makeChangeFromHistory(doc, type, allowSelectionOnly) {
  10677. if (doc.cm && doc.cm.state.suppressEdits && !allowSelectionOnly) { return }
  10678. var hist = doc.history, event, selAfter = doc.sel;
  10679. var source = type == "undo" ? hist.done : hist.undone, dest = type == "undo" ? hist.undone : hist.done;
  10680. // Verify that there is a useable event (so that ctrl-z won't
  10681. // needlessly clear selection events)
  10682. var i = 0;
  10683. for (; i < source.length; i++) {
  10684. event = source[i];
  10685. if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges)
  10686. { break }
  10687. }
  10688. if (i == source.length) { return }
  10689. hist.lastOrigin = hist.lastSelOrigin = null;
  10690. for (;;) {
  10691. event = source.pop();
  10692. if (event.ranges) {
  10693. pushSelectionToHistory(event, dest);
  10694. if (allowSelectionOnly && !event.equals(doc.sel)) {
  10695. setSelection(doc, event, {clearRedo: false});
  10696. return
  10697. }
  10698. selAfter = event;
  10699. }
  10700. else { break }
  10701. }
  10702. // Build up a reverse change object to add to the opposite history
  10703. // stack (redo when undoing, and vice versa).
  10704. var antiChanges = [];
  10705. pushSelectionToHistory(selAfter, dest);
  10706. dest.push({changes: antiChanges, generation: hist.generation});
  10707. hist.generation = event.generation || ++hist.maxGeneration;
  10708. var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange");
  10709. var loop = function ( i ) {
  10710. var change = event.changes[i];
  10711. change.origin = type;
  10712. if (filter && !filterChange(doc, change, false)) {
  10713. source.length = 0;
  10714. return {}
  10715. }
  10716. antiChanges.push(historyChangeFromChange(doc, change));
  10717. var after = i ? computeSelAfterChange(doc, change) : lst(source);
  10718. makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change));
  10719. if (!i && doc.cm) { doc.cm.scrollIntoView({from: change.from, to: changeEnd(change)}); }
  10720. var rebased = [];
  10721. // Propagate to the linked documents
  10722. linkedDocs(doc, function (doc, sharedHist) {
  10723. if (!sharedHist && indexOf(rebased, doc.history) == -1) {
  10724. rebaseHist(doc.history, change);
  10725. rebased.push(doc.history);
  10726. }
  10727. makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change));
  10728. });
  10729. };
  10730. for (var i$1 = event.changes.length - 1; i$1 >= 0; --i$1) {
  10731. var returned = loop( i$1 );
  10732. if ( returned ) return returned.v;
  10733. }
  10734. }
  10735. // Sub-views need their line numbers shifted when text is added
  10736. // above or below them in the parent document.
  10737. function shiftDoc(doc, distance) {
  10738. if (distance == 0) { return }
  10739. doc.first += distance;
  10740. doc.sel = new Selection(map(doc.sel.ranges, function (range) { return new Range(
  10741. Pos(range.anchor.line + distance, range.anchor.ch),
  10742. Pos(range.head.line + distance, range.head.ch)
  10743. ); }), doc.sel.primIndex);
  10744. if (doc.cm) {
  10745. regChange(doc.cm, doc.first, doc.first - distance, distance);
  10746. for (var d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++)
  10747. { regLineChange(doc.cm, l, "gutter"); }
  10748. }
  10749. }
  10750. // More lower-level change function, handling only a single document
  10751. // (not linked ones).
  10752. function makeChangeSingleDoc(doc, change, selAfter, spans) {
  10753. if (doc.cm && !doc.cm.curOp)
  10754. { return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans) }
  10755. if (change.to.line < doc.first) {
  10756. shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line));
  10757. return
  10758. }
  10759. if (change.from.line > doc.lastLine()) { return }
  10760. // Clip the change to the size of this doc
  10761. if (change.from.line < doc.first) {
  10762. var shift = change.text.length - 1 - (doc.first - change.from.line);
  10763. shiftDoc(doc, shift);
  10764. change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch),
  10765. text: [lst(change.text)], origin: change.origin};
  10766. }
  10767. var last = doc.lastLine();
  10768. if (change.to.line > last) {
  10769. change = {from: change.from, to: Pos(last, getLine(doc, last).text.length),
  10770. text: [change.text[0]], origin: change.origin};
  10771. }
  10772. change.removed = getBetween(doc, change.from, change.to);
  10773. if (!selAfter) { selAfter = computeSelAfterChange(doc, change); }
  10774. if (doc.cm) { makeChangeSingleDocInEditor(doc.cm, change, spans); }
  10775. else { updateDoc(doc, change, spans); }
  10776. setSelectionNoUndo(doc, selAfter, sel_dontScroll);
  10777. }
  10778. // Handle the interaction of a change to a document with the editor
  10779. // that this document is part of.
  10780. function makeChangeSingleDocInEditor(cm, change, spans) {
  10781. var doc = cm.doc, display = cm.display, from = change.from, to = change.to;
  10782. var recomputeMaxLength = false, checkWidthStart = from.line;
  10783. if (!cm.options.lineWrapping) {
  10784. checkWidthStart = lineNo(visualLine(getLine(doc, from.line)));
  10785. doc.iter(checkWidthStart, to.line + 1, function (line) {
  10786. if (line == display.maxLine) {
  10787. recomputeMaxLength = true;
  10788. return true
  10789. }
  10790. });
  10791. }
  10792. if (doc.sel.contains(change.from, change.to) > -1)
  10793. { signalCursorActivity(cm); }
  10794. updateDoc(doc, change, spans, estimateHeight(cm));
  10795. if (!cm.options.lineWrapping) {
  10796. doc.iter(checkWidthStart, from.line + change.text.length, function (line) {
  10797. var len = lineLength(line);
  10798. if (len > display.maxLineLength) {
  10799. display.maxLine = line;
  10800. display.maxLineLength = len;
  10801. display.maxLineChanged = true;
  10802. recomputeMaxLength = false;
  10803. }
  10804. });
  10805. if (recomputeMaxLength) { cm.curOp.updateMaxLine = true; }
  10806. }
  10807. retreatFrontier(doc, from.line);
  10808. startWorker(cm, 400);
  10809. var lendiff = change.text.length - (to.line - from.line) - 1;
  10810. // Remember that these lines changed, for updating the display
  10811. if (change.full)
  10812. { regChange(cm); }
  10813. else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change))
  10814. { regLineChange(cm, from.line, "text"); }
  10815. else
  10816. { regChange(cm, from.line, to.line + 1, lendiff); }
  10817. var changesHandler = hasHandler(cm, "changes"), changeHandler = hasHandler(cm, "change");
  10818. if (changeHandler || changesHandler) {
  10819. var obj = {
  10820. from: from, to: to,
  10821. text: change.text,
  10822. removed: change.removed,
  10823. origin: change.origin
  10824. };
  10825. if (changeHandler) { signalLater(cm, "change", cm, obj); }
  10826. if (changesHandler) { (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj); }
  10827. }
  10828. cm.display.selForContextMenu = null;
  10829. }
  10830. function replaceRange(doc, code, from, to, origin) {
  10831. if (!to) { to = from; }
  10832. if (cmp(to, from) < 0) { var assign;
  10833. (assign = [to, from], from = assign[0], to = assign[1], assign); }
  10834. if (typeof code == "string") { code = doc.splitLines(code); }
  10835. makeChange(doc, {from: from, to: to, text: code, origin: origin});
  10836. }
  10837. // Rebasing/resetting history to deal with externally-sourced changes
  10838. function rebaseHistSelSingle(pos, from, to, diff) {
  10839. if (to < pos.line) {
  10840. pos.line += diff;
  10841. } else if (from < pos.line) {
  10842. pos.line = from;
  10843. pos.ch = 0;
  10844. }
  10845. }
  10846. // Tries to rebase an array of history events given a change in the
  10847. // document. If the change touches the same lines as the event, the
  10848. // event, and everything 'behind' it, is discarded. If the change is
  10849. // before the event, the event's positions are updated. Uses a
  10850. // copy-on-write scheme for the positions, to avoid having to
  10851. // reallocate them all on every rebase, but also avoid problems with
  10852. // shared position objects being unsafely updated.
  10853. function rebaseHistArray(array, from, to, diff) {
  10854. for (var i = 0; i < array.length; ++i) {
  10855. var sub = array[i], ok = true;
  10856. if (sub.ranges) {
  10857. if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true; }
  10858. for (var j = 0; j < sub.ranges.length; j++) {
  10859. rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff);
  10860. rebaseHistSelSingle(sub.ranges[j].head, from, to, diff);
  10861. }
  10862. continue
  10863. }
  10864. for (var j$1 = 0; j$1 < sub.changes.length; ++j$1) {
  10865. var cur = sub.changes[j$1];
  10866. if (to < cur.from.line) {
  10867. cur.from = Pos(cur.from.line + diff, cur.from.ch);
  10868. cur.to = Pos(cur.to.line + diff, cur.to.ch);
  10869. } else if (from <= cur.to.line) {
  10870. ok = false;
  10871. break
  10872. }
  10873. }
  10874. if (!ok) {
  10875. array.splice(0, i + 1);
  10876. i = 0;
  10877. }
  10878. }
  10879. }
  10880. function rebaseHist(hist, change) {
  10881. var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1;
  10882. rebaseHistArray(hist.done, from, to, diff);
  10883. rebaseHistArray(hist.undone, from, to, diff);
  10884. }
  10885. // Utility for applying a change to a line by handle or number,
  10886. // returning the number and optionally registering the line as
  10887. // changed.
  10888. function changeLine(doc, handle, changeType, op) {
  10889. var no = handle, line = handle;
  10890. if (typeof handle == "number") { line = getLine(doc, clipLine(doc, handle)); }
  10891. else { no = lineNo(handle); }
  10892. if (no == null) { return null }
  10893. if (op(line, no) && doc.cm) { regLineChange(doc.cm, no, changeType); }
  10894. return line
  10895. }
  10896. // The document is represented as a BTree consisting of leaves, with
  10897. // chunk of lines in them, and branches, with up to ten leaves or
  10898. // other branch nodes below them. The top node is always a branch
  10899. // node, and is the document object itself (meaning it has
  10900. // additional methods and properties).
  10901. //
  10902. // All nodes have parent links. The tree is used both to go from
  10903. // line numbers to line objects, and to go from objects to numbers.
  10904. // It also indexes by height, and is used to convert between height
  10905. // and line object, and to find the total height of the document.
  10906. //
  10907. // See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html
  10908. function LeafChunk(lines) {
  10909. var this$1 = this;
  10910. this.lines = lines;
  10911. this.parent = null;
  10912. var height = 0;
  10913. for (var i = 0; i < lines.length; ++i) {
  10914. lines[i].parent = this$1;
  10915. height += lines[i].height;
  10916. }
  10917. this.height = height;
  10918. }
  10919. LeafChunk.prototype = {
  10920. chunkSize: function chunkSize() { return this.lines.length },
  10921. // Remove the n lines at offset 'at'.
  10922. removeInner: function removeInner(at, n) {
  10923. var this$1 = this;
  10924. for (var i = at, e = at + n; i < e; ++i) {
  10925. var line = this$1.lines[i];
  10926. this$1.height -= line.height;
  10927. cleanUpLine(line);
  10928. signalLater(line, "delete");
  10929. }
  10930. this.lines.splice(at, n);
  10931. },
  10932. // Helper used to collapse a small branch into a single leaf.
  10933. collapse: function collapse(lines) {
  10934. lines.push.apply(lines, this.lines);
  10935. },
  10936. // Insert the given array of lines at offset 'at', count them as
  10937. // having the given height.
  10938. insertInner: function insertInner(at, lines, height) {
  10939. var this$1 = this;
  10940. this.height += height;
  10941. this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at));
  10942. for (var i = 0; i < lines.length; ++i) { lines[i].parent = this$1; }
  10943. },
  10944. // Used to iterate over a part of the tree.
  10945. iterN: function iterN(at, n, op) {
  10946. var this$1 = this;
  10947. for (var e = at + n; at < e; ++at)
  10948. { if (op(this$1.lines[at])) { return true } }
  10949. }
  10950. };
  10951. function BranchChunk(children) {
  10952. var this$1 = this;
  10953. this.children = children;
  10954. var size = 0, height = 0;
  10955. for (var i = 0; i < children.length; ++i) {
  10956. var ch = children[i];
  10957. size += ch.chunkSize(); height += ch.height;
  10958. ch.parent = this$1;
  10959. }
  10960. this.size = size;
  10961. this.height = height;
  10962. this.parent = null;
  10963. }
  10964. BranchChunk.prototype = {
  10965. chunkSize: function chunkSize() { return this.size },
  10966. removeInner: function removeInner(at, n) {
  10967. var this$1 = this;
  10968. this.size -= n;
  10969. for (var i = 0; i < this.children.length; ++i) {
  10970. var child = this$1.children[i], sz = child.chunkSize();
  10971. if (at < sz) {
  10972. var rm = Math.min(n, sz - at), oldHeight = child.height;
  10973. child.removeInner(at, rm);
  10974. this$1.height -= oldHeight - child.height;
  10975. if (sz == rm) { this$1.children.splice(i--, 1); child.parent = null; }
  10976. if ((n -= rm) == 0) { break }
  10977. at = 0;
  10978. } else { at -= sz; }
  10979. }
  10980. // If the result is smaller than 25 lines, ensure that it is a
  10981. // single leaf node.
  10982. if (this.size - n < 25 &&
  10983. (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) {
  10984. var lines = [];
  10985. this.collapse(lines);
  10986. this.children = [new LeafChunk(lines)];
  10987. this.children[0].parent = this;
  10988. }
  10989. },
  10990. collapse: function collapse(lines) {
  10991. var this$1 = this;
  10992. for (var i = 0; i < this.children.length; ++i) { this$1.children[i].collapse(lines); }
  10993. },
  10994. insertInner: function insertInner(at, lines, height) {
  10995. var this$1 = this;
  10996. this.size += lines.length;
  10997. this.height += height;
  10998. for (var i = 0; i < this.children.length; ++i) {
  10999. var child = this$1.children[i], sz = child.chunkSize();
  11000. if (at <= sz) {
  11001. child.insertInner(at, lines, height);
  11002. if (child.lines && child.lines.length > 50) {
  11003. // To avoid memory thrashing when child.lines is huge (e.g. first view of a large file), it's never spliced.
  11004. // Instead, small slices are taken. They're taken in order because sequential memory accesses are fastest.
  11005. var remaining = child.lines.length % 25 + 25;
  11006. for (var pos = remaining; pos < child.lines.length;) {
  11007. var leaf = new LeafChunk(child.lines.slice(pos, pos += 25));
  11008. child.height -= leaf.height;
  11009. this$1.children.splice(++i, 0, leaf);
  11010. leaf.parent = this$1;
  11011. }
  11012. child.lines = child.lines.slice(0, remaining);
  11013. this$1.maybeSpill();
  11014. }
  11015. break
  11016. }
  11017. at -= sz;
  11018. }
  11019. },
  11020. // When a node has grown, check whether it should be split.
  11021. maybeSpill: function maybeSpill() {
  11022. if (this.children.length <= 10) { return }
  11023. var me = this;
  11024. do {
  11025. var spilled = me.children.splice(me.children.length - 5, 5);
  11026. var sibling = new BranchChunk(spilled);
  11027. if (!me.parent) { // Become the parent node
  11028. var copy = new BranchChunk(me.children);
  11029. copy.parent = me;
  11030. me.children = [copy, sibling];
  11031. me = copy;
  11032. } else {
  11033. me.size -= sibling.size;
  11034. me.height -= sibling.height;
  11035. var myIndex = indexOf(me.parent.children, me);
  11036. me.parent.children.splice(myIndex + 1, 0, sibling);
  11037. }
  11038. sibling.parent = me.parent;
  11039. } while (me.children.length > 10)
  11040. me.parent.maybeSpill();
  11041. },
  11042. iterN: function iterN(at, n, op) {
  11043. var this$1 = this;
  11044. for (var i = 0; i < this.children.length; ++i) {
  11045. var child = this$1.children[i], sz = child.chunkSize();
  11046. if (at < sz) {
  11047. var used = Math.min(n, sz - at);
  11048. if (child.iterN(at, used, op)) { return true }
  11049. if ((n -= used) == 0) { break }
  11050. at = 0;
  11051. } else { at -= sz; }
  11052. }
  11053. }
  11054. };
  11055. // Line widgets are block elements displayed above or below a line.
  11056. var LineWidget = function(doc, node, options) {
  11057. var this$1 = this;
  11058. if (options) { for (var opt in options) { if (options.hasOwnProperty(opt))
  11059. { this$1[opt] = options[opt]; } } }
  11060. this.doc = doc;
  11061. this.node = node;
  11062. };
  11063. LineWidget.prototype.clear = function () {
  11064. var this$1 = this;
  11065. var cm = this.doc.cm, ws = this.line.widgets, line = this.line, no = lineNo(line);
  11066. if (no == null || !ws) { return }
  11067. for (var i = 0; i < ws.length; ++i) { if (ws[i] == this$1) { ws.splice(i--, 1); } }
  11068. if (!ws.length) { line.widgets = null; }
  11069. var height = widgetHeight(this);
  11070. updateLineHeight(line, Math.max(0, line.height - height));
  11071. if (cm) {
  11072. runInOp(cm, function () {
  11073. adjustScrollWhenAboveVisible(cm, line, -height);
  11074. regLineChange(cm, no, "widget");
  11075. });
  11076. signalLater(cm, "lineWidgetCleared", cm, this, no);
  11077. }
  11078. };
  11079. LineWidget.prototype.changed = function () {
  11080. var this$1 = this;
  11081. var oldH = this.height, cm = this.doc.cm, line = this.line;
  11082. this.height = null;
  11083. var diff = widgetHeight(this) - oldH;
  11084. if (!diff) { return }
  11085. updateLineHeight(line, line.height + diff);
  11086. if (cm) {
  11087. runInOp(cm, function () {
  11088. cm.curOp.forceUpdate = true;
  11089. adjustScrollWhenAboveVisible(cm, line, diff);
  11090. signalLater(cm, "lineWidgetChanged", cm, this$1, lineNo(line));
  11091. });
  11092. }
  11093. };
  11094. eventMixin(LineWidget);
  11095. function adjustScrollWhenAboveVisible(cm, line, diff) {
  11096. if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop))
  11097. { addToScrollTop(cm, diff); }
  11098. }
  11099. function addLineWidget(doc, handle, node, options) {
  11100. var widget = new LineWidget(doc, node, options);
  11101. var cm = doc.cm;
  11102. if (cm && widget.noHScroll) { cm.display.alignWidgets = true; }
  11103. changeLine(doc, handle, "widget", function (line) {
  11104. var widgets = line.widgets || (line.widgets = []);
  11105. if (widget.insertAt == null) { widgets.push(widget); }
  11106. else { widgets.splice(Math.min(widgets.length - 1, Math.max(0, widget.insertAt)), 0, widget); }
  11107. widget.line = line;
  11108. if (cm && !lineIsHidden(doc, line)) {
  11109. var aboveVisible = heightAtLine(line) < doc.scrollTop;
  11110. updateLineHeight(line, line.height + widgetHeight(widget));
  11111. if (aboveVisible) { addToScrollTop(cm, widget.height); }
  11112. cm.curOp.forceUpdate = true;
  11113. }
  11114. return true
  11115. });
  11116. signalLater(cm, "lineWidgetAdded", cm, widget, typeof handle == "number" ? handle : lineNo(handle));
  11117. return widget
  11118. }
  11119. // TEXTMARKERS
  11120. // Created with markText and setBookmark methods. A TextMarker is a
  11121. // handle that can be used to clear or find a marked position in the
  11122. // document. Line objects hold arrays (markedSpans) containing
  11123. // {from, to, marker} object pointing to such marker objects, and
  11124. // indicating that such a marker is present on that line. Multiple
  11125. // lines may point to the same marker when it spans across lines.
  11126. // The spans will have null for their from/to properties when the
  11127. // marker continues beyond the start/end of the line. Markers have
  11128. // links back to the lines they currently touch.
  11129. // Collapsed markers have unique ids, in order to be able to order
  11130. // them, which is needed for uniquely determining an outer marker
  11131. // when they overlap (they may nest, but not partially overlap).
  11132. var nextMarkerId = 0;
  11133. var TextMarker = function(doc, type) {
  11134. this.lines = [];
  11135. this.type = type;
  11136. this.doc = doc;
  11137. this.id = ++nextMarkerId;
  11138. };
  11139. // Clear the marker.
  11140. TextMarker.prototype.clear = function () {
  11141. var this$1 = this;
  11142. if (this.explicitlyCleared) { return }
  11143. var cm = this.doc.cm, withOp = cm && !cm.curOp;
  11144. if (withOp) { startOperation(cm); }
  11145. if (hasHandler(this, "clear")) {
  11146. var found = this.find();
  11147. if (found) { signalLater(this, "clear", found.from, found.to); }
  11148. }
  11149. var min = null, max = null;
  11150. for (var i = 0; i < this.lines.length; ++i) {
  11151. var line = this$1.lines[i];
  11152. var span = getMarkedSpanFor(line.markedSpans, this$1);
  11153. if (cm && !this$1.collapsed) { regLineChange(cm, lineNo(line), "text"); }
  11154. else if (cm) {
  11155. if (span.to != null) { max = lineNo(line); }
  11156. if (span.from != null) { min = lineNo(line); }
  11157. }
  11158. line.markedSpans = removeMarkedSpan(line.markedSpans, span);
  11159. if (span.from == null && this$1.collapsed && !lineIsHidden(this$1.doc, line) && cm)
  11160. { updateLineHeight(line, textHeight(cm.display)); }
  11161. }
  11162. if (cm && this.collapsed && !cm.options.lineWrapping) { for (var i$1 = 0; i$1 < this.lines.length; ++i$1) {
  11163. var visual = visualLine(this$1.lines[i$1]), len = lineLength(visual);
  11164. if (len > cm.display.maxLineLength) {
  11165. cm.display.maxLine = visual;
  11166. cm.display.maxLineLength = len;
  11167. cm.display.maxLineChanged = true;
  11168. }
  11169. } }
  11170. if (min != null && cm && this.collapsed) { regChange(cm, min, max + 1); }
  11171. this.lines.length = 0;
  11172. this.explicitlyCleared = true;
  11173. if (this.atomic && this.doc.cantEdit) {
  11174. this.doc.cantEdit = false;
  11175. if (cm) { reCheckSelection(cm.doc); }
  11176. }
  11177. if (cm) { signalLater(cm, "markerCleared", cm, this, min, max); }
  11178. if (withOp) { endOperation(cm); }
  11179. if (this.parent) { this.parent.clear(); }
  11180. };
  11181. // Find the position of the marker in the document. Returns a {from,
  11182. // to} object by default. Side can be passed to get a specific side
  11183. // -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the
  11184. // Pos objects returned contain a line object, rather than a line
  11185. // number (used to prevent looking up the same line twice).
  11186. TextMarker.prototype.find = function (side, lineObj) {
  11187. var this$1 = this;
  11188. if (side == null && this.type == "bookmark") { side = 1; }
  11189. var from, to;
  11190. for (var i = 0; i < this.lines.length; ++i) {
  11191. var line = this$1.lines[i];
  11192. var span = getMarkedSpanFor(line.markedSpans, this$1);
  11193. if (span.from != null) {
  11194. from = Pos(lineObj ? line : lineNo(line), span.from);
  11195. if (side == -1) { return from }
  11196. }
  11197. if (span.to != null) {
  11198. to = Pos(lineObj ? line : lineNo(line), span.to);
  11199. if (side == 1) { return to }
  11200. }
  11201. }
  11202. return from && {from: from, to: to}
  11203. };
  11204. // Signals that the marker's widget changed, and surrounding layout
  11205. // should be recomputed.
  11206. TextMarker.prototype.changed = function () {
  11207. var this$1 = this;
  11208. var pos = this.find(-1, true), widget = this, cm = this.doc.cm;
  11209. if (!pos || !cm) { return }
  11210. runInOp(cm, function () {
  11211. var line = pos.line, lineN = lineNo(pos.line);
  11212. var view = findViewForLine(cm, lineN);
  11213. if (view) {
  11214. clearLineMeasurementCacheFor(view);
  11215. cm.curOp.selectionChanged = cm.curOp.forceUpdate = true;
  11216. }
  11217. cm.curOp.updateMaxLine = true;
  11218. if (!lineIsHidden(widget.doc, line) && widget.height != null) {
  11219. var oldHeight = widget.height;
  11220. widget.height = null;
  11221. var dHeight = widgetHeight(widget) - oldHeight;
  11222. if (dHeight)
  11223. { updateLineHeight(line, line.height + dHeight); }
  11224. }
  11225. signalLater(cm, "markerChanged", cm, this$1);
  11226. });
  11227. };
  11228. TextMarker.prototype.attachLine = function (line) {
  11229. if (!this.lines.length && this.doc.cm) {
  11230. var op = this.doc.cm.curOp;
  11231. if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1)
  11232. { (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this); }
  11233. }
  11234. this.lines.push(line);
  11235. };
  11236. TextMarker.prototype.detachLine = function (line) {
  11237. this.lines.splice(indexOf(this.lines, line), 1);
  11238. if (!this.lines.length && this.doc.cm) {
  11239. var op = this.doc.cm.curOp;(op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this);
  11240. }
  11241. };
  11242. eventMixin(TextMarker);
  11243. // Create a marker, wire it up to the right lines, and
  11244. function markText(doc, from, to, options, type) {
  11245. // Shared markers (across linked documents) are handled separately
  11246. // (markTextShared will call out to this again, once per
  11247. // document).
  11248. if (options && options.shared) { return markTextShared(doc, from, to, options, type) }
  11249. // Ensure we are in an operation.
  11250. if (doc.cm && !doc.cm.curOp) { return operation(doc.cm, markText)(doc, from, to, options, type) }
  11251. var marker = new TextMarker(doc, type), diff = cmp(from, to);
  11252. if (options) { copyObj(options, marker, false); }
  11253. // Don't connect empty markers unless clearWhenEmpty is false
  11254. if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false)
  11255. { return marker }
  11256. if (marker.replacedWith) {
  11257. // Showing up as a widget implies collapsed (widget replaces text)
  11258. marker.collapsed = true;
  11259. marker.widgetNode = eltP("span", [marker.replacedWith], "CodeMirror-widget");
  11260. if (!options.handleMouseEvents) { marker.widgetNode.setAttribute("cm-ignore-events", "true"); }
  11261. if (options.insertLeft) { marker.widgetNode.insertLeft = true; }
  11262. }
  11263. if (marker.collapsed) {
  11264. if (conflictingCollapsedRange(doc, from.line, from, to, marker) ||
  11265. from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker))
  11266. { throw new Error("Inserting collapsed marker partially overlapping an existing one") }
  11267. seeCollapsedSpans();
  11268. }
  11269. if (marker.addToHistory)
  11270. { addChangeToHistory(doc, {from: from, to: to, origin: "markText"}, doc.sel, NaN); }
  11271. var curLine = from.line, cm = doc.cm, updateMaxLine;
  11272. doc.iter(curLine, to.line + 1, function (line) {
  11273. if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine)
  11274. { updateMaxLine = true; }
  11275. if (marker.collapsed && curLine != from.line) { updateLineHeight(line, 0); }
  11276. addMarkedSpan(line, new MarkedSpan(marker,
  11277. curLine == from.line ? from.ch : null,
  11278. curLine == to.line ? to.ch : null));
  11279. ++curLine;
  11280. });
  11281. // lineIsHidden depends on the presence of the spans, so needs a second pass
  11282. if (marker.collapsed) { doc.iter(from.line, to.line + 1, function (line) {
  11283. if (lineIsHidden(doc, line)) { updateLineHeight(line, 0); }
  11284. }); }
  11285. if (marker.clearOnEnter) { on(marker, "beforeCursorEnter", function () { return marker.clear(); }); }
  11286. if (marker.readOnly) {
  11287. seeReadOnlySpans();
  11288. if (doc.history.done.length || doc.history.undone.length)
  11289. { doc.clearHistory(); }
  11290. }
  11291. if (marker.collapsed) {
  11292. marker.id = ++nextMarkerId;
  11293. marker.atomic = true;
  11294. }
  11295. if (cm) {
  11296. // Sync editor state
  11297. if (updateMaxLine) { cm.curOp.updateMaxLine = true; }
  11298. if (marker.collapsed)
  11299. { regChange(cm, from.line, to.line + 1); }
  11300. else if (marker.className || marker.title || marker.startStyle || marker.endStyle || marker.css)
  11301. { for (var i = from.line; i <= to.line; i++) { regLineChange(cm, i, "text"); } }
  11302. if (marker.atomic) { reCheckSelection(cm.doc); }
  11303. signalLater(cm, "markerAdded", cm, marker);
  11304. }
  11305. return marker
  11306. }
  11307. // SHARED TEXTMARKERS
  11308. // A shared marker spans multiple linked documents. It is
  11309. // implemented as a meta-marker-object controlling multiple normal
  11310. // markers.
  11311. var SharedTextMarker = function(markers, primary) {
  11312. var this$1 = this;
  11313. this.markers = markers;
  11314. this.primary = primary;
  11315. for (var i = 0; i < markers.length; ++i)
  11316. { markers[i].parent = this$1; }
  11317. };
  11318. SharedTextMarker.prototype.clear = function () {
  11319. var this$1 = this;
  11320. if (this.explicitlyCleared) { return }
  11321. this.explicitlyCleared = true;
  11322. for (var i = 0; i < this.markers.length; ++i)
  11323. { this$1.markers[i].clear(); }
  11324. signalLater(this, "clear");
  11325. };
  11326. SharedTextMarker.prototype.find = function (side, lineObj) {
  11327. return this.primary.find(side, lineObj)
  11328. };
  11329. eventMixin(SharedTextMarker);
  11330. function markTextShared(doc, from, to, options, type) {
  11331. options = copyObj(options);
  11332. options.shared = false;
  11333. var markers = [markText(doc, from, to, options, type)], primary = markers[0];
  11334. var widget = options.widgetNode;
  11335. linkedDocs(doc, function (doc) {
  11336. if (widget) { options.widgetNode = widget.cloneNode(true); }
  11337. markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type));
  11338. for (var i = 0; i < doc.linked.length; ++i)
  11339. { if (doc.linked[i].isParent) { return } }
  11340. primary = lst(markers);
  11341. });
  11342. return new SharedTextMarker(markers, primary)
  11343. }
  11344. function findSharedMarkers(doc) {
  11345. return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())), function (m) { return m.parent; })
  11346. }
  11347. function copySharedMarkers(doc, markers) {
  11348. for (var i = 0; i < markers.length; i++) {
  11349. var marker = markers[i], pos = marker.find();
  11350. var mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to);
  11351. if (cmp(mFrom, mTo)) {
  11352. var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type);
  11353. marker.markers.push(subMark);
  11354. subMark.parent = marker;
  11355. }
  11356. }
  11357. }
  11358. function detachSharedMarkers(markers) {
  11359. var loop = function ( i ) {
  11360. var marker = markers[i], linked = [marker.primary.doc];
  11361. linkedDocs(marker.primary.doc, function (d) { return linked.push(d); });
  11362. for (var j = 0; j < marker.markers.length; j++) {
  11363. var subMarker = marker.markers[j];
  11364. if (indexOf(linked, subMarker.doc) == -1) {
  11365. subMarker.parent = null;
  11366. marker.markers.splice(j--, 1);
  11367. }
  11368. }
  11369. };
  11370. for (var i = 0; i < markers.length; i++) loop( i );
  11371. }
  11372. var nextDocId = 0;
  11373. var Doc = function(text, mode, firstLine, lineSep, direction) {
  11374. if (!(this instanceof Doc)) { return new Doc(text, mode, firstLine, lineSep, direction) }
  11375. if (firstLine == null) { firstLine = 0; }
  11376. BranchChunk.call(this, [new LeafChunk([new Line("", null)])]);
  11377. this.first = firstLine;
  11378. this.scrollTop = this.scrollLeft = 0;
  11379. this.cantEdit = false;
  11380. this.cleanGeneration = 1;
  11381. this.modeFrontier = this.highlightFrontier = firstLine;
  11382. var start = Pos(firstLine, 0);
  11383. this.sel = simpleSelection(start);
  11384. this.history = new History(null);
  11385. this.id = ++nextDocId;
  11386. this.modeOption = mode;
  11387. this.lineSep = lineSep;
  11388. this.direction = (direction == "rtl") ? "rtl" : "ltr";
  11389. this.extend = false;
  11390. if (typeof text == "string") { text = this.splitLines(text); }
  11391. updateDoc(this, {from: start, to: start, text: text});
  11392. setSelection(this, simpleSelection(start), sel_dontScroll);
  11393. };
  11394. Doc.prototype = createObj(BranchChunk.prototype, {
  11395. constructor: Doc,
  11396. // Iterate over the document. Supports two forms -- with only one
  11397. // argument, it calls that for each line in the document. With
  11398. // three, it iterates over the range given by the first two (with
  11399. // the second being non-inclusive).
  11400. iter: function(from, to, op) {
  11401. if (op) { this.iterN(from - this.first, to - from, op); }
  11402. else { this.iterN(this.first, this.first + this.size, from); }
  11403. },
  11404. // Non-public interface for adding and removing lines.
  11405. insert: function(at, lines) {
  11406. var height = 0;
  11407. for (var i = 0; i < lines.length; ++i) { height += lines[i].height; }
  11408. this.insertInner(at - this.first, lines, height);
  11409. },
  11410. remove: function(at, n) { this.removeInner(at - this.first, n); },
  11411. // From here, the methods are part of the public interface. Most
  11412. // are also available from CodeMirror (editor) instances.
  11413. getValue: function(lineSep) {
  11414. var lines = getLines(this, this.first, this.first + this.size);
  11415. if (lineSep === false) { return lines }
  11416. return lines.join(lineSep || this.lineSeparator())
  11417. },
  11418. setValue: docMethodOp(function(code) {
  11419. var top = Pos(this.first, 0), last = this.first + this.size - 1;
  11420. makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length),
  11421. text: this.splitLines(code), origin: "setValue", full: true}, true);
  11422. if (this.cm) { scrollToCoords(this.cm, 0, 0); }
  11423. setSelection(this, simpleSelection(top), sel_dontScroll);
  11424. }),
  11425. replaceRange: function(code, from, to, origin) {
  11426. from = clipPos(this, from);
  11427. to = to ? clipPos(this, to) : from;
  11428. replaceRange(this, code, from, to, origin);
  11429. },
  11430. getRange: function(from, to, lineSep) {
  11431. var lines = getBetween(this, clipPos(this, from), clipPos(this, to));
  11432. if (lineSep === false) { return lines }
  11433. return lines.join(lineSep || this.lineSeparator())
  11434. },
  11435. getLine: function(line) {var l = this.getLineHandle(line); return l && l.text},
  11436. getLineHandle: function(line) {if (isLine(this, line)) { return getLine(this, line) }},
  11437. getLineNumber: function(line) {return lineNo(line)},
  11438. getLineHandleVisualStart: function(line) {
  11439. if (typeof line == "number") { line = getLine(this, line); }
  11440. return visualLine(line)
  11441. },
  11442. lineCount: function() {return this.size},
  11443. firstLine: function() {return this.first},
  11444. lastLine: function() {return this.first + this.size - 1},
  11445. clipPos: function(pos) {return clipPos(this, pos)},
  11446. getCursor: function(start) {
  11447. var range$$1 = this.sel.primary(), pos;
  11448. if (start == null || start == "head") { pos = range$$1.head; }
  11449. else if (start == "anchor") { pos = range$$1.anchor; }
  11450. else if (start == "end" || start == "to" || start === false) { pos = range$$1.to(); }
  11451. else { pos = range$$1.from(); }
  11452. return pos
  11453. },
  11454. listSelections: function() { return this.sel.ranges },
  11455. somethingSelected: function() {return this.sel.somethingSelected()},
  11456. setCursor: docMethodOp(function(line, ch, options) {
  11457. setSimpleSelection(this, clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line), null, options);
  11458. }),
  11459. setSelection: docMethodOp(function(anchor, head, options) {
  11460. setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options);
  11461. }),
  11462. extendSelection: docMethodOp(function(head, other, options) {
  11463. extendSelection(this, clipPos(this, head), other && clipPos(this, other), options);
  11464. }),
  11465. extendSelections: docMethodOp(function(heads, options) {
  11466. extendSelections(this, clipPosArray(this, heads), options);
  11467. }),
  11468. extendSelectionsBy: docMethodOp(function(f, options) {
  11469. var heads = map(this.sel.ranges, f);
  11470. extendSelections(this, clipPosArray(this, heads), options);
  11471. }),
  11472. setSelections: docMethodOp(function(ranges, primary, options) {
  11473. var this$1 = this;
  11474. if (!ranges.length) { return }
  11475. var out = [];
  11476. for (var i = 0; i < ranges.length; i++)
  11477. { out[i] = new Range(clipPos(this$1, ranges[i].anchor),
  11478. clipPos(this$1, ranges[i].head)); }
  11479. if (primary == null) { primary = Math.min(ranges.length - 1, this.sel.primIndex); }
  11480. setSelection(this, normalizeSelection(out, primary), options);
  11481. }),
  11482. addSelection: docMethodOp(function(anchor, head, options) {
  11483. var ranges = this.sel.ranges.slice(0);
  11484. ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor)));
  11485. setSelection(this, normalizeSelection(ranges, ranges.length - 1), options);
  11486. }),
  11487. getSelection: function(lineSep) {
  11488. var this$1 = this;
  11489. var ranges = this.sel.ranges, lines;
  11490. for (var i = 0; i < ranges.length; i++) {
  11491. var sel = getBetween(this$1, ranges[i].from(), ranges[i].to());
  11492. lines = lines ? lines.concat(sel) : sel;
  11493. }
  11494. if (lineSep === false) { return lines }
  11495. else { return lines.join(lineSep || this.lineSeparator()) }
  11496. },
  11497. getSelections: function(lineSep) {
  11498. var this$1 = this;
  11499. var parts = [], ranges = this.sel.ranges;
  11500. for (var i = 0; i < ranges.length; i++) {
  11501. var sel = getBetween(this$1, ranges[i].from(), ranges[i].to());
  11502. if (lineSep !== false) { sel = sel.join(lineSep || this$1.lineSeparator()); }
  11503. parts[i] = sel;
  11504. }
  11505. return parts
  11506. },
  11507. replaceSelection: function(code, collapse, origin) {
  11508. var dup = [];
  11509. for (var i = 0; i < this.sel.ranges.length; i++)
  11510. { dup[i] = code; }
  11511. this.replaceSelections(dup, collapse, origin || "+input");
  11512. },
  11513. replaceSelections: docMethodOp(function(code, collapse, origin) {
  11514. var this$1 = this;
  11515. var changes = [], sel = this.sel;
  11516. for (var i = 0; i < sel.ranges.length; i++) {
  11517. var range$$1 = sel.ranges[i];
  11518. changes[i] = {from: range$$1.from(), to: range$$1.to(), text: this$1.splitLines(code[i]), origin: origin};
  11519. }
  11520. var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse);
  11521. for (var i$1 = changes.length - 1; i$1 >= 0; i$1--)
  11522. { makeChange(this$1, changes[i$1]); }
  11523. if (newSel) { setSelectionReplaceHistory(this, newSel); }
  11524. else if (this.cm) { ensureCursorVisible(this.cm); }
  11525. }),
  11526. undo: docMethodOp(function() {makeChangeFromHistory(this, "undo");}),
  11527. redo: docMethodOp(function() {makeChangeFromHistory(this, "redo");}),
  11528. undoSelection: docMethodOp(function() {makeChangeFromHistory(this, "undo", true);}),
  11529. redoSelection: docMethodOp(function() {makeChangeFromHistory(this, "redo", true);}),
  11530. setExtending: function(val) {this.extend = val;},
  11531. getExtending: function() {return this.extend},
  11532. historySize: function() {
  11533. var hist = this.history, done = 0, undone = 0;
  11534. for (var i = 0; i < hist.done.length; i++) { if (!hist.done[i].ranges) { ++done; } }
  11535. for (var i$1 = 0; i$1 < hist.undone.length; i$1++) { if (!hist.undone[i$1].ranges) { ++undone; } }
  11536. return {undo: done, redo: undone}
  11537. },
  11538. clearHistory: function() {this.history = new History(this.history.maxGeneration);},
  11539. markClean: function() {
  11540. this.cleanGeneration = this.changeGeneration(true);
  11541. },
  11542. changeGeneration: function(forceSplit) {
  11543. if (forceSplit)
  11544. { this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null; }
  11545. return this.history.generation
  11546. },
  11547. isClean: function (gen) {
  11548. return this.history.generation == (gen || this.cleanGeneration)
  11549. },
  11550. getHistory: function() {
  11551. return {done: copyHistoryArray(this.history.done),
  11552. undone: copyHistoryArray(this.history.undone)}
  11553. },
  11554. setHistory: function(histData) {
  11555. var hist = this.history = new History(this.history.maxGeneration);
  11556. hist.done = copyHistoryArray(histData.done.slice(0), null, true);
  11557. hist.undone = copyHistoryArray(histData.undone.slice(0), null, true);
  11558. },
  11559. setGutterMarker: docMethodOp(function(line, gutterID, value) {
  11560. return changeLine(this, line, "gutter", function (line) {
  11561. var markers = line.gutterMarkers || (line.gutterMarkers = {});
  11562. markers[gutterID] = value;
  11563. if (!value && isEmpty(markers)) { line.gutterMarkers = null; }
  11564. return true
  11565. })
  11566. }),
  11567. clearGutter: docMethodOp(function(gutterID) {
  11568. var this$1 = this;
  11569. this.iter(function (line) {
  11570. if (line.gutterMarkers && line.gutterMarkers[gutterID]) {
  11571. changeLine(this$1, line, "gutter", function () {
  11572. line.gutterMarkers[gutterID] = null;
  11573. if (isEmpty(line.gutterMarkers)) { line.gutterMarkers = null; }
  11574. return true
  11575. });
  11576. }
  11577. });
  11578. }),
  11579. lineInfo: function(line) {
  11580. var n;
  11581. if (typeof line == "number") {
  11582. if (!isLine(this, line)) { return null }
  11583. n = line;
  11584. line = getLine(this, line);
  11585. if (!line) { return null }
  11586. } else {
  11587. n = lineNo(line);
  11588. if (n == null) { return null }
  11589. }
  11590. return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers,
  11591. textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass,
  11592. widgets: line.widgets}
  11593. },
  11594. addLineClass: docMethodOp(function(handle, where, cls) {
  11595. return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) {
  11596. var prop = where == "text" ? "textClass"
  11597. : where == "background" ? "bgClass"
  11598. : where == "gutter" ? "gutterClass" : "wrapClass";
  11599. if (!line[prop]) { line[prop] = cls; }
  11600. else if (classTest(cls).test(line[prop])) { return false }
  11601. else { line[prop] += " " + cls; }
  11602. return true
  11603. })
  11604. }),
  11605. removeLineClass: docMethodOp(function(handle, where, cls) {
  11606. return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) {
  11607. var prop = where == "text" ? "textClass"
  11608. : where == "background" ? "bgClass"
  11609. : where == "gutter" ? "gutterClass" : "wrapClass";
  11610. var cur = line[prop];
  11611. if (!cur) { return false }
  11612. else if (cls == null) { line[prop] = null; }
  11613. else {
  11614. var found = cur.match(classTest(cls));
  11615. if (!found) { return false }
  11616. var end = found.index + found[0].length;
  11617. line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null;
  11618. }
  11619. return true
  11620. })
  11621. }),
  11622. addLineWidget: docMethodOp(function(handle, node, options) {
  11623. return addLineWidget(this, handle, node, options)
  11624. }),
  11625. removeLineWidget: function(widget) { widget.clear(); },
  11626. markText: function(from, to, options) {
  11627. return markText(this, clipPos(this, from), clipPos(this, to), options, options && options.type || "range")
  11628. },
  11629. setBookmark: function(pos, options) {
  11630. var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options),
  11631. insertLeft: options && options.insertLeft,
  11632. clearWhenEmpty: false, shared: options && options.shared,
  11633. handleMouseEvents: options && options.handleMouseEvents};
  11634. pos = clipPos(this, pos);
  11635. return markText(this, pos, pos, realOpts, "bookmark")
  11636. },
  11637. findMarksAt: function(pos) {
  11638. pos = clipPos(this, pos);
  11639. var markers = [], spans = getLine(this, pos.line).markedSpans;
  11640. if (spans) { for (var i = 0; i < spans.length; ++i) {
  11641. var span = spans[i];
  11642. if ((span.from == null || span.from <= pos.ch) &&
  11643. (span.to == null || span.to >= pos.ch))
  11644. { markers.push(span.marker.parent || span.marker); }
  11645. } }
  11646. return markers
  11647. },
  11648. findMarks: function(from, to, filter) {
  11649. from = clipPos(this, from); to = clipPos(this, to);
  11650. var found = [], lineNo$$1 = from.line;
  11651. this.iter(from.line, to.line + 1, function (line) {
  11652. var spans = line.markedSpans;
  11653. if (spans) { for (var i = 0; i < spans.length; i++) {
  11654. var span = spans[i];
  11655. if (!(span.to != null && lineNo$$1 == from.line && from.ch >= span.to ||
  11656. span.from == null && lineNo$$1 != from.line ||
  11657. span.from != null && lineNo$$1 == to.line && span.from >= to.ch) &&
  11658. (!filter || filter(span.marker)))
  11659. { found.push(span.marker.parent || span.marker); }
  11660. } }
  11661. ++lineNo$$1;
  11662. });
  11663. return found
  11664. },
  11665. getAllMarks: function() {
  11666. var markers = [];
  11667. this.iter(function (line) {
  11668. var sps = line.markedSpans;
  11669. if (sps) { for (var i = 0; i < sps.length; ++i)
  11670. { if (sps[i].from != null) { markers.push(sps[i].marker); } } }
  11671. });
  11672. return markers
  11673. },
  11674. posFromIndex: function(off) {
  11675. var ch, lineNo$$1 = this.first, sepSize = this.lineSeparator().length;
  11676. this.iter(function (line) {
  11677. var sz = line.text.length + sepSize;
  11678. if (sz > off) { ch = off; return true }
  11679. off -= sz;
  11680. ++lineNo$$1;
  11681. });
  11682. return clipPos(this, Pos(lineNo$$1, ch))
  11683. },
  11684. indexFromPos: function (coords) {
  11685. coords = clipPos(this, coords);
  11686. var index = coords.ch;
  11687. if (coords.line < this.first || coords.ch < 0) { return 0 }
  11688. var sepSize = this.lineSeparator().length;
  11689. this.iter(this.first, coords.line, function (line) { // iter aborts when callback returns a truthy value
  11690. index += line.text.length + sepSize;
  11691. });
  11692. return index
  11693. },
  11694. copy: function(copyHistory) {
  11695. var doc = new Doc(getLines(this, this.first, this.first + this.size),
  11696. this.modeOption, this.first, this.lineSep, this.direction);
  11697. doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft;
  11698. doc.sel = this.sel;
  11699. doc.extend = false;
  11700. if (copyHistory) {
  11701. doc.history.undoDepth = this.history.undoDepth;
  11702. doc.setHistory(this.getHistory());
  11703. }
  11704. return doc
  11705. },
  11706. linkedDoc: function(options) {
  11707. if (!options) { options = {}; }
  11708. var from = this.first, to = this.first + this.size;
  11709. if (options.from != null && options.from > from) { from = options.from; }
  11710. if (options.to != null && options.to < to) { to = options.to; }
  11711. var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from, this.lineSep, this.direction);
  11712. if (options.sharedHist) { copy.history = this.history
  11713. ; }(this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist});
  11714. copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}];
  11715. copySharedMarkers(copy, findSharedMarkers(this));
  11716. return copy
  11717. },
  11718. unlinkDoc: function(other) {
  11719. var this$1 = this;
  11720. if (other instanceof CodeMirror$1) { other = other.doc; }
  11721. if (this.linked) { for (var i = 0; i < this.linked.length; ++i) {
  11722. var link = this$1.linked[i];
  11723. if (link.doc != other) { continue }
  11724. this$1.linked.splice(i, 1);
  11725. other.unlinkDoc(this$1);
  11726. detachSharedMarkers(findSharedMarkers(this$1));
  11727. break
  11728. } }
  11729. // If the histories were shared, split them again
  11730. if (other.history == this.history) {
  11731. var splitIds = [other.id];
  11732. linkedDocs(other, function (doc) { return splitIds.push(doc.id); }, true);
  11733. other.history = new History(null);
  11734. other.history.done = copyHistoryArray(this.history.done, splitIds);
  11735. other.history.undone = copyHistoryArray(this.history.undone, splitIds);
  11736. }
  11737. },
  11738. iterLinkedDocs: function(f) {linkedDocs(this, f);},
  11739. getMode: function() {return this.mode},
  11740. getEditor: function() {return this.cm},
  11741. splitLines: function(str) {
  11742. if (this.lineSep) { return str.split(this.lineSep) }
  11743. return splitLinesAuto(str)
  11744. },
  11745. lineSeparator: function() { return this.lineSep || "\n" },
  11746. setDirection: docMethodOp(function (dir) {
  11747. if (dir != "rtl") { dir = "ltr"; }
  11748. if (dir == this.direction) { return }
  11749. this.direction = dir;
  11750. this.iter(function (line) { return line.order = null; });
  11751. if (this.cm) { directionChanged(this.cm); }
  11752. })
  11753. });
  11754. // Public alias.
  11755. Doc.prototype.eachLine = Doc.prototype.iter;
  11756. // Kludge to work around strange IE behavior where it'll sometimes
  11757. // re-fire a series of drag-related events right after the drop (#1551)
  11758. var lastDrop = 0;
  11759. function onDrop(e) {
  11760. var cm = this;
  11761. clearDragCursor(cm);
  11762. if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e))
  11763. { return }
  11764. e_preventDefault(e);
  11765. if (ie) { lastDrop = +new Date; }
  11766. var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files;
  11767. if (!pos || cm.isReadOnly()) { return }
  11768. // Might be a file drop, in which case we simply extract the text
  11769. // and insert it.
  11770. if (files && files.length && window.FileReader && window.File) {
  11771. var n = files.length, text = Array(n), read = 0;
  11772. var loadFile = function (file, i) {
  11773. if (cm.options.allowDropFileTypes &&
  11774. indexOf(cm.options.allowDropFileTypes, file.type) == -1)
  11775. { return }
  11776. var reader = new FileReader;
  11777. reader.onload = operation(cm, function () {
  11778. var content = reader.result;
  11779. if (/[\x00-\x08\x0e-\x1f]{2}/.test(content)) { content = ""; }
  11780. text[i] = content;
  11781. if (++read == n) {
  11782. pos = clipPos(cm.doc, pos);
  11783. var change = {from: pos, to: pos,
  11784. text: cm.doc.splitLines(text.join(cm.doc.lineSeparator())),
  11785. origin: "paste"};
  11786. makeChange(cm.doc, change);
  11787. setSelectionReplaceHistory(cm.doc, simpleSelection(pos, changeEnd(change)));
  11788. }
  11789. });
  11790. reader.readAsText(file);
  11791. };
  11792. for (var i = 0; i < n; ++i) { loadFile(files[i], i); }
  11793. } else { // Normal drop
  11794. // Don't do a replace if the drop happened inside of the selected text.
  11795. if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) {
  11796. cm.state.draggingText(e);
  11797. // Ensure the editor is re-focused
  11798. setTimeout(function () { return cm.display.input.focus(); }, 20);
  11799. return
  11800. }
  11801. try {
  11802. var text$1 = e.dataTransfer.getData("Text");
  11803. if (text$1) {
  11804. var selected;
  11805. if (cm.state.draggingText && !cm.state.draggingText.copy)
  11806. { selected = cm.listSelections(); }
  11807. setSelectionNoUndo(cm.doc, simpleSelection(pos, pos));
  11808. if (selected) { for (var i$1 = 0; i$1 < selected.length; ++i$1)
  11809. { replaceRange(cm.doc, "", selected[i$1].anchor, selected[i$1].head, "drag"); } }
  11810. cm.replaceSelection(text$1, "around", "paste");
  11811. cm.display.input.focus();
  11812. }
  11813. }
  11814. catch(e){}
  11815. }
  11816. }
  11817. function onDragStart(cm, e) {
  11818. if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return }
  11819. if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) { return }
  11820. e.dataTransfer.setData("Text", cm.getSelection());
  11821. e.dataTransfer.effectAllowed = "copyMove";
  11822. // Use dummy image instead of default browsers image.
  11823. // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there.
  11824. if (e.dataTransfer.setDragImage && !safari) {
  11825. var img = elt("img", null, null, "position: fixed; left: 0; top: 0;");
  11826. img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";
  11827. if (presto) {
  11828. img.width = img.height = 1;
  11829. cm.display.wrapper.appendChild(img);
  11830. // Force a relayout, or Opera won't use our image for some obscure reason
  11831. img._top = img.offsetTop;
  11832. }
  11833. e.dataTransfer.setDragImage(img, 0, 0);
  11834. if (presto) { img.parentNode.removeChild(img); }
  11835. }
  11836. }
  11837. function onDragOver(cm, e) {
  11838. var pos = posFromMouse(cm, e);
  11839. if (!pos) { return }
  11840. var frag = document.createDocumentFragment();
  11841. drawSelectionCursor(cm, pos, frag);
  11842. if (!cm.display.dragCursor) {
  11843. cm.display.dragCursor = elt("div", null, "CodeMirror-cursors CodeMirror-dragcursors");
  11844. cm.display.lineSpace.insertBefore(cm.display.dragCursor, cm.display.cursorDiv);
  11845. }
  11846. removeChildrenAndAdd(cm.display.dragCursor, frag);
  11847. }
  11848. function clearDragCursor(cm) {
  11849. if (cm.display.dragCursor) {
  11850. cm.display.lineSpace.removeChild(cm.display.dragCursor);
  11851. cm.display.dragCursor = null;
  11852. }
  11853. }
  11854. // These must be handled carefully, because naively registering a
  11855. // handler for each editor will cause the editors to never be
  11856. // garbage collected.
  11857. function forEachCodeMirror(f) {
  11858. if (!document.getElementsByClassName) { return }
  11859. var byClass = document.getElementsByClassName("CodeMirror");
  11860. for (var i = 0; i < byClass.length; i++) {
  11861. var cm = byClass[i].CodeMirror;
  11862. if (cm) { f(cm); }
  11863. }
  11864. }
  11865. var globalsRegistered = false;
  11866. function ensureGlobalHandlers() {
  11867. if (globalsRegistered) { return }
  11868. registerGlobalHandlers();
  11869. globalsRegistered = true;
  11870. }
  11871. function registerGlobalHandlers() {
  11872. // When the window resizes, we need to refresh active editors.
  11873. var resizeTimer;
  11874. on(window, "resize", function () {
  11875. if (resizeTimer == null) { resizeTimer = setTimeout(function () {
  11876. resizeTimer = null;
  11877. forEachCodeMirror(onResize);
  11878. }, 100); }
  11879. });
  11880. // When the window loses focus, we want to show the editor as blurred
  11881. on(window, "blur", function () { return forEachCodeMirror(onBlur); });
  11882. }
  11883. // Called when the window resizes
  11884. function onResize(cm) {
  11885. var d = cm.display;
  11886. if (d.lastWrapHeight == d.wrapper.clientHeight && d.lastWrapWidth == d.wrapper.clientWidth)
  11887. { return }
  11888. // Might be a text scaling operation, clear size caches.
  11889. d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
  11890. d.scrollbarsClipped = false;
  11891. cm.setSize();
  11892. }
  11893. var keyNames = {
  11894. 3: "Enter", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt",
  11895. 19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End",
  11896. 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert",
  11897. 46: "Delete", 59: ";", 61: "=", 91: "Mod", 92: "Mod", 93: "Mod",
  11898. 106: "*", 107: "=", 109: "-", 110: ".", 111: "/", 127: "Delete",
  11899. 173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\",
  11900. 221: "]", 222: "'", 63232: "Up", 63233: "Down", 63234: "Left", 63235: "Right", 63272: "Delete",
  11901. 63273: "Home", 63275: "End", 63276: "PageUp", 63277: "PageDown", 63302: "Insert"
  11902. };
  11903. // Number keys
  11904. for (var i = 0; i < 10; i++) { keyNames[i + 48] = keyNames[i + 96] = String(i); }
  11905. // Alphabetic keys
  11906. for (var i$1 = 65; i$1 <= 90; i$1++) { keyNames[i$1] = String.fromCharCode(i$1); }
  11907. // Function keys
  11908. for (var i$2 = 1; i$2 <= 12; i$2++) { keyNames[i$2 + 111] = keyNames[i$2 + 63235] = "F" + i$2; }
  11909. var keyMap = {};
  11910. keyMap.basic = {
  11911. "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown",
  11912. "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown",
  11913. "Delete": "delCharAfter", "Backspace": "delCharBefore", "Shift-Backspace": "delCharBefore",
  11914. "Tab": "defaultTab", "Shift-Tab": "indentAuto",
  11915. "Enter": "newlineAndIndent", "Insert": "toggleOverwrite",
  11916. "Esc": "singleSelection"
  11917. };
  11918. // Note that the save and find-related commands aren't defined by
  11919. // default. User code or addons can define them. Unknown commands
  11920. // are simply ignored.
  11921. keyMap.pcDefault = {
  11922. "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo",
  11923. "Ctrl-Home": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Up": "goLineUp", "Ctrl-Down": "goLineDown",
  11924. "Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd",
  11925. "Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find",
  11926. "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll",
  11927. "Ctrl-[": "indentLess", "Ctrl-]": "indentMore",
  11928. "Ctrl-U": "undoSelection", "Shift-Ctrl-U": "redoSelection", "Alt-U": "redoSelection",
  11929. fallthrough: "basic"
  11930. };
  11931. // Very basic readline/emacs-style bindings, which are standard on Mac.
  11932. keyMap.emacsy = {
  11933. "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown",
  11934. "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd",
  11935. "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp", "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore",
  11936. "Alt-D": "delWordAfter", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars",
  11937. "Ctrl-O": "openLine"
  11938. };
  11939. keyMap.macDefault = {
  11940. "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo",
  11941. "Cmd-Home": "goDocStart", "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft",
  11942. "Alt-Right": "goGroupRight", "Cmd-Left": "goLineLeft", "Cmd-Right": "goLineRight", "Alt-Backspace": "delGroupBefore",
  11943. "Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find",
  11944. "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll",
  11945. "Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delWrappedLineLeft", "Cmd-Delete": "delWrappedLineRight",
  11946. "Cmd-U": "undoSelection", "Shift-Cmd-U": "redoSelection", "Ctrl-Up": "goDocStart", "Ctrl-Down": "goDocEnd",
  11947. fallthrough: ["basic", "emacsy"]
  11948. };
  11949. keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault;
  11950. // KEYMAP DISPATCH
  11951. function normalizeKeyName(name) {
  11952. var parts = name.split(/-(?!$)/);
  11953. name = parts[parts.length - 1];
  11954. var alt, ctrl, shift, cmd;
  11955. for (var i = 0; i < parts.length - 1; i++) {
  11956. var mod = parts[i];
  11957. if (/^(cmd|meta|m)$/i.test(mod)) { cmd = true; }
  11958. else if (/^a(lt)?$/i.test(mod)) { alt = true; }
  11959. else if (/^(c|ctrl|control)$/i.test(mod)) { ctrl = true; }
  11960. else if (/^s(hift)?$/i.test(mod)) { shift = true; }
  11961. else { throw new Error("Unrecognized modifier name: " + mod) }
  11962. }
  11963. if (alt) { name = "Alt-" + name; }
  11964. if (ctrl) { name = "Ctrl-" + name; }
  11965. if (cmd) { name = "Cmd-" + name; }
  11966. if (shift) { name = "Shift-" + name; }
  11967. return name
  11968. }
  11969. // This is a kludge to keep keymaps mostly working as raw objects
  11970. // (backwards compatibility) while at the same time support features
  11971. // like normalization and multi-stroke key bindings. It compiles a
  11972. // new normalized keymap, and then updates the old object to reflect
  11973. // this.
  11974. function normalizeKeyMap(keymap) {
  11975. var copy = {};
  11976. for (var keyname in keymap) { if (keymap.hasOwnProperty(keyname)) {
  11977. var value = keymap[keyname];
  11978. if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) { continue }
  11979. if (value == "...") { delete keymap[keyname]; continue }
  11980. var keys = map(keyname.split(" "), normalizeKeyName);
  11981. for (var i = 0; i < keys.length; i++) {
  11982. var val = (void 0), name = (void 0);
  11983. if (i == keys.length - 1) {
  11984. name = keys.join(" ");
  11985. val = value;
  11986. } else {
  11987. name = keys.slice(0, i + 1).join(" ");
  11988. val = "...";
  11989. }
  11990. var prev = copy[name];
  11991. if (!prev) { copy[name] = val; }
  11992. else if (prev != val) { throw new Error("Inconsistent bindings for " + name) }
  11993. }
  11994. delete keymap[keyname];
  11995. } }
  11996. for (var prop in copy) { keymap[prop] = copy[prop]; }
  11997. return keymap
  11998. }
  11999. function lookupKey(key, map$$1, handle, context) {
  12000. map$$1 = getKeyMap(map$$1);
  12001. var found = map$$1.call ? map$$1.call(key, context) : map$$1[key];
  12002. if (found === false) { return "nothing" }
  12003. if (found === "...") { return "multi" }
  12004. if (found != null && handle(found)) { return "handled" }
  12005. if (map$$1.fallthrough) {
  12006. if (Object.prototype.toString.call(map$$1.fallthrough) != "[object Array]")
  12007. { return lookupKey(key, map$$1.fallthrough, handle, context) }
  12008. for (var i = 0; i < map$$1.fallthrough.length; i++) {
  12009. var result = lookupKey(key, map$$1.fallthrough[i], handle, context);
  12010. if (result) { return result }
  12011. }
  12012. }
  12013. }
  12014. // Modifier key presses don't count as 'real' key presses for the
  12015. // purpose of keymap fallthrough.
  12016. function isModifierKey(value) {
  12017. var name = typeof value == "string" ? value : keyNames[value.keyCode];
  12018. return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod"
  12019. }
  12020. function addModifierNames(name, event, noShift) {
  12021. var base = name;
  12022. if (event.altKey && base != "Alt") { name = "Alt-" + name; }
  12023. if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != "Ctrl") { name = "Ctrl-" + name; }
  12024. if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != "Cmd") { name = "Cmd-" + name; }
  12025. if (!noShift && event.shiftKey && base != "Shift") { name = "Shift-" + name; }
  12026. return name
  12027. }
  12028. // Look up the name of a key as indicated by an event object.
  12029. function keyName(event, noShift) {
  12030. if (presto && event.keyCode == 34 && event["char"]) { return false }
  12031. var name = keyNames[event.keyCode];
  12032. if (name == null || event.altGraphKey) { return false }
  12033. return addModifierNames(name, event, noShift)
  12034. }
  12035. function getKeyMap(val) {
  12036. return typeof val == "string" ? keyMap[val] : val
  12037. }
  12038. // Helper for deleting text near the selection(s), used to implement
  12039. // backspace, delete, and similar functionality.
  12040. function deleteNearSelection(cm, compute) {
  12041. var ranges = cm.doc.sel.ranges, kill = [];
  12042. // Build up a set of ranges to kill first, merging overlapping
  12043. // ranges.
  12044. for (var i = 0; i < ranges.length; i++) {
  12045. var toKill = compute(ranges[i]);
  12046. while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) {
  12047. var replaced = kill.pop();
  12048. if (cmp(replaced.from, toKill.from) < 0) {
  12049. toKill.from = replaced.from;
  12050. break
  12051. }
  12052. }
  12053. kill.push(toKill);
  12054. }
  12055. // Next, remove those actual ranges.
  12056. runInOp(cm, function () {
  12057. for (var i = kill.length - 1; i >= 0; i--)
  12058. { replaceRange(cm.doc, "", kill[i].from, kill[i].to, "+delete"); }
  12059. ensureCursorVisible(cm);
  12060. });
  12061. }
  12062. function moveCharLogically(line, ch, dir) {
  12063. var target = skipExtendingChars(line.text, ch + dir, dir);
  12064. return target < 0 || target > line.text.length ? null : target
  12065. }
  12066. function moveLogically(line, start, dir) {
  12067. var ch = moveCharLogically(line, start.ch, dir);
  12068. return ch == null ? null : new Pos(start.line, ch, dir < 0 ? "after" : "before")
  12069. }
  12070. function endOfLine(visually, cm, lineObj, lineNo, dir) {
  12071. if (visually) {
  12072. var order = getOrder(lineObj, cm.doc.direction);
  12073. if (order) {
  12074. var part = dir < 0 ? lst(order) : order[0];
  12075. var moveInStorageOrder = (dir < 0) == (part.level == 1);
  12076. var sticky = moveInStorageOrder ? "after" : "before";
  12077. var ch;
  12078. // With a wrapped rtl chunk (possibly spanning multiple bidi parts),
  12079. // it could be that the last bidi part is not on the last visual line,
  12080. // since visual lines contain content order-consecutive chunks.
  12081. // Thus, in rtl, we are looking for the first (content-order) character
  12082. // in the rtl chunk that is on the last line (that is, the same line
  12083. // as the last (content-order) character).
  12084. if (part.level > 0 || cm.doc.direction == "rtl") {
  12085. var prep = prepareMeasureForLine(cm, lineObj);
  12086. ch = dir < 0 ? lineObj.text.length - 1 : 0;
  12087. var targetTop = measureCharPrepared(cm, prep, ch).top;
  12088. ch = findFirst(function (ch) { return measureCharPrepared(cm, prep, ch).top == targetTop; }, (dir < 0) == (part.level == 1) ? part.from : part.to - 1, ch);
  12089. if (sticky == "before") { ch = moveCharLogically(lineObj, ch, 1); }
  12090. } else { ch = dir < 0 ? part.to : part.from; }
  12091. return new Pos(lineNo, ch, sticky)
  12092. }
  12093. }
  12094. return new Pos(lineNo, dir < 0 ? lineObj.text.length : 0, dir < 0 ? "before" : "after")
  12095. }
  12096. function moveVisually(cm, line, start, dir) {
  12097. var bidi = getOrder(line, cm.doc.direction);
  12098. if (!bidi) { return moveLogically(line, start, dir) }
  12099. if (start.ch >= line.text.length) {
  12100. start.ch = line.text.length;
  12101. start.sticky = "before";
  12102. } else if (start.ch <= 0) {
  12103. start.ch = 0;
  12104. start.sticky = "after";
  12105. }
  12106. var partPos = getBidiPartAt(bidi, start.ch, start.sticky), part = bidi[partPos];
  12107. if (cm.doc.direction == "ltr" && part.level % 2 == 0 && (dir > 0 ? part.to > start.ch : part.from < start.ch)) {
  12108. // Case 1: We move within an ltr part in an ltr editor. Even with wrapped lines,
  12109. // nothing interesting happens.
  12110. return moveLogically(line, start, dir)
  12111. }
  12112. var mv = function (pos, dir) { return moveCharLogically(line, pos instanceof Pos ? pos.ch : pos, dir); };
  12113. var prep;
  12114. var getWrappedLineExtent = function (ch) {
  12115. if (!cm.options.lineWrapping) { return {begin: 0, end: line.text.length} }
  12116. prep = prep || prepareMeasureForLine(cm, line);
  12117. return wrappedLineExtentChar(cm, line, prep, ch)
  12118. };
  12119. var wrappedLineExtent = getWrappedLineExtent(start.sticky == "before" ? mv(start, -1) : start.ch);
  12120. if (cm.doc.direction == "rtl" || part.level == 1) {
  12121. var moveInStorageOrder = (part.level == 1) == (dir < 0);
  12122. var ch = mv(start, moveInStorageOrder ? 1 : -1);
  12123. if (ch != null && (!moveInStorageOrder ? ch >= part.from && ch >= wrappedLineExtent.begin : ch <= part.to && ch <= wrappedLineExtent.end)) {
  12124. // Case 2: We move within an rtl part or in an rtl editor on the same visual line
  12125. var sticky = moveInStorageOrder ? "before" : "after";
  12126. return new Pos(start.line, ch, sticky)
  12127. }
  12128. }
  12129. // Case 3: Could not move within this bidi part in this visual line, so leave
  12130. // the current bidi part
  12131. var searchInVisualLine = function (partPos, dir, wrappedLineExtent) {
  12132. var getRes = function (ch, moveInStorageOrder) { return moveInStorageOrder
  12133. ? new Pos(start.line, mv(ch, 1), "before")
  12134. : new Pos(start.line, ch, "after"); };
  12135. for (; partPos >= 0 && partPos < bidi.length; partPos += dir) {
  12136. var part = bidi[partPos];
  12137. var moveInStorageOrder = (dir > 0) == (part.level != 1);
  12138. var ch = moveInStorageOrder ? wrappedLineExtent.begin : mv(wrappedLineExtent.end, -1);
  12139. if (part.from <= ch && ch < part.to) { return getRes(ch, moveInStorageOrder) }
  12140. ch = moveInStorageOrder ? part.from : mv(part.to, -1);
  12141. if (wrappedLineExtent.begin <= ch && ch < wrappedLineExtent.end) { return getRes(ch, moveInStorageOrder) }
  12142. }
  12143. };
  12144. // Case 3a: Look for other bidi parts on the same visual line
  12145. var res = searchInVisualLine(partPos + dir, dir, wrappedLineExtent);
  12146. if (res) { return res }
  12147. // Case 3b: Look for other bidi parts on the next visual line
  12148. var nextCh = dir > 0 ? wrappedLineExtent.end : mv(wrappedLineExtent.begin, -1);
  12149. if (nextCh != null && !(dir > 0 && nextCh == line.text.length)) {
  12150. res = searchInVisualLine(dir > 0 ? 0 : bidi.length - 1, dir, getWrappedLineExtent(nextCh));
  12151. if (res) { return res }
  12152. }
  12153. // Case 4: Nowhere to move
  12154. return null
  12155. }
  12156. // Commands are parameter-less actions that can be performed on an
  12157. // editor, mostly used for keybindings.
  12158. var commands = {
  12159. selectAll: selectAll,
  12160. singleSelection: function (cm) { return cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll); },
  12161. killLine: function (cm) { return deleteNearSelection(cm, function (range) {
  12162. if (range.empty()) {
  12163. var len = getLine(cm.doc, range.head.line).text.length;
  12164. if (range.head.ch == len && range.head.line < cm.lastLine())
  12165. { return {from: range.head, to: Pos(range.head.line + 1, 0)} }
  12166. else
  12167. { return {from: range.head, to: Pos(range.head.line, len)} }
  12168. } else {
  12169. return {from: range.from(), to: range.to()}
  12170. }
  12171. }); },
  12172. deleteLine: function (cm) { return deleteNearSelection(cm, function (range) { return ({
  12173. from: Pos(range.from().line, 0),
  12174. to: clipPos(cm.doc, Pos(range.to().line + 1, 0))
  12175. }); }); },
  12176. delLineLeft: function (cm) { return deleteNearSelection(cm, function (range) { return ({
  12177. from: Pos(range.from().line, 0), to: range.from()
  12178. }); }); },
  12179. delWrappedLineLeft: function (cm) { return deleteNearSelection(cm, function (range) {
  12180. var top = cm.charCoords(range.head, "div").top + 5;
  12181. var leftPos = cm.coordsChar({left: 0, top: top}, "div");
  12182. return {from: leftPos, to: range.from()}
  12183. }); },
  12184. delWrappedLineRight: function (cm) { return deleteNearSelection(cm, function (range) {
  12185. var top = cm.charCoords(range.head, "div").top + 5;
  12186. var rightPos = cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div");
  12187. return {from: range.from(), to: rightPos }
  12188. }); },
  12189. undo: function (cm) { return cm.undo(); },
  12190. redo: function (cm) { return cm.redo(); },
  12191. undoSelection: function (cm) { return cm.undoSelection(); },
  12192. redoSelection: function (cm) { return cm.redoSelection(); },
  12193. goDocStart: function (cm) { return cm.extendSelection(Pos(cm.firstLine(), 0)); },
  12194. goDocEnd: function (cm) { return cm.extendSelection(Pos(cm.lastLine())); },
  12195. goLineStart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStart(cm, range.head.line); },
  12196. {origin: "+move", bias: 1}
  12197. ); },
  12198. goLineStartSmart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStartSmart(cm, range.head); },
  12199. {origin: "+move", bias: 1}
  12200. ); },
  12201. goLineEnd: function (cm) { return cm.extendSelectionsBy(function (range) { return lineEnd(cm, range.head.line); },
  12202. {origin: "+move", bias: -1}
  12203. ); },
  12204. goLineRight: function (cm) { return cm.extendSelectionsBy(function (range) {
  12205. var top = cm.cursorCoords(range.head, "div").top + 5;
  12206. return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div")
  12207. }, sel_move); },
  12208. goLineLeft: function (cm) { return cm.extendSelectionsBy(function (range) {
  12209. var top = cm.cursorCoords(range.head, "div").top + 5;
  12210. return cm.coordsChar({left: 0, top: top}, "div")
  12211. }, sel_move); },
  12212. goLineLeftSmart: function (cm) { return cm.extendSelectionsBy(function (range) {
  12213. var top = cm.cursorCoords(range.head, "div").top + 5;
  12214. var pos = cm.coordsChar({left: 0, top: top}, "div");
  12215. if (pos.ch < cm.getLine(pos.line).search(/\S/)) { return lineStartSmart(cm, range.head) }
  12216. return pos
  12217. }, sel_move); },
  12218. goLineUp: function (cm) { return cm.moveV(-1, "line"); },
  12219. goLineDown: function (cm) { return cm.moveV(1, "line"); },
  12220. goPageUp: function (cm) { return cm.moveV(-1, "page"); },
  12221. goPageDown: function (cm) { return cm.moveV(1, "page"); },
  12222. goCharLeft: function (cm) { return cm.moveH(-1, "char"); },
  12223. goCharRight: function (cm) { return cm.moveH(1, "char"); },
  12224. goColumnLeft: function (cm) { return cm.moveH(-1, "column"); },
  12225. goColumnRight: function (cm) { return cm.moveH(1, "column"); },
  12226. goWordLeft: function (cm) { return cm.moveH(-1, "word"); },
  12227. goGroupRight: function (cm) { return cm.moveH(1, "group"); },
  12228. goGroupLeft: function (cm) { return cm.moveH(-1, "group"); },
  12229. goWordRight: function (cm) { return cm.moveH(1, "word"); },
  12230. delCharBefore: function (cm) { return cm.deleteH(-1, "char"); },
  12231. delCharAfter: function (cm) { return cm.deleteH(1, "char"); },
  12232. delWordBefore: function (cm) { return cm.deleteH(-1, "word"); },
  12233. delWordAfter: function (cm) { return cm.deleteH(1, "word"); },
  12234. delGroupBefore: function (cm) { return cm.deleteH(-1, "group"); },
  12235. delGroupAfter: function (cm) { return cm.deleteH(1, "group"); },
  12236. indentAuto: function (cm) { return cm.indentSelection("smart"); },
  12237. indentMore: function (cm) { return cm.indentSelection("add"); },
  12238. indentLess: function (cm) { return cm.indentSelection("subtract"); },
  12239. insertTab: function (cm) { return cm.replaceSelection("\t"); },
  12240. insertSoftTab: function (cm) {
  12241. var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize;
  12242. for (var i = 0; i < ranges.length; i++) {
  12243. var pos = ranges[i].from();
  12244. var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize);
  12245. spaces.push(spaceStr(tabSize - col % tabSize));
  12246. }
  12247. cm.replaceSelections(spaces);
  12248. },
  12249. defaultTab: function (cm) {
  12250. if (cm.somethingSelected()) { cm.indentSelection("add"); }
  12251. else { cm.execCommand("insertTab"); }
  12252. },
  12253. // Swap the two chars left and right of each selection's head.
  12254. // Move cursor behind the two swapped characters afterwards.
  12255. //
  12256. // Doesn't consider line feeds a character.
  12257. // Doesn't scan more than one line above to find a character.
  12258. // Doesn't do anything on an empty line.
  12259. // Doesn't do anything with non-empty selections.
  12260. transposeChars: function (cm) { return runInOp(cm, function () {
  12261. var ranges = cm.listSelections(), newSel = [];
  12262. for (var i = 0; i < ranges.length; i++) {
  12263. if (!ranges[i].empty()) { continue }
  12264. var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text;
  12265. if (line) {
  12266. if (cur.ch == line.length) { cur = new Pos(cur.line, cur.ch - 1); }
  12267. if (cur.ch > 0) {
  12268. cur = new Pos(cur.line, cur.ch + 1);
  12269. cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2),
  12270. Pos(cur.line, cur.ch - 2), cur, "+transpose");
  12271. } else if (cur.line > cm.doc.first) {
  12272. var prev = getLine(cm.doc, cur.line - 1).text;
  12273. if (prev) {
  12274. cur = new Pos(cur.line, 1);
  12275. cm.replaceRange(line.charAt(0) + cm.doc.lineSeparator() +
  12276. prev.charAt(prev.length - 1),
  12277. Pos(cur.line - 1, prev.length - 1), cur, "+transpose");
  12278. }
  12279. }
  12280. }
  12281. newSel.push(new Range(cur, cur));
  12282. }
  12283. cm.setSelections(newSel);
  12284. }); },
  12285. newlineAndIndent: function (cm) { return runInOp(cm, function () {
  12286. var sels = cm.listSelections();
  12287. for (var i = sels.length - 1; i >= 0; i--)
  12288. { cm.replaceRange(cm.doc.lineSeparator(), sels[i].anchor, sels[i].head, "+input"); }
  12289. sels = cm.listSelections();
  12290. for (var i$1 = 0; i$1 < sels.length; i$1++)
  12291. { cm.indentLine(sels[i$1].from().line, null, true); }
  12292. ensureCursorVisible(cm);
  12293. }); },
  12294. openLine: function (cm) { return cm.replaceSelection("\n", "start"); },
  12295. toggleOverwrite: function (cm) { return cm.toggleOverwrite(); }
  12296. };
  12297. function lineStart(cm, lineN) {
  12298. var line = getLine(cm.doc, lineN);
  12299. var visual = visualLine(line);
  12300. if (visual != line) { lineN = lineNo(visual); }
  12301. return endOfLine(true, cm, visual, lineN, 1)
  12302. }
  12303. function lineEnd(cm, lineN) {
  12304. var line = getLine(cm.doc, lineN);
  12305. var visual = visualLineEnd(line);
  12306. if (visual != line) { lineN = lineNo(visual); }
  12307. return endOfLine(true, cm, line, lineN, -1)
  12308. }
  12309. function lineStartSmart(cm, pos) {
  12310. var start = lineStart(cm, pos.line);
  12311. var line = getLine(cm.doc, start.line);
  12312. var order = getOrder(line, cm.doc.direction);
  12313. if (!order || order[0].level == 0) {
  12314. var firstNonWS = Math.max(0, line.text.search(/\S/));
  12315. var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch;
  12316. return Pos(start.line, inWS ? 0 : firstNonWS, start.sticky)
  12317. }
  12318. return start
  12319. }
  12320. // Run a handler that was bound to a key.
  12321. function doHandleBinding(cm, bound, dropShift) {
  12322. if (typeof bound == "string") {
  12323. bound = commands[bound];
  12324. if (!bound) { return false }
  12325. }
  12326. // Ensure previous input has been read, so that the handler sees a
  12327. // consistent view of the document
  12328. cm.display.input.ensurePolled();
  12329. var prevShift = cm.display.shift, done = false;
  12330. try {
  12331. if (cm.isReadOnly()) { cm.state.suppressEdits = true; }
  12332. if (dropShift) { cm.display.shift = false; }
  12333. done = bound(cm) != Pass;
  12334. } finally {
  12335. cm.display.shift = prevShift;
  12336. cm.state.suppressEdits = false;
  12337. }
  12338. return done
  12339. }
  12340. function lookupKeyForEditor(cm, name, handle) {
  12341. for (var i = 0; i < cm.state.keyMaps.length; i++) {
  12342. var result = lookupKey(name, cm.state.keyMaps[i], handle, cm);
  12343. if (result) { return result }
  12344. }
  12345. return (cm.options.extraKeys && lookupKey(name, cm.options.extraKeys, handle, cm))
  12346. || lookupKey(name, cm.options.keyMap, handle, cm)
  12347. }
  12348. // Note that, despite the name, this function is also used to check
  12349. // for bound mouse clicks.
  12350. var stopSeq = new Delayed;
  12351. function dispatchKey(cm, name, e, handle) {
  12352. var seq = cm.state.keySeq;
  12353. if (seq) {
  12354. if (isModifierKey(name)) { return "handled" }
  12355. if (/\'$/.test(name))
  12356. { cm.state.keySeq = null; }
  12357. else
  12358. { stopSeq.set(50, function () {
  12359. if (cm.state.keySeq == seq) {
  12360. cm.state.keySeq = null;
  12361. cm.display.input.reset();
  12362. }
  12363. }); }
  12364. if (dispatchKeyInner(cm, seq + " " + name, e, handle)) { return true }
  12365. }
  12366. return dispatchKeyInner(cm, name, e, handle)
  12367. }
  12368. function dispatchKeyInner(cm, name, e, handle) {
  12369. var result = lookupKeyForEditor(cm, name, handle);
  12370. if (result == "multi")
  12371. { cm.state.keySeq = name; }
  12372. if (result == "handled")
  12373. { signalLater(cm, "keyHandled", cm, name, e); }
  12374. if (result == "handled" || result == "multi") {
  12375. e_preventDefault(e);
  12376. restartBlink(cm);
  12377. }
  12378. return !!result
  12379. }
  12380. // Handle a key from the keydown event.
  12381. function handleKeyBinding(cm, e) {
  12382. var name = keyName(e, true);
  12383. if (!name) { return false }
  12384. if (e.shiftKey && !cm.state.keySeq) {
  12385. // First try to resolve full name (including 'Shift-'). Failing
  12386. // that, see if there is a cursor-motion command (starting with
  12387. // 'go') bound to the keyname without 'Shift-'.
  12388. return dispatchKey(cm, "Shift-" + name, e, function (b) { return doHandleBinding(cm, b, true); })
  12389. || dispatchKey(cm, name, e, function (b) {
  12390. if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion)
  12391. { return doHandleBinding(cm, b) }
  12392. })
  12393. } else {
  12394. return dispatchKey(cm, name, e, function (b) { return doHandleBinding(cm, b); })
  12395. }
  12396. }
  12397. // Handle a key from the keypress event
  12398. function handleCharBinding(cm, e, ch) {
  12399. return dispatchKey(cm, "'" + ch + "'", e, function (b) { return doHandleBinding(cm, b, true); })
  12400. }
  12401. var lastStoppedKey = null;
  12402. function onKeyDown(e) {
  12403. var cm = this;
  12404. cm.curOp.focus = activeElt();
  12405. if (signalDOMEvent(cm, e)) { return }
  12406. // IE does strange things with escape.
  12407. if (ie && ie_version < 11 && e.keyCode == 27) { e.returnValue = false; }
  12408. var code = e.keyCode;
  12409. cm.display.shift = code == 16 || e.shiftKey;
  12410. var handled = handleKeyBinding(cm, e);
  12411. if (presto) {
  12412. lastStoppedKey = handled ? code : null;
  12413. // Opera has no cut event... we try to at least catch the key combo
  12414. if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey))
  12415. { cm.replaceSelection("", null, "cut"); }
  12416. }
  12417. // Turn mouse into crosshair when Alt is held on Mac.
  12418. if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className))
  12419. { showCrossHair(cm); }
  12420. }
  12421. function showCrossHair(cm) {
  12422. var lineDiv = cm.display.lineDiv;
  12423. addClass(lineDiv, "CodeMirror-crosshair");
  12424. function up(e) {
  12425. if (e.keyCode == 18 || !e.altKey) {
  12426. rmClass(lineDiv, "CodeMirror-crosshair");
  12427. off(document, "keyup", up);
  12428. off(document, "mouseover", up);
  12429. }
  12430. }
  12431. on(document, "keyup", up);
  12432. on(document, "mouseover", up);
  12433. }
  12434. function onKeyUp(e) {
  12435. if (e.keyCode == 16) { this.doc.sel.shift = false; }
  12436. signalDOMEvent(this, e);
  12437. }
  12438. function onKeyPress(e) {
  12439. var cm = this;
  12440. if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) { return }
  12441. var keyCode = e.keyCode, charCode = e.charCode;
  12442. if (presto && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return}
  12443. if ((presto && (!e.which || e.which < 10)) && handleKeyBinding(cm, e)) { return }
  12444. var ch = String.fromCharCode(charCode == null ? keyCode : charCode);
  12445. // Some browsers fire keypress events for backspace
  12446. if (ch == "\x08") { return }
  12447. if (handleCharBinding(cm, e, ch)) { return }
  12448. cm.display.input.onKeyPress(e);
  12449. }
  12450. var DOUBLECLICK_DELAY = 400;
  12451. var PastClick = function(time, pos, button) {
  12452. this.time = time;
  12453. this.pos = pos;
  12454. this.button = button;
  12455. };
  12456. PastClick.prototype.compare = function (time, pos, button) {
  12457. return this.time + DOUBLECLICK_DELAY > time &&
  12458. cmp(pos, this.pos) == 0 && button == this.button
  12459. };
  12460. var lastClick;
  12461. var lastDoubleClick;
  12462. function clickRepeat(pos, button) {
  12463. var now = +new Date;
  12464. if (lastDoubleClick && lastDoubleClick.compare(now, pos, button)) {
  12465. lastClick = lastDoubleClick = null;
  12466. return "triple"
  12467. } else if (lastClick && lastClick.compare(now, pos, button)) {
  12468. lastDoubleClick = new PastClick(now, pos, button);
  12469. lastClick = null;
  12470. return "double"
  12471. } else {
  12472. lastClick = new PastClick(now, pos, button);
  12473. lastDoubleClick = null;
  12474. return "single"
  12475. }
  12476. }
  12477. // A mouse down can be a single click, double click, triple click,
  12478. // start of selection drag, start of text drag, new cursor
  12479. // (ctrl-click), rectangle drag (alt-drag), or xwin
  12480. // middle-click-paste. Or it might be a click on something we should
  12481. // not interfere with, such as a scrollbar or widget.
  12482. function onMouseDown(e) {
  12483. var cm = this, display = cm.display;
  12484. if (signalDOMEvent(cm, e) || display.activeTouch && display.input.supportsTouch()) { return }
  12485. display.input.ensurePolled();
  12486. display.shift = e.shiftKey;
  12487. if (eventInWidget(display, e)) {
  12488. if (!webkit) {
  12489. // Briefly turn off draggability, to allow widgets to do
  12490. // normal dragging things.
  12491. display.scroller.draggable = false;
  12492. setTimeout(function () { return display.scroller.draggable = true; }, 100);
  12493. }
  12494. return
  12495. }
  12496. if (clickInGutter(cm, e)) { return }
  12497. var pos = posFromMouse(cm, e), button = e_button(e), repeat = pos ? clickRepeat(pos, button) : "single";
  12498. window.focus();
  12499. // #3261: make sure, that we're not starting a second selection
  12500. if (button == 1 && cm.state.selectingText)
  12501. { cm.state.selectingText(e); }
  12502. if (pos && handleMappedButton(cm, button, pos, repeat, e)) { return }
  12503. if (button == 1) {
  12504. if (pos) { leftButtonDown(cm, pos, repeat, e); }
  12505. else if (e_target(e) == display.scroller) { e_preventDefault(e); }
  12506. } else if (button == 2) {
  12507. if (pos) { extendSelection(cm.doc, pos); }
  12508. setTimeout(function () { return display.input.focus(); }, 20);
  12509. } else if (button == 3) {
  12510. if (captureRightClick) { onContextMenu(cm, e); }
  12511. else { delayBlurEvent(cm); }
  12512. }
  12513. }
  12514. function handleMappedButton(cm, button, pos, repeat, event) {
  12515. var name = "Click";
  12516. if (repeat == "double") { name = "Double" + name; }
  12517. else if (repeat == "triple") { name = "Triple" + name; }
  12518. name = (button == 1 ? "Left" : button == 2 ? "Middle" : "Right") + name;
  12519. return dispatchKey(cm, addModifierNames(name, event), event, function (bound) {
  12520. if (typeof bound == "string") { bound = commands[bound]; }
  12521. if (!bound) { return false }
  12522. var done = false;
  12523. try {
  12524. if (cm.isReadOnly()) { cm.state.suppressEdits = true; }
  12525. done = bound(cm, pos) != Pass;
  12526. } finally {
  12527. cm.state.suppressEdits = false;
  12528. }
  12529. return done
  12530. })
  12531. }
  12532. function configureMouse(cm, repeat, event) {
  12533. var option = cm.getOption("configureMouse");
  12534. var value = option ? option(cm, repeat, event) : {};
  12535. if (value.unit == null) {
  12536. var rect = chromeOS ? event.shiftKey && event.metaKey : event.altKey;
  12537. value.unit = rect ? "rectangle" : repeat == "single" ? "char" : repeat == "double" ? "word" : "line";
  12538. }
  12539. if (value.extend == null || cm.doc.extend) { value.extend = cm.doc.extend || event.shiftKey; }
  12540. if (value.addNew == null) { value.addNew = mac ? event.metaKey : event.ctrlKey; }
  12541. if (value.moveOnDrag == null) { value.moveOnDrag = !(mac ? event.altKey : event.ctrlKey); }
  12542. return value
  12543. }
  12544. function leftButtonDown(cm, pos, repeat, event) {
  12545. if (ie) { setTimeout(bind(ensureFocus, cm), 0); }
  12546. else { cm.curOp.focus = activeElt(); }
  12547. var behavior = configureMouse(cm, repeat, event);
  12548. var sel = cm.doc.sel, contained;
  12549. if (cm.options.dragDrop && dragAndDrop && !cm.isReadOnly() &&
  12550. repeat == "single" && (contained = sel.contains(pos)) > -1 &&
  12551. (cmp((contained = sel.ranges[contained]).from(), pos) < 0 || pos.xRel > 0) &&
  12552. (cmp(contained.to(), pos) > 0 || pos.xRel < 0))
  12553. { leftButtonStartDrag(cm, event, pos, behavior); }
  12554. else
  12555. { leftButtonSelect(cm, event, pos, behavior); }
  12556. }
  12557. // Start a text drag. When it ends, see if any dragging actually
  12558. // happen, and treat as a click if it didn't.
  12559. function leftButtonStartDrag(cm, event, pos, behavior) {
  12560. var display = cm.display, moved = false;
  12561. var dragEnd = operation(cm, function (e) {
  12562. if (webkit) { display.scroller.draggable = false; }
  12563. cm.state.draggingText = false;
  12564. off(document, "mouseup", dragEnd);
  12565. off(document, "mousemove", mouseMove);
  12566. off(display.scroller, "dragstart", dragStart);
  12567. off(display.scroller, "drop", dragEnd);
  12568. if (!moved) {
  12569. e_preventDefault(e);
  12570. if (!behavior.addNew)
  12571. { extendSelection(cm.doc, pos, null, null, behavior.extend); }
  12572. // Work around unexplainable focus problem in IE9 (#2127) and Chrome (#3081)
  12573. if (webkit || ie && ie_version == 9)
  12574. { setTimeout(function () {document.body.focus(); display.input.focus();}, 20); }
  12575. else
  12576. { display.input.focus(); }
  12577. }
  12578. });
  12579. var mouseMove = function(e2) {
  12580. moved = moved || Math.abs(event.clientX - e2.clientX) + Math.abs(event.clientY - e2.clientY) >= 10;
  12581. };
  12582. var dragStart = function () { return moved = true; };
  12583. // Let the drag handler handle this.
  12584. if (webkit) { display.scroller.draggable = true; }
  12585. cm.state.draggingText = dragEnd;
  12586. dragEnd.copy = !behavior.moveOnDrag;
  12587. // IE's approach to draggable
  12588. if (display.scroller.dragDrop) { display.scroller.dragDrop(); }
  12589. on(document, "mouseup", dragEnd);
  12590. on(document, "mousemove", mouseMove);
  12591. on(display.scroller, "dragstart", dragStart);
  12592. on(display.scroller, "drop", dragEnd);
  12593. delayBlurEvent(cm);
  12594. setTimeout(function () { return display.input.focus(); }, 20);
  12595. }
  12596. function rangeForUnit(cm, pos, unit) {
  12597. if (unit == "char") { return new Range(pos, pos) }
  12598. if (unit == "word") { return cm.findWordAt(pos) }
  12599. if (unit == "line") { return new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))) }
  12600. var result = unit(cm, pos);
  12601. return new Range(result.from, result.to)
  12602. }
  12603. // Normal selection, as opposed to text dragging.
  12604. function leftButtonSelect(cm, event, start, behavior) {
  12605. var display = cm.display, doc = cm.doc;
  12606. e_preventDefault(event);
  12607. var ourRange, ourIndex, startSel = doc.sel, ranges = startSel.ranges;
  12608. if (behavior.addNew && !behavior.extend) {
  12609. ourIndex = doc.sel.contains(start);
  12610. if (ourIndex > -1)
  12611. { ourRange = ranges[ourIndex]; }
  12612. else
  12613. { ourRange = new Range(start, start); }
  12614. } else {
  12615. ourRange = doc.sel.primary();
  12616. ourIndex = doc.sel.primIndex;
  12617. }
  12618. if (behavior.unit == "rectangle") {
  12619. if (!behavior.addNew) { ourRange = new Range(start, start); }
  12620. start = posFromMouse(cm, event, true, true);
  12621. ourIndex = -1;
  12622. } else {
  12623. var range$$1 = rangeForUnit(cm, start, behavior.unit);
  12624. if (behavior.extend)
  12625. { ourRange = extendRange(ourRange, range$$1.anchor, range$$1.head, behavior.extend); }
  12626. else
  12627. { ourRange = range$$1; }
  12628. }
  12629. if (!behavior.addNew) {
  12630. ourIndex = 0;
  12631. setSelection(doc, new Selection([ourRange], 0), sel_mouse);
  12632. startSel = doc.sel;
  12633. } else if (ourIndex == -1) {
  12634. ourIndex = ranges.length;
  12635. setSelection(doc, normalizeSelection(ranges.concat([ourRange]), ourIndex),
  12636. {scroll: false, origin: "*mouse"});
  12637. } else if (ranges.length > 1 && ranges[ourIndex].empty() && behavior.unit == "char" && !behavior.extend) {
  12638. setSelection(doc, normalizeSelection(ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0),
  12639. {scroll: false, origin: "*mouse"});
  12640. startSel = doc.sel;
  12641. } else {
  12642. replaceOneSelection(doc, ourIndex, ourRange, sel_mouse);
  12643. }
  12644. var lastPos = start;
  12645. function extendTo(pos) {
  12646. if (cmp(lastPos, pos) == 0) { return }
  12647. lastPos = pos;
  12648. if (behavior.unit == "rectangle") {
  12649. var ranges = [], tabSize = cm.options.tabSize;
  12650. var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize);
  12651. var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize);
  12652. var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol);
  12653. for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line));
  12654. line <= end; line++) {
  12655. var text = getLine(doc, line).text, leftPos = findColumn(text, left, tabSize);
  12656. if (left == right)
  12657. { ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos))); }
  12658. else if (text.length > leftPos)
  12659. { ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize)))); }
  12660. }
  12661. if (!ranges.length) { ranges.push(new Range(start, start)); }
  12662. setSelection(doc, normalizeSelection(startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex),
  12663. {origin: "*mouse", scroll: false});
  12664. cm.scrollIntoView(pos);
  12665. } else {
  12666. var oldRange = ourRange;
  12667. var range$$1 = rangeForUnit(cm, pos, behavior.unit);
  12668. var anchor = oldRange.anchor, head;
  12669. if (cmp(range$$1.anchor, anchor) > 0) {
  12670. head = range$$1.head;
  12671. anchor = minPos(oldRange.from(), range$$1.anchor);
  12672. } else {
  12673. head = range$$1.anchor;
  12674. anchor = maxPos(oldRange.to(), range$$1.head);
  12675. }
  12676. var ranges$1 = startSel.ranges.slice(0);
  12677. ranges$1[ourIndex] = bidiSimplify(cm, new Range(clipPos(doc, anchor), head));
  12678. setSelection(doc, normalizeSelection(ranges$1, ourIndex), sel_mouse);
  12679. }
  12680. }
  12681. var editorSize = display.wrapper.getBoundingClientRect();
  12682. // Used to ensure timeout re-tries don't fire when another extend
  12683. // happened in the meantime (clearTimeout isn't reliable -- at
  12684. // least on Chrome, the timeouts still happen even when cleared,
  12685. // if the clear happens after their scheduled firing time).
  12686. var counter = 0;
  12687. function extend(e) {
  12688. var curCount = ++counter;
  12689. var cur = posFromMouse(cm, e, true, behavior.unit == "rectangle");
  12690. if (!cur) { return }
  12691. if (cmp(cur, lastPos) != 0) {
  12692. cm.curOp.focus = activeElt();
  12693. extendTo(cur);
  12694. var visible = visibleLines(display, doc);
  12695. if (cur.line >= visible.to || cur.line < visible.from)
  12696. { setTimeout(operation(cm, function () {if (counter == curCount) { extend(e); }}), 150); }
  12697. } else {
  12698. var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0;
  12699. if (outside) { setTimeout(operation(cm, function () {
  12700. if (counter != curCount) { return }
  12701. display.scroller.scrollTop += outside;
  12702. extend(e);
  12703. }), 50); }
  12704. }
  12705. }
  12706. function done(e) {
  12707. cm.state.selectingText = false;
  12708. counter = Infinity;
  12709. e_preventDefault(e);
  12710. display.input.focus();
  12711. off(document, "mousemove", move);
  12712. off(document, "mouseup", up);
  12713. doc.history.lastSelOrigin = null;
  12714. }
  12715. var move = operation(cm, function (e) {
  12716. if (!e_button(e)) { done(e); }
  12717. else { extend(e); }
  12718. });
  12719. var up = operation(cm, done);
  12720. cm.state.selectingText = up;
  12721. on(document, "mousemove", move);
  12722. on(document, "mouseup", up);
  12723. }
  12724. // Used when mouse-selecting to adjust the anchor to the proper side
  12725. // of a bidi jump depending on the visual position of the head.
  12726. function bidiSimplify(cm, range$$1) {
  12727. var anchor = range$$1.anchor;
  12728. var head = range$$1.head;
  12729. var anchorLine = getLine(cm.doc, anchor.line);
  12730. if (cmp(anchor, head) == 0 && anchor.sticky == head.sticky) { return range$$1 }
  12731. var order = getOrder(anchorLine);
  12732. if (!order) { return range$$1 }
  12733. var index = getBidiPartAt(order, anchor.ch, anchor.sticky), part = order[index];
  12734. if (part.from != anchor.ch && part.to != anchor.ch) { return range$$1 }
  12735. var boundary = index + ((part.from == anchor.ch) == (part.level != 1) ? 0 : 1);
  12736. if (boundary == 0 || boundary == order.length) { return range$$1 }
  12737. // Compute the relative visual position of the head compared to the
  12738. // anchor (<0 is to the left, >0 to the right)
  12739. var leftSide;
  12740. if (head.line != anchor.line) {
  12741. leftSide = (head.line - anchor.line) * (cm.doc.direction == "ltr" ? 1 : -1) > 0;
  12742. } else {
  12743. var headIndex = getBidiPartAt(order, head.ch, head.sticky);
  12744. var dir = headIndex - index || (head.ch - anchor.ch) * (part.level == 1 ? -1 : 1);
  12745. if (headIndex == boundary - 1 || headIndex == boundary)
  12746. { leftSide = dir < 0; }
  12747. else
  12748. { leftSide = dir > 0; }
  12749. }
  12750. var usePart = order[boundary + (leftSide ? -1 : 0)];
  12751. var from = leftSide == (usePart.level == 1);
  12752. var ch = from ? usePart.from : usePart.to, sticky = from ? "after" : "before";
  12753. return anchor.ch == ch && anchor.sticky == sticky ? range$$1 : new Range(new Pos(anchor.line, ch, sticky), head)
  12754. }
  12755. // Determines whether an event happened in the gutter, and fires the
  12756. // handlers for the corresponding event.
  12757. function gutterEvent(cm, e, type, prevent) {
  12758. var mX, mY;
  12759. if (e.touches) {
  12760. mX = e.touches[0].clientX;
  12761. mY = e.touches[0].clientY;
  12762. } else {
  12763. try { mX = e.clientX; mY = e.clientY; }
  12764. catch(e) { return false }
  12765. }
  12766. if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) { return false }
  12767. if (prevent) { e_preventDefault(e); }
  12768. var display = cm.display;
  12769. var lineBox = display.lineDiv.getBoundingClientRect();
  12770. if (mY > lineBox.bottom || !hasHandler(cm, type)) { return e_defaultPrevented(e) }
  12771. mY -= lineBox.top - display.viewOffset;
  12772. for (var i = 0; i < cm.options.gutters.length; ++i) {
  12773. var g = display.gutters.childNodes[i];
  12774. if (g && g.getBoundingClientRect().right >= mX) {
  12775. var line = lineAtHeight(cm.doc, mY);
  12776. var gutter = cm.options.gutters[i];
  12777. signal(cm, type, cm, line, gutter, e);
  12778. return e_defaultPrevented(e)
  12779. }
  12780. }
  12781. }
  12782. function clickInGutter(cm, e) {
  12783. return gutterEvent(cm, e, "gutterClick", true)
  12784. }
  12785. // CONTEXT MENU HANDLING
  12786. // To make the context menu work, we need to briefly unhide the
  12787. // textarea (making it as unobtrusive as possible) to let the
  12788. // right-click take effect on it.
  12789. function onContextMenu(cm, e) {
  12790. if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) { return }
  12791. if (signalDOMEvent(cm, e, "contextmenu")) { return }
  12792. cm.display.input.onContextMenu(e);
  12793. }
  12794. function contextMenuInGutter(cm, e) {
  12795. if (!hasHandler(cm, "gutterContextMenu")) { return false }
  12796. return gutterEvent(cm, e, "gutterContextMenu", false)
  12797. }
  12798. function themeChanged(cm) {
  12799. cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") +
  12800. cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-");
  12801. clearCaches(cm);
  12802. }
  12803. var Init = {toString: function(){return "CodeMirror.Init"}};
  12804. var defaults = {};
  12805. var optionHandlers = {};
  12806. function defineOptions(CodeMirror) {
  12807. var optionHandlers = CodeMirror.optionHandlers;
  12808. function option(name, deflt, handle, notOnInit) {
  12809. CodeMirror.defaults[name] = deflt;
  12810. if (handle) { optionHandlers[name] =
  12811. notOnInit ? function (cm, val, old) {if (old != Init) { handle(cm, val, old); }} : handle; }
  12812. }
  12813. CodeMirror.defineOption = option;
  12814. // Passed to option handlers when there is no old value.
  12815. CodeMirror.Init = Init;
  12816. // These two are, on init, called from the constructor because they
  12817. // have to be initialized before the editor can start at all.
  12818. option("value", "", function (cm, val) { return cm.setValue(val); }, true);
  12819. option("mode", null, function (cm, val) {
  12820. cm.doc.modeOption = val;
  12821. loadMode(cm);
  12822. }, true);
  12823. option("indentUnit", 2, loadMode, true);
  12824. option("indentWithTabs", false);
  12825. option("smartIndent", true);
  12826. option("tabSize", 4, function (cm) {
  12827. resetModeState(cm);
  12828. clearCaches(cm);
  12829. regChange(cm);
  12830. }, true);
  12831. option("lineSeparator", null, function (cm, val) {
  12832. cm.doc.lineSep = val;
  12833. if (!val) { return }
  12834. var newBreaks = [], lineNo = cm.doc.first;
  12835. cm.doc.iter(function (line) {
  12836. for (var pos = 0;;) {
  12837. var found = line.text.indexOf(val, pos);
  12838. if (found == -1) { break }
  12839. pos = found + val.length;
  12840. newBreaks.push(Pos(lineNo, found));
  12841. }
  12842. lineNo++;
  12843. });
  12844. for (var i = newBreaks.length - 1; i >= 0; i--)
  12845. { replaceRange(cm.doc, val, newBreaks[i], Pos(newBreaks[i].line, newBreaks[i].ch + val.length)); }
  12846. });
  12847. option("specialChars", /[\u0000-\u001f\u007f-\u009f\u00ad\u061c\u200b-\u200f\u2028\u2029\ufeff]/g, function (cm, val, old) {
  12848. cm.state.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g");
  12849. if (old != Init) { cm.refresh(); }
  12850. });
  12851. option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function (cm) { return cm.refresh(); }, true);
  12852. option("electricChars", true);
  12853. option("inputStyle", mobile ? "contenteditable" : "textarea", function () {
  12854. throw new Error("inputStyle can not (yet) be changed in a running editor") // FIXME
  12855. }, true);
  12856. option("spellcheck", false, function (cm, val) { return cm.getInputField().spellcheck = val; }, true);
  12857. option("rtlMoveVisually", !windows);
  12858. option("wholeLineUpdateBefore", true);
  12859. option("theme", "default", function (cm) {
  12860. themeChanged(cm);
  12861. guttersChanged(cm);
  12862. }, true);
  12863. option("keyMap", "default", function (cm, val, old) {
  12864. var next = getKeyMap(val);
  12865. var prev = old != Init && getKeyMap(old);
  12866. if (prev && prev.detach) { prev.detach(cm, next); }
  12867. if (next.attach) { next.attach(cm, prev || null); }
  12868. });
  12869. option("extraKeys", null);
  12870. option("configureMouse", null);
  12871. option("lineWrapping", false, wrappingChanged, true);
  12872. option("gutters", [], function (cm) {
  12873. setGuttersForLineNumbers(cm.options);
  12874. guttersChanged(cm);
  12875. }, true);
  12876. option("fixedGutter", true, function (cm, val) {
  12877. cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0";
  12878. cm.refresh();
  12879. }, true);
  12880. option("coverGutterNextToScrollbar", false, function (cm) { return updateScrollbars(cm); }, true);
  12881. option("scrollbarStyle", "native", function (cm) {
  12882. initScrollbars(cm);
  12883. updateScrollbars(cm);
  12884. cm.display.scrollbars.setScrollTop(cm.doc.scrollTop);
  12885. cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft);
  12886. }, true);
  12887. option("lineNumbers", false, function (cm) {
  12888. setGuttersForLineNumbers(cm.options);
  12889. guttersChanged(cm);
  12890. }, true);
  12891. option("firstLineNumber", 1, guttersChanged, true);
  12892. option("lineNumberFormatter", function (integer) { return integer; }, guttersChanged, true);
  12893. option("showCursorWhenSelecting", false, updateSelection, true);
  12894. option("resetSelectionOnContextMenu", true);
  12895. option("lineWiseCopyCut", true);
  12896. option("pasteLinesPerSelection", true);
  12897. option("readOnly", false, function (cm, val) {
  12898. if (val == "nocursor") {
  12899. onBlur(cm);
  12900. cm.display.input.blur();
  12901. }
  12902. cm.display.input.readOnlyChanged(val);
  12903. });
  12904. option("disableInput", false, function (cm, val) {if (!val) { cm.display.input.reset(); }}, true);
  12905. option("dragDrop", true, dragDropChanged);
  12906. option("allowDropFileTypes", null);
  12907. option("cursorBlinkRate", 530);
  12908. option("cursorScrollMargin", 0);
  12909. option("cursorHeight", 1, updateSelection, true);
  12910. option("singleCursorHeightPerLine", true, updateSelection, true);
  12911. option("workTime", 100);
  12912. option("workDelay", 100);
  12913. option("flattenSpans", true, resetModeState, true);
  12914. option("addModeClass", false, resetModeState, true);
  12915. option("pollInterval", 100);
  12916. option("undoDepth", 200, function (cm, val) { return cm.doc.history.undoDepth = val; });
  12917. option("historyEventDelay", 1250);
  12918. option("viewportMargin", 10, function (cm) { return cm.refresh(); }, true);
  12919. option("maxHighlightLength", 10000, resetModeState, true);
  12920. option("moveInputWithCursor", true, function (cm, val) {
  12921. if (!val) { cm.display.input.resetPosition(); }
  12922. });
  12923. option("tabindex", null, function (cm, val) { return cm.display.input.getField().tabIndex = val || ""; });
  12924. option("autofocus", null);
  12925. option("direction", "ltr", function (cm, val) { return cm.doc.setDirection(val); }, true);
  12926. }
  12927. function guttersChanged(cm) {
  12928. updateGutters(cm);
  12929. regChange(cm);
  12930. alignHorizontally(cm);
  12931. }
  12932. function dragDropChanged(cm, value, old) {
  12933. var wasOn = old && old != Init;
  12934. if (!value != !wasOn) {
  12935. var funcs = cm.display.dragFunctions;
  12936. var toggle = value ? on : off;
  12937. toggle(cm.display.scroller, "dragstart", funcs.start);
  12938. toggle(cm.display.scroller, "dragenter", funcs.enter);
  12939. toggle(cm.display.scroller, "dragover", funcs.over);
  12940. toggle(cm.display.scroller, "dragleave", funcs.leave);
  12941. toggle(cm.display.scroller, "drop", funcs.drop);
  12942. }
  12943. }
  12944. function wrappingChanged(cm) {
  12945. if (cm.options.lineWrapping) {
  12946. addClass(cm.display.wrapper, "CodeMirror-wrap");
  12947. cm.display.sizer.style.minWidth = "";
  12948. cm.display.sizerWidth = null;
  12949. } else {
  12950. rmClass(cm.display.wrapper, "CodeMirror-wrap");
  12951. findMaxLine(cm);
  12952. }
  12953. estimateLineHeights(cm);
  12954. regChange(cm);
  12955. clearCaches(cm);
  12956. setTimeout(function () { return updateScrollbars(cm); }, 100);
  12957. }
  12958. // A CodeMirror instance represents an editor. This is the object
  12959. // that user code is usually dealing with.
  12960. function CodeMirror$1(place, options) {
  12961. var this$1 = this;
  12962. if (!(this instanceof CodeMirror$1)) { return new CodeMirror$1(place, options) }
  12963. this.options = options = options ? copyObj(options) : {};
  12964. // Determine effective options based on given values and defaults.
  12965. copyObj(defaults, options, false);
  12966. setGuttersForLineNumbers(options);
  12967. var doc = options.value;
  12968. if (typeof doc == "string") { doc = new Doc(doc, options.mode, null, options.lineSeparator, options.direction); }
  12969. this.doc = doc;
  12970. var input = new CodeMirror$1.inputStyles[options.inputStyle](this);
  12971. var display = this.display = new Display(place, doc, input);
  12972. display.wrapper.CodeMirror = this;
  12973. updateGutters(this);
  12974. themeChanged(this);
  12975. if (options.lineWrapping)
  12976. { this.display.wrapper.className += " CodeMirror-wrap"; }
  12977. initScrollbars(this);
  12978. this.state = {
  12979. keyMaps: [], // stores maps added by addKeyMap
  12980. overlays: [], // highlighting overlays, as added by addOverlay
  12981. modeGen: 0, // bumped when mode/overlay changes, used to invalidate highlighting info
  12982. overwrite: false,
  12983. delayingBlurEvent: false,
  12984. focused: false,
  12985. suppressEdits: false, // used to disable editing during key handlers when in readOnly mode
  12986. pasteIncoming: false, cutIncoming: false, // help recognize paste/cut edits in input.poll
  12987. selectingText: false,
  12988. draggingText: false,
  12989. highlight: new Delayed(), // stores highlight worker timeout
  12990. keySeq: null, // Unfinished key sequence
  12991. specialChars: null
  12992. };
  12993. if (options.autofocus && !mobile) { display.input.focus(); }
  12994. // Override magic textarea content restore that IE sometimes does
  12995. // on our hidden textarea on reload
  12996. if (ie && ie_version < 11) { setTimeout(function () { return this$1.display.input.reset(true); }, 20); }
  12997. registerEventHandlers(this);
  12998. ensureGlobalHandlers();
  12999. startOperation(this);
  13000. this.curOp.forceUpdate = true;
  13001. attachDoc(this, doc);
  13002. if ((options.autofocus && !mobile) || this.hasFocus())
  13003. { setTimeout(bind(onFocus, this), 20); }
  13004. else
  13005. { onBlur(this); }
  13006. for (var opt in optionHandlers) { if (optionHandlers.hasOwnProperty(opt))
  13007. { optionHandlers[opt](this$1, options[opt], Init); } }
  13008. maybeUpdateLineNumberWidth(this);
  13009. if (options.finishInit) { options.finishInit(this); }
  13010. for (var i = 0; i < initHooks.length; ++i) { initHooks[i](this$1); }
  13011. endOperation(this);
  13012. // Suppress optimizelegibility in Webkit, since it breaks text
  13013. // measuring on line wrapping boundaries.
  13014. if (webkit && options.lineWrapping &&
  13015. getComputedStyle(display.lineDiv).textRendering == "optimizelegibility")
  13016. { display.lineDiv.style.textRendering = "auto"; }
  13017. }
  13018. // The default configuration options.
  13019. CodeMirror$1.defaults = defaults;
  13020. // Functions to run when options are changed.
  13021. CodeMirror$1.optionHandlers = optionHandlers;
  13022. // Attach the necessary event handlers when initializing the editor
  13023. function registerEventHandlers(cm) {
  13024. var d = cm.display;
  13025. on(d.scroller, "mousedown", operation(cm, onMouseDown));
  13026. // Older IE's will not fire a second mousedown for a double click
  13027. if (ie && ie_version < 11)
  13028. { on(d.scroller, "dblclick", operation(cm, function (e) {
  13029. if (signalDOMEvent(cm, e)) { return }
  13030. var pos = posFromMouse(cm, e);
  13031. if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) { return }
  13032. e_preventDefault(e);
  13033. var word = cm.findWordAt(pos);
  13034. extendSelection(cm.doc, word.anchor, word.head);
  13035. })); }
  13036. else
  13037. { on(d.scroller, "dblclick", function (e) { return signalDOMEvent(cm, e) || e_preventDefault(e); }); }
  13038. // Some browsers fire contextmenu *after* opening the menu, at
  13039. // which point we can't mess with it anymore. Context menu is
  13040. // handled in onMouseDown for these browsers.
  13041. if (!captureRightClick) { on(d.scroller, "contextmenu", function (e) { return onContextMenu(cm, e); }); }
  13042. // Used to suppress mouse event handling when a touch happens
  13043. var touchFinished, prevTouch = {end: 0};
  13044. function finishTouch() {
  13045. if (d.activeTouch) {
  13046. touchFinished = setTimeout(function () { return d.activeTouch = null; }, 1000);
  13047. prevTouch = d.activeTouch;
  13048. prevTouch.end = +new Date;
  13049. }
  13050. }
  13051. function isMouseLikeTouchEvent(e) {
  13052. if (e.touches.length != 1) { return false }
  13053. var touch = e.touches[0];
  13054. return touch.radiusX <= 1 && touch.radiusY <= 1
  13055. }
  13056. function farAway(touch, other) {
  13057. if (other.left == null) { return true }
  13058. var dx = other.left - touch.left, dy = other.top - touch.top;
  13059. return dx * dx + dy * dy > 20 * 20
  13060. }
  13061. on(d.scroller, "touchstart", function (e) {
  13062. if (!signalDOMEvent(cm, e) && !isMouseLikeTouchEvent(e) && !clickInGutter(cm, e)) {
  13063. d.input.ensurePolled();
  13064. clearTimeout(touchFinished);
  13065. var now = +new Date;
  13066. d.activeTouch = {start: now, moved: false,
  13067. prev: now - prevTouch.end <= 300 ? prevTouch : null};
  13068. if (e.touches.length == 1) {
  13069. d.activeTouch.left = e.touches[0].pageX;
  13070. d.activeTouch.top = e.touches[0].pageY;
  13071. }
  13072. }
  13073. });
  13074. on(d.scroller, "touchmove", function () {
  13075. if (d.activeTouch) { d.activeTouch.moved = true; }
  13076. });
  13077. on(d.scroller, "touchend", function (e) {
  13078. var touch = d.activeTouch;
  13079. if (touch && !eventInWidget(d, e) && touch.left != null &&
  13080. !touch.moved && new Date - touch.start < 300) {
  13081. var pos = cm.coordsChar(d.activeTouch, "page"), range;
  13082. if (!touch.prev || farAway(touch, touch.prev)) // Single tap
  13083. { range = new Range(pos, pos); }
  13084. else if (!touch.prev.prev || farAway(touch, touch.prev.prev)) // Double tap
  13085. { range = cm.findWordAt(pos); }
  13086. else // Triple tap
  13087. { range = new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))); }
  13088. cm.setSelection(range.anchor, range.head);
  13089. cm.focus();
  13090. e_preventDefault(e);
  13091. }
  13092. finishTouch();
  13093. });
  13094. on(d.scroller, "touchcancel", finishTouch);
  13095. // Sync scrolling between fake scrollbars and real scrollable
  13096. // area, ensure viewport is updated when scrolling.
  13097. on(d.scroller, "scroll", function () {
  13098. if (d.scroller.clientHeight) {
  13099. updateScrollTop(cm, d.scroller.scrollTop);
  13100. setScrollLeft(cm, d.scroller.scrollLeft, true);
  13101. signal(cm, "scroll", cm);
  13102. }
  13103. });
  13104. // Listen to wheel events in order to try and update the viewport on time.
  13105. on(d.scroller, "mousewheel", function (e) { return onScrollWheel(cm, e); });
  13106. on(d.scroller, "DOMMouseScroll", function (e) { return onScrollWheel(cm, e); });
  13107. // Prevent wrapper from ever scrolling
  13108. on(d.wrapper, "scroll", function () { return d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; });
  13109. d.dragFunctions = {
  13110. enter: function (e) {if (!signalDOMEvent(cm, e)) { e_stop(e); }},
  13111. over: function (e) {if (!signalDOMEvent(cm, e)) { onDragOver(cm, e); e_stop(e); }},
  13112. start: function (e) { return onDragStart(cm, e); },
  13113. drop: operation(cm, onDrop),
  13114. leave: function (e) {if (!signalDOMEvent(cm, e)) { clearDragCursor(cm); }}
  13115. };
  13116. var inp = d.input.getField();
  13117. on(inp, "keyup", function (e) { return onKeyUp.call(cm, e); });
  13118. on(inp, "keydown", operation(cm, onKeyDown));
  13119. on(inp, "keypress", operation(cm, onKeyPress));
  13120. on(inp, "focus", function (e) { return onFocus(cm, e); });
  13121. on(inp, "blur", function (e) { return onBlur(cm, e); });
  13122. }
  13123. var initHooks = [];
  13124. CodeMirror$1.defineInitHook = function (f) { return initHooks.push(f); };
  13125. // Indent the given line. The how parameter can be "smart",
  13126. // "add"/null, "subtract", or "prev". When aggressive is false
  13127. // (typically set to true for forced single-line indents), empty
  13128. // lines are not indented, and places where the mode returns Pass
  13129. // are left alone.
  13130. function indentLine(cm, n, how, aggressive) {
  13131. var doc = cm.doc, state;
  13132. if (how == null) { how = "add"; }
  13133. if (how == "smart") {
  13134. // Fall back to "prev" when the mode doesn't have an indentation
  13135. // method.
  13136. if (!doc.mode.indent) { how = "prev"; }
  13137. else { state = getContextBefore(cm, n).state; }
  13138. }
  13139. var tabSize = cm.options.tabSize;
  13140. var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize);
  13141. if (line.stateAfter) { line.stateAfter = null; }
  13142. var curSpaceString = line.text.match(/^\s*/)[0], indentation;
  13143. if (!aggressive && !/\S/.test(line.text)) {
  13144. indentation = 0;
  13145. how = "not";
  13146. } else if (how == "smart") {
  13147. indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text);
  13148. if (indentation == Pass || indentation > 150) {
  13149. if (!aggressive) { return }
  13150. how = "prev";
  13151. }
  13152. }
  13153. if (how == "prev") {
  13154. if (n > doc.first) { indentation = countColumn(getLine(doc, n-1).text, null, tabSize); }
  13155. else { indentation = 0; }
  13156. } else if (how == "add") {
  13157. indentation = curSpace + cm.options.indentUnit;
  13158. } else if (how == "subtract") {
  13159. indentation = curSpace - cm.options.indentUnit;
  13160. } else if (typeof how == "number") {
  13161. indentation = curSpace + how;
  13162. }
  13163. indentation = Math.max(0, indentation);
  13164. var indentString = "", pos = 0;
  13165. if (cm.options.indentWithTabs)
  13166. { for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";} }
  13167. if (pos < indentation) { indentString += spaceStr(indentation - pos); }
  13168. if (indentString != curSpaceString) {
  13169. replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input");
  13170. line.stateAfter = null;
  13171. return true
  13172. } else {
  13173. // Ensure that, if the cursor was in the whitespace at the start
  13174. // of the line, it is moved to the end of that space.
  13175. for (var i$1 = 0; i$1 < doc.sel.ranges.length; i$1++) {
  13176. var range = doc.sel.ranges[i$1];
  13177. if (range.head.line == n && range.head.ch < curSpaceString.length) {
  13178. var pos$1 = Pos(n, curSpaceString.length);
  13179. replaceOneSelection(doc, i$1, new Range(pos$1, pos$1));
  13180. break
  13181. }
  13182. }
  13183. }
  13184. }
  13185. // This will be set to a {lineWise: bool, text: [string]} object, so
  13186. // that, when pasting, we know what kind of selections the copied
  13187. // text was made out of.
  13188. var lastCopied = null;
  13189. function setLastCopied(newLastCopied) {
  13190. lastCopied = newLastCopied;
  13191. }
  13192. function applyTextInput(cm, inserted, deleted, sel, origin) {
  13193. var doc = cm.doc;
  13194. cm.display.shift = false;
  13195. if (!sel) { sel = doc.sel; }
  13196. var paste = cm.state.pasteIncoming || origin == "paste";
  13197. var textLines = splitLinesAuto(inserted), multiPaste = null;
  13198. // When pasing N lines into N selections, insert one line per selection
  13199. if (paste && sel.ranges.length > 1) {
  13200. if (lastCopied && lastCopied.text.join("\n") == inserted) {
  13201. if (sel.ranges.length % lastCopied.text.length == 0) {
  13202. multiPaste = [];
  13203. for (var i = 0; i < lastCopied.text.length; i++)
  13204. { multiPaste.push(doc.splitLines(lastCopied.text[i])); }
  13205. }
  13206. } else if (textLines.length == sel.ranges.length && cm.options.pasteLinesPerSelection) {
  13207. multiPaste = map(textLines, function (l) { return [l]; });
  13208. }
  13209. }
  13210. var updateInput;
  13211. // Normal behavior is to insert the new text into every selection
  13212. for (var i$1 = sel.ranges.length - 1; i$1 >= 0; i$1--) {
  13213. var range$$1 = sel.ranges[i$1];
  13214. var from = range$$1.from(), to = range$$1.to();
  13215. if (range$$1.empty()) {
  13216. if (deleted && deleted > 0) // Handle deletion
  13217. { from = Pos(from.line, from.ch - deleted); }
  13218. else if (cm.state.overwrite && !paste) // Handle overwrite
  13219. { to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length)); }
  13220. else if (lastCopied && lastCopied.lineWise && lastCopied.text.join("\n") == inserted)
  13221. { from = to = Pos(from.line, 0); }
  13222. }
  13223. updateInput = cm.curOp.updateInput;
  13224. var changeEvent = {from: from, to: to, text: multiPaste ? multiPaste[i$1 % multiPaste.length] : textLines,
  13225. origin: origin || (paste ? "paste" : cm.state.cutIncoming ? "cut" : "+input")};
  13226. makeChange(cm.doc, changeEvent);
  13227. signalLater(cm, "inputRead", cm, changeEvent);
  13228. }
  13229. if (inserted && !paste)
  13230. { triggerElectric(cm, inserted); }
  13231. ensureCursorVisible(cm);
  13232. cm.curOp.updateInput = updateInput;
  13233. cm.curOp.typing = true;
  13234. cm.state.pasteIncoming = cm.state.cutIncoming = false;
  13235. }
  13236. function handlePaste(e, cm) {
  13237. var pasted = e.clipboardData && e.clipboardData.getData("Text");
  13238. if (pasted) {
  13239. e.preventDefault();
  13240. if (!cm.isReadOnly() && !cm.options.disableInput)
  13241. { runInOp(cm, function () { return applyTextInput(cm, pasted, 0, null, "paste"); }); }
  13242. return true
  13243. }
  13244. }
  13245. function triggerElectric(cm, inserted) {
  13246. // When an 'electric' character is inserted, immediately trigger a reindent
  13247. if (!cm.options.electricChars || !cm.options.smartIndent) { return }
  13248. var sel = cm.doc.sel;
  13249. for (var i = sel.ranges.length - 1; i >= 0; i--) {
  13250. var range$$1 = sel.ranges[i];
  13251. if (range$$1.head.ch > 100 || (i && sel.ranges[i - 1].head.line == range$$1.head.line)) { continue }
  13252. var mode = cm.getModeAt(range$$1.head);
  13253. var indented = false;
  13254. if (mode.electricChars) {
  13255. for (var j = 0; j < mode.electricChars.length; j++)
  13256. { if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) {
  13257. indented = indentLine(cm, range$$1.head.line, "smart");
  13258. break
  13259. } }
  13260. } else if (mode.electricInput) {
  13261. if (mode.electricInput.test(getLine(cm.doc, range$$1.head.line).text.slice(0, range$$1.head.ch)))
  13262. { indented = indentLine(cm, range$$1.head.line, "smart"); }
  13263. }
  13264. if (indented) { signalLater(cm, "electricInput", cm, range$$1.head.line); }
  13265. }
  13266. }
  13267. function copyableRanges(cm) {
  13268. var text = [], ranges = [];
  13269. for (var i = 0; i < cm.doc.sel.ranges.length; i++) {
  13270. var line = cm.doc.sel.ranges[i].head.line;
  13271. var lineRange = {anchor: Pos(line, 0), head: Pos(line + 1, 0)};
  13272. ranges.push(lineRange);
  13273. text.push(cm.getRange(lineRange.anchor, lineRange.head));
  13274. }
  13275. return {text: text, ranges: ranges}
  13276. }
  13277. function disableBrowserMagic(field, spellcheck) {
  13278. field.setAttribute("autocorrect", "off");
  13279. field.setAttribute("autocapitalize", "off");
  13280. field.setAttribute("spellcheck", !!spellcheck);
  13281. }
  13282. function hiddenTextarea() {
  13283. var te = elt("textarea", null, null, "position: absolute; bottom: -1em; padding: 0; width: 1px; height: 1em; outline: none");
  13284. var div = elt("div", [te], null, "overflow: hidden; position: relative; width: 3px; height: 0px;");
  13285. // The textarea is kept positioned near the cursor to prevent the
  13286. // fact that it'll be scrolled into view on input from scrolling
  13287. // our fake cursor out of view. On webkit, when wrap=off, paste is
  13288. // very slow. So make the area wide instead.
  13289. if (webkit) { te.style.width = "1000px"; }
  13290. else { te.setAttribute("wrap", "off"); }
  13291. // If border: 0; -- iOS fails to open keyboard (issue #1287)
  13292. if (ios) { te.style.border = "1px solid black"; }
  13293. disableBrowserMagic(te);
  13294. return div
  13295. }
  13296. // The publicly visible API. Note that methodOp(f) means
  13297. // 'wrap f in an operation, performed on its `this` parameter'.
  13298. // This is not the complete set of editor methods. Most of the
  13299. // methods defined on the Doc type are also injected into
  13300. // CodeMirror.prototype, for backwards compatibility and
  13301. // convenience.
  13302. var addEditorMethods = function(CodeMirror) {
  13303. var optionHandlers = CodeMirror.optionHandlers;
  13304. var helpers = CodeMirror.helpers = {};
  13305. CodeMirror.prototype = {
  13306. constructor: CodeMirror,
  13307. focus: function(){window.focus(); this.display.input.focus();},
  13308. setOption: function(option, value) {
  13309. var options = this.options, old = options[option];
  13310. if (options[option] == value && option != "mode") { return }
  13311. options[option] = value;
  13312. if (optionHandlers.hasOwnProperty(option))
  13313. { operation(this, optionHandlers[option])(this, value, old); }
  13314. signal(this, "optionChange", this, option);
  13315. },
  13316. getOption: function(option) {return this.options[option]},
  13317. getDoc: function() {return this.doc},
  13318. addKeyMap: function(map$$1, bottom) {
  13319. this.state.keyMaps[bottom ? "push" : "unshift"](getKeyMap(map$$1));
  13320. },
  13321. removeKeyMap: function(map$$1) {
  13322. var maps = this.state.keyMaps;
  13323. for (var i = 0; i < maps.length; ++i)
  13324. { if (maps[i] == map$$1 || maps[i].name == map$$1) {
  13325. maps.splice(i, 1);
  13326. return true
  13327. } }
  13328. },
  13329. addOverlay: methodOp(function(spec, options) {
  13330. var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec);
  13331. if (mode.startState) { throw new Error("Overlays may not be stateful.") }
  13332. insertSorted(this.state.overlays,
  13333. {mode: mode, modeSpec: spec, opaque: options && options.opaque,
  13334. priority: (options && options.priority) || 0},
  13335. function (overlay) { return overlay.priority; });
  13336. this.state.modeGen++;
  13337. regChange(this);
  13338. }),
  13339. removeOverlay: methodOp(function(spec) {
  13340. var this$1 = this;
  13341. var overlays = this.state.overlays;
  13342. for (var i = 0; i < overlays.length; ++i) {
  13343. var cur = overlays[i].modeSpec;
  13344. if (cur == spec || typeof spec == "string" && cur.name == spec) {
  13345. overlays.splice(i, 1);
  13346. this$1.state.modeGen++;
  13347. regChange(this$1);
  13348. return
  13349. }
  13350. }
  13351. }),
  13352. indentLine: methodOp(function(n, dir, aggressive) {
  13353. if (typeof dir != "string" && typeof dir != "number") {
  13354. if (dir == null) { dir = this.options.smartIndent ? "smart" : "prev"; }
  13355. else { dir = dir ? "add" : "subtract"; }
  13356. }
  13357. if (isLine(this.doc, n)) { indentLine(this, n, dir, aggressive); }
  13358. }),
  13359. indentSelection: methodOp(function(how) {
  13360. var this$1 = this;
  13361. var ranges = this.doc.sel.ranges, end = -1;
  13362. for (var i = 0; i < ranges.length; i++) {
  13363. var range$$1 = ranges[i];
  13364. if (!range$$1.empty()) {
  13365. var from = range$$1.from(), to = range$$1.to();
  13366. var start = Math.max(end, from.line);
  13367. end = Math.min(this$1.lastLine(), to.line - (to.ch ? 0 : 1)) + 1;
  13368. for (var j = start; j < end; ++j)
  13369. { indentLine(this$1, j, how); }
  13370. var newRanges = this$1.doc.sel.ranges;
  13371. if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i].from().ch > 0)
  13372. { replaceOneSelection(this$1.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll); }
  13373. } else if (range$$1.head.line > end) {
  13374. indentLine(this$1, range$$1.head.line, how, true);
  13375. end = range$$1.head.line;
  13376. if (i == this$1.doc.sel.primIndex) { ensureCursorVisible(this$1); }
  13377. }
  13378. }
  13379. }),
  13380. // Fetch the parser token for a given character. Useful for hacks
  13381. // that want to inspect the mode state (say, for completion).
  13382. getTokenAt: function(pos, precise) {
  13383. return takeToken(this, pos, precise)
  13384. },
  13385. getLineTokens: function(line, precise) {
  13386. return takeToken(this, Pos(line), precise, true)
  13387. },
  13388. getTokenTypeAt: function(pos) {
  13389. pos = clipPos(this.doc, pos);
  13390. var styles = getLineStyles(this, getLine(this.doc, pos.line));
  13391. var before = 0, after = (styles.length - 1) / 2, ch = pos.ch;
  13392. var type;
  13393. if (ch == 0) { type = styles[2]; }
  13394. else { for (;;) {
  13395. var mid = (before + after) >> 1;
  13396. if ((mid ? styles[mid * 2 - 1] : 0) >= ch) { after = mid; }
  13397. else if (styles[mid * 2 + 1] < ch) { before = mid + 1; }
  13398. else { type = styles[mid * 2 + 2]; break }
  13399. } }
  13400. var cut = type ? type.indexOf("overlay ") : -1;
  13401. return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1)
  13402. },
  13403. getModeAt: function(pos) {
  13404. var mode = this.doc.mode;
  13405. if (!mode.innerMode) { return mode }
  13406. return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode
  13407. },
  13408. getHelper: function(pos, type) {
  13409. return this.getHelpers(pos, type)[0]
  13410. },
  13411. getHelpers: function(pos, type) {
  13412. var this$1 = this;
  13413. var found = [];
  13414. if (!helpers.hasOwnProperty(type)) { return found }
  13415. var help = helpers[type], mode = this.getModeAt(pos);
  13416. if (typeof mode[type] == "string") {
  13417. if (help[mode[type]]) { found.push(help[mode[type]]); }
  13418. } else if (mode[type]) {
  13419. for (var i = 0; i < mode[type].length; i++) {
  13420. var val = help[mode[type][i]];
  13421. if (val) { found.push(val); }
  13422. }
  13423. } else if (mode.helperType && help[mode.helperType]) {
  13424. found.push(help[mode.helperType]);
  13425. } else if (help[mode.name]) {
  13426. found.push(help[mode.name]);
  13427. }
  13428. for (var i$1 = 0; i$1 < help._global.length; i$1++) {
  13429. var cur = help._global[i$1];
  13430. if (cur.pred(mode, this$1) && indexOf(found, cur.val) == -1)
  13431. { found.push(cur.val); }
  13432. }
  13433. return found
  13434. },
  13435. getStateAfter: function(line, precise) {
  13436. var doc = this.doc;
  13437. line = clipLine(doc, line == null ? doc.first + doc.size - 1: line);
  13438. return getContextBefore(this, line + 1, precise).state
  13439. },
  13440. cursorCoords: function(start, mode) {
  13441. var pos, range$$1 = this.doc.sel.primary();
  13442. if (start == null) { pos = range$$1.head; }
  13443. else if (typeof start == "object") { pos = clipPos(this.doc, start); }
  13444. else { pos = start ? range$$1.from() : range$$1.to(); }
  13445. return cursorCoords(this, pos, mode || "page")
  13446. },
  13447. charCoords: function(pos, mode) {
  13448. return charCoords(this, clipPos(this.doc, pos), mode || "page")
  13449. },
  13450. coordsChar: function(coords, mode) {
  13451. coords = fromCoordSystem(this, coords, mode || "page");
  13452. return coordsChar(this, coords.left, coords.top)
  13453. },
  13454. lineAtHeight: function(height, mode) {
  13455. height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top;
  13456. return lineAtHeight(this.doc, height + this.display.viewOffset)
  13457. },
  13458. heightAtLine: function(line, mode, includeWidgets) {
  13459. var end = false, lineObj;
  13460. if (typeof line == "number") {
  13461. var last = this.doc.first + this.doc.size - 1;
  13462. if (line < this.doc.first) { line = this.doc.first; }
  13463. else if (line > last) { line = last; end = true; }
  13464. lineObj = getLine(this.doc, line);
  13465. } else {
  13466. lineObj = line;
  13467. }
  13468. return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || "page", includeWidgets || end).top +
  13469. (end ? this.doc.height - heightAtLine(lineObj) : 0)
  13470. },
  13471. defaultTextHeight: function() { return textHeight(this.display) },
  13472. defaultCharWidth: function() { return charWidth(this.display) },
  13473. getViewport: function() { return {from: this.display.viewFrom, to: this.display.viewTo}},
  13474. addWidget: function(pos, node, scroll, vert, horiz) {
  13475. var display = this.display;
  13476. pos = cursorCoords(this, clipPos(this.doc, pos));
  13477. var top = pos.bottom, left = pos.left;
  13478. node.style.position = "absolute";
  13479. node.setAttribute("cm-ignore-events", "true");
  13480. this.display.input.setUneditable(node);
  13481. display.sizer.appendChild(node);
  13482. if (vert == "over") {
  13483. top = pos.top;
  13484. } else if (vert == "above" || vert == "near") {
  13485. var vspace = Math.max(display.wrapper.clientHeight, this.doc.height),
  13486. hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth);
  13487. // Default to positioning above (if specified and possible); otherwise default to positioning below
  13488. if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight)
  13489. { top = pos.top - node.offsetHeight; }
  13490. else if (pos.bottom + node.offsetHeight <= vspace)
  13491. { top = pos.bottom; }
  13492. if (left + node.offsetWidth > hspace)
  13493. { left = hspace - node.offsetWidth; }
  13494. }
  13495. node.style.top = top + "px";
  13496. node.style.left = node.style.right = "";
  13497. if (horiz == "right") {
  13498. left = display.sizer.clientWidth - node.offsetWidth;
  13499. node.style.right = "0px";
  13500. } else {
  13501. if (horiz == "left") { left = 0; }
  13502. else if (horiz == "middle") { left = (display.sizer.clientWidth - node.offsetWidth) / 2; }
  13503. node.style.left = left + "px";
  13504. }
  13505. if (scroll)
  13506. { scrollIntoView(this, {left: left, top: top, right: left + node.offsetWidth, bottom: top + node.offsetHeight}); }
  13507. },
  13508. triggerOnKeyDown: methodOp(onKeyDown),
  13509. triggerOnKeyPress: methodOp(onKeyPress),
  13510. triggerOnKeyUp: onKeyUp,
  13511. triggerOnMouseDown: methodOp(onMouseDown),
  13512. execCommand: function(cmd) {
  13513. if (commands.hasOwnProperty(cmd))
  13514. { return commands[cmd].call(null, this) }
  13515. },
  13516. triggerElectric: methodOp(function(text) { triggerElectric(this, text); }),
  13517. findPosH: function(from, amount, unit, visually) {
  13518. var this$1 = this;
  13519. var dir = 1;
  13520. if (amount < 0) { dir = -1; amount = -amount; }
  13521. var cur = clipPos(this.doc, from);
  13522. for (var i = 0; i < amount; ++i) {
  13523. cur = findPosH(this$1.doc, cur, dir, unit, visually);
  13524. if (cur.hitSide) { break }
  13525. }
  13526. return cur
  13527. },
  13528. moveH: methodOp(function(dir, unit) {
  13529. var this$1 = this;
  13530. this.extendSelectionsBy(function (range$$1) {
  13531. if (this$1.display.shift || this$1.doc.extend || range$$1.empty())
  13532. { return findPosH(this$1.doc, range$$1.head, dir, unit, this$1.options.rtlMoveVisually) }
  13533. else
  13534. { return dir < 0 ? range$$1.from() : range$$1.to() }
  13535. }, sel_move);
  13536. }),
  13537. deleteH: methodOp(function(dir, unit) {
  13538. var sel = this.doc.sel, doc = this.doc;
  13539. if (sel.somethingSelected())
  13540. { doc.replaceSelection("", null, "+delete"); }
  13541. else
  13542. { deleteNearSelection(this, function (range$$1) {
  13543. var other = findPosH(doc, range$$1.head, dir, unit, false);
  13544. return dir < 0 ? {from: other, to: range$$1.head} : {from: range$$1.head, to: other}
  13545. }); }
  13546. }),
  13547. findPosV: function(from, amount, unit, goalColumn) {
  13548. var this$1 = this;
  13549. var dir = 1, x = goalColumn;
  13550. if (amount < 0) { dir = -1; amount = -amount; }
  13551. var cur = clipPos(this.doc, from);
  13552. for (var i = 0; i < amount; ++i) {
  13553. var coords = cursorCoords(this$1, cur, "div");
  13554. if (x == null) { x = coords.left; }
  13555. else { coords.left = x; }
  13556. cur = findPosV(this$1, coords, dir, unit);
  13557. if (cur.hitSide) { break }
  13558. }
  13559. return cur
  13560. },
  13561. moveV: methodOp(function(dir, unit) {
  13562. var this$1 = this;
  13563. var doc = this.doc, goals = [];
  13564. var collapse = !this.display.shift && !doc.extend && doc.sel.somethingSelected();
  13565. doc.extendSelectionsBy(function (range$$1) {
  13566. if (collapse)
  13567. { return dir < 0 ? range$$1.from() : range$$1.to() }
  13568. var headPos = cursorCoords(this$1, range$$1.head, "div");
  13569. if (range$$1.goalColumn != null) { headPos.left = range$$1.goalColumn; }
  13570. goals.push(headPos.left);
  13571. var pos = findPosV(this$1, headPos, dir, unit);
  13572. if (unit == "page" && range$$1 == doc.sel.primary())
  13573. { addToScrollTop(this$1, charCoords(this$1, pos, "div").top - headPos.top); }
  13574. return pos
  13575. }, sel_move);
  13576. if (goals.length) { for (var i = 0; i < doc.sel.ranges.length; i++)
  13577. { doc.sel.ranges[i].goalColumn = goals[i]; } }
  13578. }),
  13579. // Find the word at the given position (as returned by coordsChar).
  13580. findWordAt: function(pos) {
  13581. var doc = this.doc, line = getLine(doc, pos.line).text;
  13582. var start = pos.ch, end = pos.ch;
  13583. if (line) {
  13584. var helper = this.getHelper(pos, "wordChars");
  13585. if ((pos.sticky == "before" || end == line.length) && start) { --start; } else { ++end; }
  13586. var startChar = line.charAt(start);
  13587. var check = isWordChar(startChar, helper)
  13588. ? function (ch) { return isWordChar(ch, helper); }
  13589. : /\s/.test(startChar) ? function (ch) { return /\s/.test(ch); }
  13590. : function (ch) { return (!/\s/.test(ch) && !isWordChar(ch)); };
  13591. while (start > 0 && check(line.charAt(start - 1))) { --start; }
  13592. while (end < line.length && check(line.charAt(end))) { ++end; }
  13593. }
  13594. return new Range(Pos(pos.line, start), Pos(pos.line, end))
  13595. },
  13596. toggleOverwrite: function(value) {
  13597. if (value != null && value == this.state.overwrite) { return }
  13598. if (this.state.overwrite = !this.state.overwrite)
  13599. { addClass(this.display.cursorDiv, "CodeMirror-overwrite"); }
  13600. else
  13601. { rmClass(this.display.cursorDiv, "CodeMirror-overwrite"); }
  13602. signal(this, "overwriteToggle", this, this.state.overwrite);
  13603. },
  13604. hasFocus: function() { return this.display.input.getField() == activeElt() },
  13605. isReadOnly: function() { return !!(this.options.readOnly || this.doc.cantEdit) },
  13606. scrollTo: methodOp(function (x, y) { scrollToCoords(this, x, y); }),
  13607. getScrollInfo: function() {
  13608. var scroller = this.display.scroller;
  13609. return {left: scroller.scrollLeft, top: scroller.scrollTop,
  13610. height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight,
  13611. width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth,
  13612. clientHeight: displayHeight(this), clientWidth: displayWidth(this)}
  13613. },
  13614. scrollIntoView: methodOp(function(range$$1, margin) {
  13615. if (range$$1 == null) {
  13616. range$$1 = {from: this.doc.sel.primary().head, to: null};
  13617. if (margin == null) { margin = this.options.cursorScrollMargin; }
  13618. } else if (typeof range$$1 == "number") {
  13619. range$$1 = {from: Pos(range$$1, 0), to: null};
  13620. } else if (range$$1.from == null) {
  13621. range$$1 = {from: range$$1, to: null};
  13622. }
  13623. if (!range$$1.to) { range$$1.to = range$$1.from; }
  13624. range$$1.margin = margin || 0;
  13625. if (range$$1.from.line != null) {
  13626. scrollToRange(this, range$$1);
  13627. } else {
  13628. scrollToCoordsRange(this, range$$1.from, range$$1.to, range$$1.margin);
  13629. }
  13630. }),
  13631. setSize: methodOp(function(width, height) {
  13632. var this$1 = this;
  13633. var interpret = function (val) { return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val; };
  13634. if (width != null) { this.display.wrapper.style.width = interpret(width); }
  13635. if (height != null) { this.display.wrapper.style.height = interpret(height); }
  13636. if (this.options.lineWrapping) { clearLineMeasurementCache(this); }
  13637. var lineNo$$1 = this.display.viewFrom;
  13638. this.doc.iter(lineNo$$1, this.display.viewTo, function (line) {
  13639. if (line.widgets) { for (var i = 0; i < line.widgets.length; i++)
  13640. { if (line.widgets[i].noHScroll) { regLineChange(this$1, lineNo$$1, "widget"); break } } }
  13641. ++lineNo$$1;
  13642. });
  13643. this.curOp.forceUpdate = true;
  13644. signal(this, "refresh", this);
  13645. }),
  13646. operation: function(f){return runInOp(this, f)},
  13647. startOperation: function(){return startOperation(this)},
  13648. endOperation: function(){return endOperation(this)},
  13649. refresh: methodOp(function() {
  13650. var oldHeight = this.display.cachedTextHeight;
  13651. regChange(this);
  13652. this.curOp.forceUpdate = true;
  13653. clearCaches(this);
  13654. scrollToCoords(this, this.doc.scrollLeft, this.doc.scrollTop);
  13655. updateGutterSpace(this);
  13656. if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5)
  13657. { estimateLineHeights(this); }
  13658. signal(this, "refresh", this);
  13659. }),
  13660. swapDoc: methodOp(function(doc) {
  13661. var old = this.doc;
  13662. old.cm = null;
  13663. attachDoc(this, doc);
  13664. clearCaches(this);
  13665. this.display.input.reset();
  13666. scrollToCoords(this, doc.scrollLeft, doc.scrollTop);
  13667. this.curOp.forceScroll = true;
  13668. signalLater(this, "swapDoc", this, old);
  13669. return old
  13670. }),
  13671. getInputField: function(){return this.display.input.getField()},
  13672. getWrapperElement: function(){return this.display.wrapper},
  13673. getScrollerElement: function(){return this.display.scroller},
  13674. getGutterElement: function(){return this.display.gutters}
  13675. };
  13676. eventMixin(CodeMirror);
  13677. CodeMirror.registerHelper = function(type, name, value) {
  13678. if (!helpers.hasOwnProperty(type)) { helpers[type] = CodeMirror[type] = {_global: []}; }
  13679. helpers[type][name] = value;
  13680. };
  13681. CodeMirror.registerGlobalHelper = function(type, name, predicate, value) {
  13682. CodeMirror.registerHelper(type, name, value);
  13683. helpers[type]._global.push({pred: predicate, val: value});
  13684. };
  13685. };
  13686. // Used for horizontal relative motion. Dir is -1 or 1 (left or
  13687. // right), unit can be "char", "column" (like char, but doesn't
  13688. // cross line boundaries), "word" (across next word), or "group" (to
  13689. // the start of next group of word or non-word-non-whitespace
  13690. // chars). The visually param controls whether, in right-to-left
  13691. // text, direction 1 means to move towards the next index in the
  13692. // string, or towards the character to the right of the current
  13693. // position. The resulting position will have a hitSide=true
  13694. // property if it reached the end of the document.
  13695. function findPosH(doc, pos, dir, unit, visually) {
  13696. var oldPos = pos;
  13697. var origDir = dir;
  13698. var lineObj = getLine(doc, pos.line);
  13699. function findNextLine() {
  13700. var l = pos.line + dir;
  13701. if (l < doc.first || l >= doc.first + doc.size) { return false }
  13702. pos = new Pos(l, pos.ch, pos.sticky);
  13703. return lineObj = getLine(doc, l)
  13704. }
  13705. function moveOnce(boundToLine) {
  13706. var next;
  13707. if (visually) {
  13708. next = moveVisually(doc.cm, lineObj, pos, dir);
  13709. } else {
  13710. next = moveLogically(lineObj, pos, dir);
  13711. }
  13712. if (next == null) {
  13713. if (!boundToLine && findNextLine())
  13714. { pos = endOfLine(visually, doc.cm, lineObj, pos.line, dir); }
  13715. else
  13716. { return false }
  13717. } else {
  13718. pos = next;
  13719. }
  13720. return true
  13721. }
  13722. if (unit == "char") {
  13723. moveOnce();
  13724. } else if (unit == "column") {
  13725. moveOnce(true);
  13726. } else if (unit == "word" || unit == "group") {
  13727. var sawType = null, group = unit == "group";
  13728. var helper = doc.cm && doc.cm.getHelper(pos, "wordChars");
  13729. for (var first = true;; first = false) {
  13730. if (dir < 0 && !moveOnce(!first)) { break }
  13731. var cur = lineObj.text.charAt(pos.ch) || "\n";
  13732. var type = isWordChar(cur, helper) ? "w"
  13733. : group && cur == "\n" ? "n"
  13734. : !group || /\s/.test(cur) ? null
  13735. : "p";
  13736. if (group && !first && !type) { type = "s"; }
  13737. if (sawType && sawType != type) {
  13738. if (dir < 0) {dir = 1; moveOnce(); pos.sticky = "after";}
  13739. break
  13740. }
  13741. if (type) { sawType = type; }
  13742. if (dir > 0 && !moveOnce(!first)) { break }
  13743. }
  13744. }
  13745. var result = skipAtomic(doc, pos, oldPos, origDir, true);
  13746. if (equalCursorPos(oldPos, result)) { result.hitSide = true; }
  13747. return result
  13748. }
  13749. // For relative vertical movement. Dir may be -1 or 1. Unit can be
  13750. // "page" or "line". The resulting position will have a hitSide=true
  13751. // property if it reached the end of the document.
  13752. function findPosV(cm, pos, dir, unit) {
  13753. var doc = cm.doc, x = pos.left, y;
  13754. if (unit == "page") {
  13755. var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight);
  13756. var moveAmount = Math.max(pageSize - .5 * textHeight(cm.display), 3);
  13757. y = (dir > 0 ? pos.bottom : pos.top) + dir * moveAmount;
  13758. } else if (unit == "line") {
  13759. y = dir > 0 ? pos.bottom + 3 : pos.top - 3;
  13760. }
  13761. var target;
  13762. for (;;) {
  13763. target = coordsChar(cm, x, y);
  13764. if (!target.outside) { break }
  13765. if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break }
  13766. y += dir * 5;
  13767. }
  13768. return target
  13769. }
  13770. // CONTENTEDITABLE INPUT STYLE
  13771. var ContentEditableInput = function(cm) {
  13772. this.cm = cm;
  13773. this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null;
  13774. this.polling = new Delayed();
  13775. this.composing = null;
  13776. this.gracePeriod = false;
  13777. this.readDOMTimeout = null;
  13778. };
  13779. ContentEditableInput.prototype.init = function (display) {
  13780. var this$1 = this;
  13781. var input = this, cm = input.cm;
  13782. var div = input.div = display.lineDiv;
  13783. disableBrowserMagic(div, cm.options.spellcheck);
  13784. on(div, "paste", function (e) {
  13785. if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { return }
  13786. // IE doesn't fire input events, so we schedule a read for the pasted content in this way
  13787. if (ie_version <= 11) { setTimeout(operation(cm, function () { return this$1.updateFromDOM(); }), 20); }
  13788. });
  13789. on(div, "compositionstart", function (e) {
  13790. this$1.composing = {data: e.data, done: false};
  13791. });
  13792. on(div, "compositionupdate", function (e) {
  13793. if (!this$1.composing) { this$1.composing = {data: e.data, done: false}; }
  13794. });
  13795. on(div, "compositionend", function (e) {
  13796. if (this$1.composing) {
  13797. if (e.data != this$1.composing.data) { this$1.readFromDOMSoon(); }
  13798. this$1.composing.done = true;
  13799. }
  13800. });
  13801. on(div, "touchstart", function () { return input.forceCompositionEnd(); });
  13802. on(div, "input", function () {
  13803. if (!this$1.composing) { this$1.readFromDOMSoon(); }
  13804. });
  13805. function onCopyCut(e) {
  13806. if (signalDOMEvent(cm, e)) { return }
  13807. if (cm.somethingSelected()) {
  13808. setLastCopied({lineWise: false, text: cm.getSelections()});
  13809. if (e.type == "cut") { cm.replaceSelection("", null, "cut"); }
  13810. } else if (!cm.options.lineWiseCopyCut) {
  13811. return
  13812. } else {
  13813. var ranges = copyableRanges(cm);
  13814. setLastCopied({lineWise: true, text: ranges.text});
  13815. if (e.type == "cut") {
  13816. cm.operation(function () {
  13817. cm.setSelections(ranges.ranges, 0, sel_dontScroll);
  13818. cm.replaceSelection("", null, "cut");
  13819. });
  13820. }
  13821. }
  13822. if (e.clipboardData) {
  13823. e.clipboardData.clearData();
  13824. var content = lastCopied.text.join("\n");
  13825. // iOS exposes the clipboard API, but seems to discard content inserted into it
  13826. e.clipboardData.setData("Text", content);
  13827. if (e.clipboardData.getData("Text") == content) {
  13828. e.preventDefault();
  13829. return
  13830. }
  13831. }
  13832. // Old-fashioned briefly-focus-a-textarea hack
  13833. var kludge = hiddenTextarea(), te = kludge.firstChild;
  13834. cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild);
  13835. te.value = lastCopied.text.join("\n");
  13836. var hadFocus = document.activeElement;
  13837. selectInput(te);
  13838. setTimeout(function () {
  13839. cm.display.lineSpace.removeChild(kludge);
  13840. hadFocus.focus();
  13841. if (hadFocus == div) { input.showPrimarySelection(); }
  13842. }, 50);
  13843. }
  13844. on(div, "copy", onCopyCut);
  13845. on(div, "cut", onCopyCut);
  13846. };
  13847. ContentEditableInput.prototype.prepareSelection = function () {
  13848. var result = prepareSelection(this.cm, false);
  13849. result.focus = this.cm.state.focused;
  13850. return result
  13851. };
  13852. ContentEditableInput.prototype.showSelection = function (info, takeFocus) {
  13853. if (!info || !this.cm.display.view.length) { return }
  13854. if (info.focus || takeFocus) { this.showPrimarySelection(); }
  13855. this.showMultipleSelections(info);
  13856. };
  13857. ContentEditableInput.prototype.showPrimarySelection = function () {
  13858. var sel = window.getSelection(), cm = this.cm, prim = cm.doc.sel.primary();
  13859. var from = prim.from(), to = prim.to();
  13860. if (cm.display.viewTo == cm.display.viewFrom || from.line >= cm.display.viewTo || to.line < cm.display.viewFrom) {
  13861. sel.removeAllRanges();
  13862. return
  13863. }
  13864. var curAnchor = domToPos(cm, sel.anchorNode, sel.anchorOffset);
  13865. var curFocus = domToPos(cm, sel.focusNode, sel.focusOffset);
  13866. if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad &&
  13867. cmp(minPos(curAnchor, curFocus), from) == 0 &&
  13868. cmp(maxPos(curAnchor, curFocus), to) == 0)
  13869. { return }
  13870. var view = cm.display.view;
  13871. var start = (from.line >= cm.display.viewFrom && posToDOM(cm, from)) ||
  13872. {node: view[0].measure.map[2], offset: 0};
  13873. var end = to.line < cm.display.viewTo && posToDOM(cm, to);
  13874. if (!end) {
  13875. var measure = view[view.length - 1].measure;
  13876. var map$$1 = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map;
  13877. end = {node: map$$1[map$$1.length - 1], offset: map$$1[map$$1.length - 2] - map$$1[map$$1.length - 3]};
  13878. }
  13879. if (!start || !end) {
  13880. sel.removeAllRanges();
  13881. return
  13882. }
  13883. var old = sel.rangeCount && sel.getRangeAt(0), rng;
  13884. try { rng = range(start.node, start.offset, end.offset, end.node); }
  13885. catch(e) {} // Our model of the DOM might be outdated, in which case the range we try to set can be impossible
  13886. if (rng) {
  13887. if (!gecko && cm.state.focused) {
  13888. sel.collapse(start.node, start.offset);
  13889. if (!rng.collapsed) {
  13890. sel.removeAllRanges();
  13891. sel.addRange(rng);
  13892. }
  13893. } else {
  13894. sel.removeAllRanges();
  13895. sel.addRange(rng);
  13896. }
  13897. if (old && sel.anchorNode == null) { sel.addRange(old); }
  13898. else if (gecko) { this.startGracePeriod(); }
  13899. }
  13900. this.rememberSelection();
  13901. };
  13902. ContentEditableInput.prototype.startGracePeriod = function () {
  13903. var this$1 = this;
  13904. clearTimeout(this.gracePeriod);
  13905. this.gracePeriod = setTimeout(function () {
  13906. this$1.gracePeriod = false;
  13907. if (this$1.selectionChanged())
  13908. { this$1.cm.operation(function () { return this$1.cm.curOp.selectionChanged = true; }); }
  13909. }, 20);
  13910. };
  13911. ContentEditableInput.prototype.showMultipleSelections = function (info) {
  13912. removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors);
  13913. removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection);
  13914. };
  13915. ContentEditableInput.prototype.rememberSelection = function () {
  13916. var sel = window.getSelection();
  13917. this.lastAnchorNode = sel.anchorNode; this.lastAnchorOffset = sel.anchorOffset;
  13918. this.lastFocusNode = sel.focusNode; this.lastFocusOffset = sel.focusOffset;
  13919. };
  13920. ContentEditableInput.prototype.selectionInEditor = function () {
  13921. var sel = window.getSelection();
  13922. if (!sel.rangeCount) { return false }
  13923. var node = sel.getRangeAt(0).commonAncestorContainer;
  13924. return contains(this.div, node)
  13925. };
  13926. ContentEditableInput.prototype.focus = function () {
  13927. if (this.cm.options.readOnly != "nocursor") {
  13928. if (!this.selectionInEditor())
  13929. { this.showSelection(this.prepareSelection(), true); }
  13930. this.div.focus();
  13931. }
  13932. };
  13933. ContentEditableInput.prototype.blur = function () { this.div.blur(); };
  13934. ContentEditableInput.prototype.getField = function () { return this.div };
  13935. ContentEditableInput.prototype.supportsTouch = function () { return true };
  13936. ContentEditableInput.prototype.receivedFocus = function () {
  13937. var input = this;
  13938. if (this.selectionInEditor())
  13939. { this.pollSelection(); }
  13940. else
  13941. { runInOp(this.cm, function () { return input.cm.curOp.selectionChanged = true; }); }
  13942. function poll() {
  13943. if (input.cm.state.focused) {
  13944. input.pollSelection();
  13945. input.polling.set(input.cm.options.pollInterval, poll);
  13946. }
  13947. }
  13948. this.polling.set(this.cm.options.pollInterval, poll);
  13949. };
  13950. ContentEditableInput.prototype.selectionChanged = function () {
  13951. var sel = window.getSelection();
  13952. return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset ||
  13953. sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset
  13954. };
  13955. ContentEditableInput.prototype.pollSelection = function () {
  13956. if (this.readDOMTimeout != null || this.gracePeriod || !this.selectionChanged()) { return }
  13957. var sel = window.getSelection(), cm = this.cm;
  13958. // On Android Chrome (version 56, at least), backspacing into an
  13959. // uneditable block element will put the cursor in that element,
  13960. // and then, because it's not editable, hide the virtual keyboard.
  13961. // Because Android doesn't allow us to actually detect backspace
  13962. // presses in a sane way, this code checks for when that happens
  13963. // and simulates a backspace press in this case.
  13964. if (android && chrome && this.cm.options.gutters.length && isInGutter(sel.anchorNode)) {
  13965. this.cm.triggerOnKeyDown({type: "keydown", keyCode: 8, preventDefault: Math.abs});
  13966. this.blur();
  13967. this.focus();
  13968. return
  13969. }
  13970. if (this.composing) { return }
  13971. this.rememberSelection();
  13972. var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset);
  13973. var head = domToPos(cm, sel.focusNode, sel.focusOffset);
  13974. if (anchor && head) { runInOp(cm, function () {
  13975. setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll);
  13976. if (anchor.bad || head.bad) { cm.curOp.selectionChanged = true; }
  13977. }); }
  13978. };
  13979. ContentEditableInput.prototype.pollContent = function () {
  13980. if (this.readDOMTimeout != null) {
  13981. clearTimeout(this.readDOMTimeout);
  13982. this.readDOMTimeout = null;
  13983. }
  13984. var cm = this.cm, display = cm.display, sel = cm.doc.sel.primary();
  13985. var from = sel.from(), to = sel.to();
  13986. if (from.ch == 0 && from.line > cm.firstLine())
  13987. { from = Pos(from.line - 1, getLine(cm.doc, from.line - 1).length); }
  13988. if (to.ch == getLine(cm.doc, to.line).text.length && to.line < cm.lastLine())
  13989. { to = Pos(to.line + 1, 0); }
  13990. if (from.line < display.viewFrom || to.line > display.viewTo - 1) { return false }
  13991. var fromIndex, fromLine, fromNode;
  13992. if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) {
  13993. fromLine = lineNo(display.view[0].line);
  13994. fromNode = display.view[0].node;
  13995. } else {
  13996. fromLine = lineNo(display.view[fromIndex].line);
  13997. fromNode = display.view[fromIndex - 1].node.nextSibling;
  13998. }
  13999. var toIndex = findViewIndex(cm, to.line);
  14000. var toLine, toNode;
  14001. if (toIndex == display.view.length - 1) {
  14002. toLine = display.viewTo - 1;
  14003. toNode = display.lineDiv.lastChild;
  14004. } else {
  14005. toLine = lineNo(display.view[toIndex + 1].line) - 1;
  14006. toNode = display.view[toIndex + 1].node.previousSibling;
  14007. }
  14008. if (!fromNode) { return false }
  14009. var newText = cm.doc.splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine));
  14010. var oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length));
  14011. while (newText.length > 1 && oldText.length > 1) {
  14012. if (lst(newText) == lst(oldText)) { newText.pop(); oldText.pop(); toLine--; }
  14013. else if (newText[0] == oldText[0]) { newText.shift(); oldText.shift(); fromLine++; }
  14014. else { break }
  14015. }
  14016. var cutFront = 0, cutEnd = 0;
  14017. var newTop = newText[0], oldTop = oldText[0], maxCutFront = Math.min(newTop.length, oldTop.length);
  14018. while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront))
  14019. { ++cutFront; }
  14020. var newBot = lst(newText), oldBot = lst(oldText);
  14021. var maxCutEnd = Math.min(newBot.length - (newText.length == 1 ? cutFront : 0),
  14022. oldBot.length - (oldText.length == 1 ? cutFront : 0));
  14023. while (cutEnd < maxCutEnd &&
  14024. newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1))
  14025. { ++cutEnd; }
  14026. // Try to move start of change to start of selection if ambiguous
  14027. if (newText.length == 1 && oldText.length == 1 && fromLine == from.line) {
  14028. while (cutFront && cutFront > from.ch &&
  14029. newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) {
  14030. cutFront--;
  14031. cutEnd++;
  14032. }
  14033. }
  14034. newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd).replace(/^\u200b+/, "");
  14035. newText[0] = newText[0].slice(cutFront).replace(/\u200b+$/, "");
  14036. var chFrom = Pos(fromLine, cutFront);
  14037. var chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0);
  14038. if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) {
  14039. replaceRange(cm.doc, newText, chFrom, chTo, "+input");
  14040. return true
  14041. }
  14042. };
  14043. ContentEditableInput.prototype.ensurePolled = function () {
  14044. this.forceCompositionEnd();
  14045. };
  14046. ContentEditableInput.prototype.reset = function () {
  14047. this.forceCompositionEnd();
  14048. };
  14049. ContentEditableInput.prototype.forceCompositionEnd = function () {
  14050. if (!this.composing) { return }
  14051. clearTimeout(this.readDOMTimeout);
  14052. this.composing = null;
  14053. this.updateFromDOM();
  14054. this.div.blur();
  14055. this.div.focus();
  14056. };
  14057. ContentEditableInput.prototype.readFromDOMSoon = function () {
  14058. var this$1 = this;
  14059. if (this.readDOMTimeout != null) { return }
  14060. this.readDOMTimeout = setTimeout(function () {
  14061. this$1.readDOMTimeout = null;
  14062. if (this$1.composing) {
  14063. if (this$1.composing.done) { this$1.composing = null; }
  14064. else { return }
  14065. }
  14066. this$1.updateFromDOM();
  14067. }, 80);
  14068. };
  14069. ContentEditableInput.prototype.updateFromDOM = function () {
  14070. var this$1 = this;
  14071. if (this.cm.isReadOnly() || !this.pollContent())
  14072. { runInOp(this.cm, function () { return regChange(this$1.cm); }); }
  14073. };
  14074. ContentEditableInput.prototype.setUneditable = function (node) {
  14075. node.contentEditable = "false";
  14076. };
  14077. ContentEditableInput.prototype.onKeyPress = function (e) {
  14078. if (e.charCode == 0) { return }
  14079. e.preventDefault();
  14080. if (!this.cm.isReadOnly())
  14081. { operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0); }
  14082. };
  14083. ContentEditableInput.prototype.readOnlyChanged = function (val) {
  14084. this.div.contentEditable = String(val != "nocursor");
  14085. };
  14086. ContentEditableInput.prototype.onContextMenu = function () {};
  14087. ContentEditableInput.prototype.resetPosition = function () {};
  14088. ContentEditableInput.prototype.needsContentAttribute = true;
  14089. function posToDOM(cm, pos) {
  14090. var view = findViewForLine(cm, pos.line);
  14091. if (!view || view.hidden) { return null }
  14092. var line = getLine(cm.doc, pos.line);
  14093. var info = mapFromLineView(view, line, pos.line);
  14094. var order = getOrder(line, cm.doc.direction), side = "left";
  14095. if (order) {
  14096. var partPos = getBidiPartAt(order, pos.ch);
  14097. side = partPos % 2 ? "right" : "left";
  14098. }
  14099. var result = nodeAndOffsetInLineMap(info.map, pos.ch, side);
  14100. result.offset = result.collapse == "right" ? result.end : result.start;
  14101. return result
  14102. }
  14103. function isInGutter(node) {
  14104. for (var scan = node; scan; scan = scan.parentNode)
  14105. { if (/CodeMirror-gutter-wrapper/.test(scan.className)) { return true } }
  14106. return false
  14107. }
  14108. function badPos(pos, bad) { if (bad) { pos.bad = true; } return pos }
  14109. function domTextBetween(cm, from, to, fromLine, toLine) {
  14110. var text = "", closing = false, lineSep = cm.doc.lineSeparator();
  14111. function recognizeMarker(id) { return function (marker) { return marker.id == id; } }
  14112. function close() {
  14113. if (closing) {
  14114. text += lineSep;
  14115. closing = false;
  14116. }
  14117. }
  14118. function addText(str) {
  14119. if (str) {
  14120. close();
  14121. text += str;
  14122. }
  14123. }
  14124. function walk(node) {
  14125. if (node.nodeType == 1) {
  14126. var cmText = node.getAttribute("cm-text");
  14127. if (cmText != null) {
  14128. addText(cmText || node.textContent.replace(/\u200b/g, ""));
  14129. return
  14130. }
  14131. var markerID = node.getAttribute("cm-marker"), range$$1;
  14132. if (markerID) {
  14133. var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID));
  14134. if (found.length && (range$$1 = found[0].find(0)))
  14135. { addText(getBetween(cm.doc, range$$1.from, range$$1.to).join(lineSep)); }
  14136. return
  14137. }
  14138. if (node.getAttribute("contenteditable") == "false") { return }
  14139. var isBlock = /^(pre|div|p)$/i.test(node.nodeName);
  14140. if (isBlock) { close(); }
  14141. for (var i = 0; i < node.childNodes.length; i++)
  14142. { walk(node.childNodes[i]); }
  14143. if (isBlock) { closing = true; }
  14144. } else if (node.nodeType == 3) {
  14145. addText(node.nodeValue);
  14146. }
  14147. }
  14148. for (;;) {
  14149. walk(from);
  14150. if (from == to) { break }
  14151. from = from.nextSibling;
  14152. }
  14153. return text
  14154. }
  14155. function domToPos(cm, node, offset) {
  14156. var lineNode;
  14157. if (node == cm.display.lineDiv) {
  14158. lineNode = cm.display.lineDiv.childNodes[offset];
  14159. if (!lineNode) { return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true) }
  14160. node = null; offset = 0;
  14161. } else {
  14162. for (lineNode = node;; lineNode = lineNode.parentNode) {
  14163. if (!lineNode || lineNode == cm.display.lineDiv) { return null }
  14164. if (lineNode.parentNode && lineNode.parentNode == cm.display.lineDiv) { break }
  14165. }
  14166. }
  14167. for (var i = 0; i < cm.display.view.length; i++) {
  14168. var lineView = cm.display.view[i];
  14169. if (lineView.node == lineNode)
  14170. { return locateNodeInLineView(lineView, node, offset) }
  14171. }
  14172. }
  14173. function locateNodeInLineView(lineView, node, offset) {
  14174. var wrapper = lineView.text.firstChild, bad = false;
  14175. if (!node || !contains(wrapper, node)) { return badPos(Pos(lineNo(lineView.line), 0), true) }
  14176. if (node == wrapper) {
  14177. bad = true;
  14178. node = wrapper.childNodes[offset];
  14179. offset = 0;
  14180. if (!node) {
  14181. var line = lineView.rest ? lst(lineView.rest) : lineView.line;
  14182. return badPos(Pos(lineNo(line), line.text.length), bad)
  14183. }
  14184. }
  14185. var textNode = node.nodeType == 3 ? node : null, topNode = node;
  14186. if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) {
  14187. textNode = node.firstChild;
  14188. if (offset) { offset = textNode.nodeValue.length; }
  14189. }
  14190. while (topNode.parentNode != wrapper) { topNode = topNode.parentNode; }
  14191. var measure = lineView.measure, maps = measure.maps;
  14192. function find(textNode, topNode, offset) {
  14193. for (var i = -1; i < (maps ? maps.length : 0); i++) {
  14194. var map$$1 = i < 0 ? measure.map : maps[i];
  14195. for (var j = 0; j < map$$1.length; j += 3) {
  14196. var curNode = map$$1[j + 2];
  14197. if (curNode == textNode || curNode == topNode) {
  14198. var line = lineNo(i < 0 ? lineView.line : lineView.rest[i]);
  14199. var ch = map$$1[j] + offset;
  14200. if (offset < 0 || curNode != textNode) { ch = map$$1[j + (offset ? 1 : 0)]; }
  14201. return Pos(line, ch)
  14202. }
  14203. }
  14204. }
  14205. }
  14206. var found = find(textNode, topNode, offset);
  14207. if (found) { return badPos(found, bad) }
  14208. // FIXME this is all really shaky. might handle the few cases it needs to handle, but likely to cause problems
  14209. for (var after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) {
  14210. found = find(after, after.firstChild, 0);
  14211. if (found)
  14212. { return badPos(Pos(found.line, found.ch - dist), bad) }
  14213. else
  14214. { dist += after.textContent.length; }
  14215. }
  14216. for (var before = topNode.previousSibling, dist$1 = offset; before; before = before.previousSibling) {
  14217. found = find(before, before.firstChild, -1);
  14218. if (found)
  14219. { return badPos(Pos(found.line, found.ch + dist$1), bad) }
  14220. else
  14221. { dist$1 += before.textContent.length; }
  14222. }
  14223. }
  14224. // TEXTAREA INPUT STYLE
  14225. var TextareaInput = function(cm) {
  14226. this.cm = cm;
  14227. // See input.poll and input.reset
  14228. this.prevInput = "";
  14229. // Flag that indicates whether we expect input to appear real soon
  14230. // now (after some event like 'keypress' or 'input') and are
  14231. // polling intensively.
  14232. this.pollingFast = false;
  14233. // Self-resetting timeout for the poller
  14234. this.polling = new Delayed();
  14235. // Used to work around IE issue with selection being forgotten when focus moves away from textarea
  14236. this.hasSelection = false;
  14237. this.composing = null;
  14238. };
  14239. TextareaInput.prototype.init = function (display) {
  14240. var this$1 = this;
  14241. var input = this, cm = this.cm;
  14242. // Wraps and hides input textarea
  14243. var div = this.wrapper = hiddenTextarea();
  14244. // The semihidden textarea that is focused when the editor is
  14245. // focused, and receives input.
  14246. var te = this.textarea = div.firstChild;
  14247. display.wrapper.insertBefore(div, display.wrapper.firstChild);
  14248. // Needed to hide big blue blinking cursor on Mobile Safari (doesn't seem to work in iOS 8 anymore)
  14249. if (ios) { te.style.width = "0px"; }
  14250. on(te, "input", function () {
  14251. if (ie && ie_version >= 9 && this$1.hasSelection) { this$1.hasSelection = null; }
  14252. input.poll();
  14253. });
  14254. on(te, "paste", function (e) {
  14255. if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { return }
  14256. cm.state.pasteIncoming = true;
  14257. input.fastPoll();
  14258. });
  14259. function prepareCopyCut(e) {
  14260. if (signalDOMEvent(cm, e)) { return }
  14261. if (cm.somethingSelected()) {
  14262. setLastCopied({lineWise: false, text: cm.getSelections()});
  14263. } else if (!cm.options.lineWiseCopyCut) {
  14264. return
  14265. } else {
  14266. var ranges = copyableRanges(cm);
  14267. setLastCopied({lineWise: true, text: ranges.text});
  14268. if (e.type == "cut") {
  14269. cm.setSelections(ranges.ranges, null, sel_dontScroll);
  14270. } else {
  14271. input.prevInput = "";
  14272. te.value = ranges.text.join("\n");
  14273. selectInput(te);
  14274. }
  14275. }
  14276. if (e.type == "cut") { cm.state.cutIncoming = true; }
  14277. }
  14278. on(te, "cut", prepareCopyCut);
  14279. on(te, "copy", prepareCopyCut);
  14280. on(display.scroller, "paste", function (e) {
  14281. if (eventInWidget(display, e) || signalDOMEvent(cm, e)) { return }
  14282. cm.state.pasteIncoming = true;
  14283. input.focus();
  14284. });
  14285. // Prevent normal selection in the editor (we handle our own)
  14286. on(display.lineSpace, "selectstart", function (e) {
  14287. if (!eventInWidget(display, e)) { e_preventDefault(e); }
  14288. });
  14289. on(te, "compositionstart", function () {
  14290. var start = cm.getCursor("from");
  14291. if (input.composing) { input.composing.range.clear(); }
  14292. input.composing = {
  14293. start: start,
  14294. range: cm.markText(start, cm.getCursor("to"), {className: "CodeMirror-composing"})
  14295. };
  14296. });
  14297. on(te, "compositionend", function () {
  14298. if (input.composing) {
  14299. input.poll();
  14300. input.composing.range.clear();
  14301. input.composing = null;
  14302. }
  14303. });
  14304. };
  14305. TextareaInput.prototype.prepareSelection = function () {
  14306. // Redraw the selection and/or cursor
  14307. var cm = this.cm, display = cm.display, doc = cm.doc;
  14308. var result = prepareSelection(cm);
  14309. // Move the hidden textarea near the cursor to prevent scrolling artifacts
  14310. if (cm.options.moveInputWithCursor) {
  14311. var headPos = cursorCoords(cm, doc.sel.primary().head, "div");
  14312. var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect();
  14313. result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10,
  14314. headPos.top + lineOff.top - wrapOff.top));
  14315. result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10,
  14316. headPos.left + lineOff.left - wrapOff.left));
  14317. }
  14318. return result
  14319. };
  14320. TextareaInput.prototype.showSelection = function (drawn) {
  14321. var cm = this.cm, display = cm.display;
  14322. removeChildrenAndAdd(display.cursorDiv, drawn.cursors);
  14323. removeChildrenAndAdd(display.selectionDiv, drawn.selection);
  14324. if (drawn.teTop != null) {
  14325. this.wrapper.style.top = drawn.teTop + "px";
  14326. this.wrapper.style.left = drawn.teLeft + "px";
  14327. }
  14328. };
  14329. // Reset the input to correspond to the selection (or to be empty,
  14330. // when not typing and nothing is selected)
  14331. TextareaInput.prototype.reset = function (typing) {
  14332. if (this.contextMenuPending || this.composing) { return }
  14333. var cm = this.cm;
  14334. if (cm.somethingSelected()) {
  14335. this.prevInput = "";
  14336. var content = cm.getSelection();
  14337. this.textarea.value = content;
  14338. if (cm.state.focused) { selectInput(this.textarea); }
  14339. if (ie && ie_version >= 9) { this.hasSelection = content; }
  14340. } else if (!typing) {
  14341. this.prevInput = this.textarea.value = "";
  14342. if (ie && ie_version >= 9) { this.hasSelection = null; }
  14343. }
  14344. };
  14345. TextareaInput.prototype.getField = function () { return this.textarea };
  14346. TextareaInput.prototype.supportsTouch = function () { return false };
  14347. TextareaInput.prototype.focus = function () {
  14348. if (this.cm.options.readOnly != "nocursor" && (!mobile || activeElt() != this.textarea)) {
  14349. try { this.textarea.focus(); }
  14350. catch (e) {} // IE8 will throw if the textarea is display: none or not in DOM
  14351. }
  14352. };
  14353. TextareaInput.prototype.blur = function () { this.textarea.blur(); };
  14354. TextareaInput.prototype.resetPosition = function () {
  14355. this.wrapper.style.top = this.wrapper.style.left = 0;
  14356. };
  14357. TextareaInput.prototype.receivedFocus = function () { this.slowPoll(); };
  14358. // Poll for input changes, using the normal rate of polling. This
  14359. // runs as long as the editor is focused.
  14360. TextareaInput.prototype.slowPoll = function () {
  14361. var this$1 = this;
  14362. if (this.pollingFast) { return }
  14363. this.polling.set(this.cm.options.pollInterval, function () {
  14364. this$1.poll();
  14365. if (this$1.cm.state.focused) { this$1.slowPoll(); }
  14366. });
  14367. };
  14368. // When an event has just come in that is likely to add or change
  14369. // something in the input textarea, we poll faster, to ensure that
  14370. // the change appears on the screen quickly.
  14371. TextareaInput.prototype.fastPoll = function () {
  14372. var missed = false, input = this;
  14373. input.pollingFast = true;
  14374. function p() {
  14375. var changed = input.poll();
  14376. if (!changed && !missed) {missed = true; input.polling.set(60, p);}
  14377. else {input.pollingFast = false; input.slowPoll();}
  14378. }
  14379. input.polling.set(20, p);
  14380. };
  14381. // Read input from the textarea, and update the document to match.
  14382. // When something is selected, it is present in the textarea, and
  14383. // selected (unless it is huge, in which case a placeholder is
  14384. // used). When nothing is selected, the cursor sits after previously
  14385. // seen text (can be empty), which is stored in prevInput (we must
  14386. // not reset the textarea when typing, because that breaks IME).
  14387. TextareaInput.prototype.poll = function () {
  14388. var this$1 = this;
  14389. var cm = this.cm, input = this.textarea, prevInput = this.prevInput;
  14390. // Since this is called a *lot*, try to bail out as cheaply as
  14391. // possible when it is clear that nothing happened. hasSelection
  14392. // will be the case when there is a lot of text in the textarea,
  14393. // in which case reading its value would be expensive.
  14394. if (this.contextMenuPending || !cm.state.focused ||
  14395. (hasSelection(input) && !prevInput && !this.composing) ||
  14396. cm.isReadOnly() || cm.options.disableInput || cm.state.keySeq)
  14397. { return false }
  14398. var text = input.value;
  14399. // If nothing changed, bail.
  14400. if (text == prevInput && !cm.somethingSelected()) { return false }
  14401. // Work around nonsensical selection resetting in IE9/10, and
  14402. // inexplicable appearance of private area unicode characters on
  14403. // some key combos in Mac (#2689).
  14404. if (ie && ie_version >= 9 && this.hasSelection === text ||
  14405. mac && /[\uf700-\uf7ff]/.test(text)) {
  14406. cm.display.input.reset();
  14407. return false
  14408. }
  14409. if (cm.doc.sel == cm.display.selForContextMenu) {
  14410. var first = text.charCodeAt(0);
  14411. if (first == 0x200b && !prevInput) { prevInput = "\u200b"; }
  14412. if (first == 0x21da) { this.reset(); return this.cm.execCommand("undo") }
  14413. }
  14414. // Find the part of the input that is actually new
  14415. var same = 0, l = Math.min(prevInput.length, text.length);
  14416. while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) { ++same; }
  14417. runInOp(cm, function () {
  14418. applyTextInput(cm, text.slice(same), prevInput.length - same,
  14419. null, this$1.composing ? "*compose" : null);
  14420. // Don't leave long text in the textarea, since it makes further polling slow
  14421. if (text.length > 1000 || text.indexOf("\n") > -1) { input.value = this$1.prevInput = ""; }
  14422. else { this$1.prevInput = text; }
  14423. if (this$1.composing) {
  14424. this$1.composing.range.clear();
  14425. this$1.composing.range = cm.markText(this$1.composing.start, cm.getCursor("to"),
  14426. {className: "CodeMirror-composing"});
  14427. }
  14428. });
  14429. return true
  14430. };
  14431. TextareaInput.prototype.ensurePolled = function () {
  14432. if (this.pollingFast && this.poll()) { this.pollingFast = false; }
  14433. };
  14434. TextareaInput.prototype.onKeyPress = function () {
  14435. if (ie && ie_version >= 9) { this.hasSelection = null; }
  14436. this.fastPoll();
  14437. };
  14438. TextareaInput.prototype.onContextMenu = function (e) {
  14439. var input = this, cm = input.cm, display = cm.display, te = input.textarea;
  14440. var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop;
  14441. if (!pos || presto) { return } // Opera is difficult.
  14442. // Reset the current text selection only if the click is done outside of the selection
  14443. // and 'resetSelectionOnContextMenu' option is true.
  14444. var reset = cm.options.resetSelectionOnContextMenu;
  14445. if (reset && cm.doc.sel.contains(pos) == -1)
  14446. { operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll); }
  14447. var oldCSS = te.style.cssText, oldWrapperCSS = input.wrapper.style.cssText;
  14448. input.wrapper.style.cssText = "position: absolute";
  14449. var wrapperBox = input.wrapper.getBoundingClientRect();
  14450. 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);";
  14451. var oldScrollY;
  14452. if (webkit) { oldScrollY = window.scrollY; } // Work around Chrome issue (#2712)
  14453. display.input.focus();
  14454. if (webkit) { window.scrollTo(null, oldScrollY); }
  14455. display.input.reset();
  14456. // Adds "Select all" to context menu in FF
  14457. if (!cm.somethingSelected()) { te.value = input.prevInput = " "; }
  14458. input.contextMenuPending = true;
  14459. display.selForContextMenu = cm.doc.sel;
  14460. clearTimeout(display.detectingSelectAll);
  14461. // Select-all will be greyed out if there's nothing to select, so
  14462. // this adds a zero-width space so that we can later check whether
  14463. // it got selected.
  14464. function prepareSelectAllHack() {
  14465. if (te.selectionStart != null) {
  14466. var selected = cm.somethingSelected();
  14467. var extval = "\u200b" + (selected ? te.value : "");
  14468. te.value = "\u21da"; // Used to catch context-menu undo
  14469. te.value = extval;
  14470. input.prevInput = selected ? "" : "\u200b";
  14471. te.selectionStart = 1; te.selectionEnd = extval.length;
  14472. // Re-set this, in case some other handler touched the
  14473. // selection in the meantime.
  14474. display.selForContextMenu = cm.doc.sel;
  14475. }
  14476. }
  14477. function rehide() {
  14478. input.contextMenuPending = false;
  14479. input.wrapper.style.cssText = oldWrapperCSS;
  14480. te.style.cssText = oldCSS;
  14481. if (ie && ie_version < 9) { display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos); }
  14482. // Try to detect the user choosing select-all
  14483. if (te.selectionStart != null) {
  14484. if (!ie || (ie && ie_version < 9)) { prepareSelectAllHack(); }
  14485. var i = 0, poll = function () {
  14486. if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0 &&
  14487. te.selectionEnd > 0 && input.prevInput == "\u200b") {
  14488. operation(cm, selectAll)(cm);
  14489. } else if (i++ < 10) {
  14490. display.detectingSelectAll = setTimeout(poll, 500);
  14491. } else {
  14492. display.selForContextMenu = null;
  14493. display.input.reset();
  14494. }
  14495. };
  14496. display.detectingSelectAll = setTimeout(poll, 200);
  14497. }
  14498. }
  14499. if (ie && ie_version >= 9) { prepareSelectAllHack(); }
  14500. if (captureRightClick) {
  14501. e_stop(e);
  14502. var mouseup = function () {
  14503. off(window, "mouseup", mouseup);
  14504. setTimeout(rehide, 20);
  14505. };
  14506. on(window, "mouseup", mouseup);
  14507. } else {
  14508. setTimeout(rehide, 50);
  14509. }
  14510. };
  14511. TextareaInput.prototype.readOnlyChanged = function (val) {
  14512. if (!val) { this.reset(); }
  14513. this.textarea.disabled = val == "nocursor";
  14514. };
  14515. TextareaInput.prototype.setUneditable = function () {};
  14516. TextareaInput.prototype.needsContentAttribute = false;
  14517. function fromTextArea(textarea, options) {
  14518. options = options ? copyObj(options) : {};
  14519. options.value = textarea.value;
  14520. if (!options.tabindex && textarea.tabIndex)
  14521. { options.tabindex = textarea.tabIndex; }
  14522. if (!options.placeholder && textarea.placeholder)
  14523. { options.placeholder = textarea.placeholder; }
  14524. // Set autofocus to true if this textarea is focused, or if it has
  14525. // autofocus and no other element is focused.
  14526. if (options.autofocus == null) {
  14527. var hasFocus = activeElt();
  14528. options.autofocus = hasFocus == textarea ||
  14529. textarea.getAttribute("autofocus") != null && hasFocus == document.body;
  14530. }
  14531. function save() {textarea.value = cm.getValue();}
  14532. var realSubmit;
  14533. if (textarea.form) {
  14534. on(textarea.form, "submit", save);
  14535. // Deplorable hack to make the submit method do the right thing.
  14536. if (!options.leaveSubmitMethodAlone) {
  14537. var form = textarea.form;
  14538. realSubmit = form.submit;
  14539. try {
  14540. var wrappedSubmit = form.submit = function () {
  14541. save();
  14542. form.submit = realSubmit;
  14543. form.submit();
  14544. form.submit = wrappedSubmit;
  14545. };
  14546. } catch(e) {}
  14547. }
  14548. }
  14549. options.finishInit = function (cm) {
  14550. cm.save = save;
  14551. cm.getTextArea = function () { return textarea; };
  14552. cm.toTextArea = function () {
  14553. cm.toTextArea = isNaN; // Prevent this from being ran twice
  14554. save();
  14555. textarea.parentNode.removeChild(cm.getWrapperElement());
  14556. textarea.style.display = "";
  14557. if (textarea.form) {
  14558. off(textarea.form, "submit", save);
  14559. if (typeof textarea.form.submit == "function")
  14560. { textarea.form.submit = realSubmit; }
  14561. }
  14562. };
  14563. };
  14564. textarea.style.display = "none";
  14565. var cm = CodeMirror$1(function (node) { return textarea.parentNode.insertBefore(node, textarea.nextSibling); },
  14566. options);
  14567. return cm
  14568. }
  14569. function addLegacyProps(CodeMirror) {
  14570. CodeMirror.off = off;
  14571. CodeMirror.on = on;
  14572. CodeMirror.wheelEventPixels = wheelEventPixels;
  14573. CodeMirror.Doc = Doc;
  14574. CodeMirror.splitLines = splitLinesAuto;
  14575. CodeMirror.countColumn = countColumn;
  14576. CodeMirror.findColumn = findColumn;
  14577. CodeMirror.isWordChar = isWordCharBasic;
  14578. CodeMirror.Pass = Pass;
  14579. CodeMirror.signal = signal;
  14580. CodeMirror.Line = Line;
  14581. CodeMirror.changeEnd = changeEnd;
  14582. CodeMirror.scrollbarModel = scrollbarModel;
  14583. CodeMirror.Pos = Pos;
  14584. CodeMirror.cmpPos = cmp;
  14585. CodeMirror.modes = modes;
  14586. CodeMirror.mimeModes = mimeModes;
  14587. CodeMirror.resolveMode = resolveMode;
  14588. CodeMirror.getMode = getMode;
  14589. CodeMirror.modeExtensions = modeExtensions;
  14590. CodeMirror.extendMode = extendMode;
  14591. CodeMirror.copyState = copyState;
  14592. CodeMirror.startState = startState;
  14593. CodeMirror.innerMode = innerMode;
  14594. CodeMirror.commands = commands;
  14595. CodeMirror.keyMap = keyMap;
  14596. CodeMirror.keyName = keyName;
  14597. CodeMirror.isModifierKey = isModifierKey;
  14598. CodeMirror.lookupKey = lookupKey;
  14599. CodeMirror.normalizeKeyMap = normalizeKeyMap;
  14600. CodeMirror.StringStream = StringStream;
  14601. CodeMirror.SharedTextMarker = SharedTextMarker;
  14602. CodeMirror.TextMarker = TextMarker;
  14603. CodeMirror.LineWidget = LineWidget;
  14604. CodeMirror.e_preventDefault = e_preventDefault;
  14605. CodeMirror.e_stopPropagation = e_stopPropagation;
  14606. CodeMirror.e_stop = e_stop;
  14607. CodeMirror.addClass = addClass;
  14608. CodeMirror.contains = contains;
  14609. CodeMirror.rmClass = rmClass;
  14610. CodeMirror.keyNames = keyNames;
  14611. }
  14612. // EDITOR CONSTRUCTOR
  14613. defineOptions(CodeMirror$1);
  14614. addEditorMethods(CodeMirror$1);
  14615. // Set up methods on CodeMirror's prototype to redirect to the editor's document.
  14616. var dontDelegate = "iter insert remove copy getEditor constructor".split(" ");
  14617. for (var prop in Doc.prototype) { if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0)
  14618. { CodeMirror$1.prototype[prop] = (function(method) {
  14619. return function() {return method.apply(this.doc, arguments)}
  14620. })(Doc.prototype[prop]); } }
  14621. eventMixin(Doc);
  14622. // INPUT HANDLING
  14623. CodeMirror$1.inputStyles = {"textarea": TextareaInput, "contenteditable": ContentEditableInput};
  14624. // MODE DEFINITION AND QUERYING
  14625. // Extra arguments are stored as the mode's dependencies, which is
  14626. // used by (legacy) mechanisms like loadmode.js to automatically
  14627. // load a mode. (Preferred mechanism is the require/define calls.)
  14628. CodeMirror$1.defineMode = function(name/*, mode, …*/) {
  14629. if (!CodeMirror$1.defaults.mode && name != "null") { CodeMirror$1.defaults.mode = name; }
  14630. defineMode.apply(this, arguments);
  14631. };
  14632. CodeMirror$1.defineMIME = defineMIME;
  14633. // Minimal default mode.
  14634. CodeMirror$1.defineMode("null", function () { return ({token: function (stream) { return stream.skipToEnd(); }}); });
  14635. CodeMirror$1.defineMIME("text/plain", "null");
  14636. // EXTENSIONS
  14637. CodeMirror$1.defineExtension = function (name, func) {
  14638. CodeMirror$1.prototype[name] = func;
  14639. };
  14640. CodeMirror$1.defineDocExtension = function (name, func) {
  14641. Doc.prototype[name] = func;
  14642. };
  14643. CodeMirror$1.fromTextArea = fromTextArea;
  14644. addLegacyProps(CodeMirror$1);
  14645. CodeMirror$1.version = "5.32.0";
  14646. return CodeMirror$1;
  14647. })));
  14648. /***/ }),
  14649. /* 41 */
  14650. /***/ (function(module, exports, __webpack_require__) {
  14651. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  14652. // Distributed under an MIT license: http://codemirror.net/LICENSE
  14653. (function(mod) {
  14654. if (true) // CommonJS
  14655. mod(__webpack_require__(40));
  14656. else if (typeof define == "function" && define.amd) // AMD
  14657. define(["../../lib/codemirror"], mod);
  14658. else // Plain browser env
  14659. mod(CodeMirror);
  14660. })(function(CodeMirror) {
  14661. "use strict";
  14662. var listRE = /^(\s*)(>[> ]*|[*+-] \[[x ]\]\s|[*+-]\s|(\d+)([.)]))(\s*)/,
  14663. emptyListRE = /^(\s*)(>[> ]*|[*+-] \[[x ]\]|[*+-]|(\d+)[.)])(\s*)$/,
  14664. unorderedListRE = /[*+-]\s/;
  14665. CodeMirror.commands.newlineAndIndentContinueMarkdownList = function(cm) {
  14666. if (cm.getOption("disableInput")) return CodeMirror.Pass;
  14667. var ranges = cm.listSelections(), replacements = [];
  14668. for (var i = 0; i < ranges.length; i++) {
  14669. var pos = ranges[i].head;
  14670. var eolState = cm.getStateAfter(pos.line);
  14671. var inList = eolState.list !== false;
  14672. var inQuote = eolState.quote !== 0;
  14673. var line = cm.getLine(pos.line), match = listRE.exec(line);
  14674. var cursorBeforeBullet = /^\s*$/.test(line.slice(0, pos.ch));
  14675. if (!ranges[i].empty() || (!inList && !inQuote) || !match || cursorBeforeBullet) {
  14676. cm.execCommand("newlineAndIndent");
  14677. return;
  14678. }
  14679. if (emptyListRE.test(line)) {
  14680. if (!/>\s*$/.test(line)) cm.replaceRange("", {
  14681. line: pos.line, ch: 0
  14682. }, {
  14683. line: pos.line, ch: pos.ch + 1
  14684. });
  14685. replacements[i] = "\n";
  14686. } else {
  14687. var indent = match[1], after = match[5];
  14688. var bullet = unorderedListRE.test(match[2]) || match[2].indexOf(">") >= 0
  14689. ? match[2].replace("x", " ")
  14690. : (parseInt(match[3], 10) + 1) + match[4];
  14691. replacements[i] = "\n" + indent + bullet + after;
  14692. incrementRemainingMarkdownListNumbers(cm, pos);
  14693. }
  14694. }
  14695. cm.replaceSelections(replacements);
  14696. };
  14697. // Auto-updating Markdown list numbers when a new item is added to the
  14698. // middle of a list
  14699. function incrementRemainingMarkdownListNumbers(cm, pos) {
  14700. var startLine = pos.line, lookAhead = 0, skipCount = 0;
  14701. var startItem = listRE.exec(cm.getLine(startLine)), startIndent = startItem[1];
  14702. do {
  14703. lookAhead += 1;
  14704. var nextLineNumber = startLine + lookAhead;
  14705. var nextLine = cm.getLine(nextLineNumber), nextItem = listRE.exec(nextLine);
  14706. if (nextItem) {
  14707. var nextIndent = nextItem[1];
  14708. var newNumber = (parseInt(startItem[3], 10) + lookAhead - skipCount);
  14709. var nextNumber = (parseInt(nextItem[3], 10)), itemNumber = nextNumber;
  14710. if (startIndent === nextIndent) {
  14711. if (newNumber === nextNumber) itemNumber = nextNumber + 1;
  14712. if (newNumber > nextNumber) itemNumber = newNumber + 1;
  14713. cm.replaceRange(
  14714. nextLine.replace(listRE, nextIndent + itemNumber + nextItem[4] + nextItem[5]),
  14715. {
  14716. line: nextLineNumber, ch: 0
  14717. }, {
  14718. line: nextLineNumber, ch: nextLine.length
  14719. });
  14720. } else {
  14721. if (startIndent.length > nextIndent.length) return;
  14722. // This doesn't run if the next line immediatley indents, as it is
  14723. // not clear of the users intention (new indented item or same level)
  14724. if ((startIndent.length < nextIndent.length) && (lookAhead === 1)) return;
  14725. skipCount += 1;
  14726. }
  14727. }
  14728. } while (nextItem);
  14729. }
  14730. });
  14731. /***/ }),
  14732. /* 42 */
  14733. /***/ (function(module, exports, __webpack_require__) {
  14734. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  14735. // Distributed under an MIT license: http://codemirror.net/LICENSE
  14736. var CodeMirror = __webpack_require__(40);
  14737. CodeMirror.commands.tabAndIndentMarkdownList = function (cm) {
  14738. var ranges = cm.listSelections();
  14739. var pos = ranges[0].head;
  14740. var eolState = cm.getStateAfter(pos.line);
  14741. var inList = eolState.list !== false;
  14742. if (inList) {
  14743. cm.execCommand("indentMore");
  14744. return;
  14745. }
  14746. if (cm.options.indentWithTabs) {
  14747. cm.execCommand("insertTab");
  14748. }
  14749. else {
  14750. var spaces = Array(cm.options.tabSize + 1).join(" ");
  14751. cm.replaceSelection(spaces);
  14752. }
  14753. };
  14754. CodeMirror.commands.shiftTabAndUnindentMarkdownList = function (cm) {
  14755. var ranges = cm.listSelections();
  14756. var pos = ranges[0].head;
  14757. var eolState = cm.getStateAfter(pos.line);
  14758. var inList = eolState.list !== false;
  14759. if (inList) {
  14760. cm.execCommand("indentLess");
  14761. return;
  14762. }
  14763. if (cm.options.indentWithTabs) {
  14764. cm.execCommand("insertTab");
  14765. }
  14766. else {
  14767. var spaces = Array(cm.options.tabSize + 1).join(" ");
  14768. cm.replaceSelection(spaces);
  14769. }
  14770. };
  14771. /***/ }),
  14772. /* 43 */
  14773. /***/ (function(module, exports, __webpack_require__) {
  14774. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  14775. // Distributed under an MIT license: http://codemirror.net/LICENSE
  14776. (function(mod) {
  14777. if (true) // CommonJS
  14778. mod(__webpack_require__(40));
  14779. else if (typeof define == "function" && define.amd) // AMD
  14780. define(["../../lib/codemirror"], mod);
  14781. else // Plain browser env
  14782. mod(CodeMirror);
  14783. })(function(CodeMirror) {
  14784. "use strict";
  14785. CodeMirror.defineOption("fullScreen", false, function(cm, val, old) {
  14786. if (old == CodeMirror.Init) old = false;
  14787. if (!old == !val) return;
  14788. if (val) setFullscreen(cm);
  14789. else setNormal(cm);
  14790. });
  14791. function setFullscreen(cm) {
  14792. var wrap = cm.getWrapperElement();
  14793. cm.state.fullScreenRestore = {scrollTop: window.pageYOffset, scrollLeft: window.pageXOffset,
  14794. width: wrap.style.width, height: wrap.style.height};
  14795. wrap.style.width = "";
  14796. wrap.style.height = "auto";
  14797. wrap.className += " CodeMirror-fullscreen";
  14798. document.documentElement.style.overflow = "hidden";
  14799. cm.refresh();
  14800. }
  14801. function setNormal(cm) {
  14802. var wrap = cm.getWrapperElement();
  14803. wrap.className = wrap.className.replace(/\s*CodeMirror-fullscreen\b/, "");
  14804. document.documentElement.style.overflow = "";
  14805. var info = cm.state.fullScreenRestore;
  14806. wrap.style.width = info.width; wrap.style.height = info.height;
  14807. window.scrollTo(info.scrollLeft, info.scrollTop);
  14808. cm.refresh();
  14809. }
  14810. });
  14811. /***/ }),
  14812. /* 44 */
  14813. /***/ (function(module, exports, __webpack_require__) {
  14814. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  14815. // Distributed under an MIT license: http://codemirror.net/LICENSE
  14816. (function(mod) {
  14817. if (true) // CommonJS
  14818. mod(__webpack_require__(40), __webpack_require__(45), __webpack_require__(46));
  14819. else if (typeof define == "function" && define.amd) // AMD
  14820. define(["../../lib/codemirror", "../xml/xml", "../meta"], mod);
  14821. else // Plain browser env
  14822. mod(CodeMirror);
  14823. })(function(CodeMirror) {
  14824. "use strict";
  14825. CodeMirror.defineMode("markdown", function(cmCfg, modeCfg) {
  14826. var htmlMode = CodeMirror.getMode(cmCfg, "text/html");
  14827. var htmlModeMissing = htmlMode.name == "null"
  14828. function getMode(name) {
  14829. if (CodeMirror.findModeByName) {
  14830. var found = CodeMirror.findModeByName(name);
  14831. if (found) name = found.mime || found.mimes[0];
  14832. }
  14833. var mode = CodeMirror.getMode(cmCfg, name);
  14834. return mode.name == "null" ? null : mode;
  14835. }
  14836. // Should characters that affect highlighting be highlighted separate?
  14837. // Does not include characters that will be output (such as `1.` and `-` for lists)
  14838. if (modeCfg.highlightFormatting === undefined)
  14839. modeCfg.highlightFormatting = false;
  14840. // Maximum number of nested blockquotes. Set to 0 for infinite nesting.
  14841. // Excess `>` will emit `error` token.
  14842. if (modeCfg.maxBlockquoteDepth === undefined)
  14843. modeCfg.maxBlockquoteDepth = 0;
  14844. // Turn on task lists? ("- [ ] " and "- [x] ")
  14845. if (modeCfg.taskLists === undefined) modeCfg.taskLists = false;
  14846. // Turn on strikethrough syntax
  14847. if (modeCfg.strikethrough === undefined)
  14848. modeCfg.strikethrough = false;
  14849. if (modeCfg.emoji === undefined)
  14850. modeCfg.emoji = false;
  14851. if (modeCfg.fencedCodeBlockHighlighting === undefined)
  14852. modeCfg.fencedCodeBlockHighlighting = true;
  14853. if (modeCfg.xml === undefined)
  14854. modeCfg.xml = true;
  14855. // Allow token types to be overridden by user-provided token types.
  14856. if (modeCfg.tokenTypeOverrides === undefined)
  14857. modeCfg.tokenTypeOverrides = {};
  14858. var tokenTypes = {
  14859. header: "header",
  14860. code: "comment",
  14861. quote: "quote",
  14862. list1: "variable-2",
  14863. list2: "variable-3",
  14864. list3: "keyword",
  14865. hr: "hr",
  14866. image: "image",
  14867. imageAltText: "image-alt-text",
  14868. imageMarker: "image-marker",
  14869. formatting: "formatting",
  14870. linkInline: "link",
  14871. linkEmail: "link",
  14872. linkText: "link",
  14873. linkHref: "string",
  14874. em: "em",
  14875. strong: "strong",
  14876. strikethrough: "strikethrough",
  14877. emoji: "builtin"
  14878. };
  14879. for (var tokenType in tokenTypes) {
  14880. if (tokenTypes.hasOwnProperty(tokenType) && modeCfg.tokenTypeOverrides[tokenType]) {
  14881. tokenTypes[tokenType] = modeCfg.tokenTypeOverrides[tokenType];
  14882. }
  14883. }
  14884. var hrRE = /^([*\-_])(?:\s*\1){2,}\s*$/
  14885. , listRE = /^(?:[*\-+]|^[0-9]+([.)]))\s+/
  14886. , taskListRE = /^\[(x| )\](?=\s)/i // Must follow listRE
  14887. , atxHeaderRE = modeCfg.allowAtxHeaderWithoutSpace ? /^(#+)/ : /^(#+)(?: |$)/
  14888. , setextHeaderRE = /^ *(?:\={1,}|-{1,})\s*$/
  14889. , textRE = /^[^#!\[\]*_\\<>` "'(~:]+/
  14890. , fencedCodeRE = /^(~~~+|```+)[ \t]*([\w+#-]*)[^\n`]*$/
  14891. , linkDefRE = /^\s*\[[^\]]+?\]:\s*\S+(\s*\S*\s*)?$/ // naive link-definition
  14892. , punctuation = /[!\"#$%&\'()*+,\-\.\/:;<=>?@\[\\\]^_`{|}~—]/
  14893. , expandedTab = " " // CommonMark specifies tab as 4 spaces
  14894. function switchInline(stream, state, f) {
  14895. state.f = state.inline = f;
  14896. return f(stream, state);
  14897. }
  14898. function switchBlock(stream, state, f) {
  14899. state.f = state.block = f;
  14900. return f(stream, state);
  14901. }
  14902. function lineIsEmpty(line) {
  14903. return !line || !/\S/.test(line.string)
  14904. }
  14905. // Blocks
  14906. function blankLine(state) {
  14907. // Reset linkTitle state
  14908. state.linkTitle = false;
  14909. // Reset EM state
  14910. state.em = false;
  14911. // Reset STRONG state
  14912. state.strong = false;
  14913. // Reset strikethrough state
  14914. state.strikethrough = false;
  14915. // Reset state.quote
  14916. state.quote = 0;
  14917. // Reset state.indentedCode
  14918. state.indentedCode = false;
  14919. if (state.f == htmlBlock) {
  14920. state.f = inlineNormal;
  14921. state.block = blockNormal;
  14922. }
  14923. // Reset state.trailingSpace
  14924. state.trailingSpace = 0;
  14925. state.trailingSpaceNewLine = false;
  14926. // Mark this line as blank
  14927. state.prevLine = state.thisLine
  14928. state.thisLine = {stream: null}
  14929. return null;
  14930. }
  14931. function blockNormal(stream, state) {
  14932. var firstTokenOnLine = stream.column() === state.indentation;
  14933. var prevLineLineIsEmpty = lineIsEmpty(state.prevLine.stream);
  14934. var prevLineIsIndentedCode = state.indentedCode;
  14935. var prevLineIsHr = state.prevLine.hr;
  14936. var prevLineIsList = state.list !== false;
  14937. var maxNonCodeIndentation = (state.listStack[state.listStack.length - 1] || 0) + 3;
  14938. state.indentedCode = false;
  14939. var lineIndentation = state.indentation;
  14940. // compute once per line (on first token)
  14941. if (state.indentationDiff === null) {
  14942. state.indentationDiff = state.indentation;
  14943. if (prevLineIsList) {
  14944. state.list = null;
  14945. // While this list item's marker's indentation is less than the deepest
  14946. // list item's content's indentation,pop the deepest list item
  14947. // indentation off the stack, and update block indentation state
  14948. while (lineIndentation < state.listStack[state.listStack.length - 1]) {
  14949. state.listStack.pop();
  14950. if (state.listStack.length) {
  14951. state.indentation = state.listStack[state.listStack.length - 1];
  14952. // less than the first list's indent -> the line is no longer a list
  14953. } else {
  14954. state.list = false;
  14955. }
  14956. }
  14957. if (state.list !== false) {
  14958. state.indentationDiff = lineIndentation - state.listStack[state.listStack.length - 1]
  14959. }
  14960. }
  14961. }
  14962. // not comprehensive (currently only for setext detection purposes)
  14963. var allowsInlineContinuation = (
  14964. !prevLineLineIsEmpty && !prevLineIsHr && !state.prevLine.header &&
  14965. (!prevLineIsList || !prevLineIsIndentedCode) &&
  14966. !state.prevLine.fencedCodeEnd
  14967. );
  14968. var isHr = (state.list === false || prevLineIsHr || prevLineLineIsEmpty) &&
  14969. state.indentation <= maxNonCodeIndentation && stream.match(hrRE);
  14970. var match = null;
  14971. if (state.indentationDiff >= 4 && (prevLineIsIndentedCode || state.prevLine.fencedCodeEnd ||
  14972. state.prevLine.header || prevLineLineIsEmpty)) {
  14973. stream.skipToEnd();
  14974. state.indentedCode = true;
  14975. return tokenTypes.code;
  14976. } else if (stream.eatSpace()) {
  14977. return null;
  14978. } else if (firstTokenOnLine && state.indentation <= maxNonCodeIndentation && (match = stream.match(atxHeaderRE)) && match[1].length <= 6) {
  14979. state.quote = 0;
  14980. state.header = match[1].length;
  14981. state.thisLine.header = true;
  14982. if (modeCfg.highlightFormatting) state.formatting = "header";
  14983. state.f = state.inline;
  14984. return getType(state);
  14985. } else if (state.indentation <= maxNonCodeIndentation && stream.eat('>')) {
  14986. state.quote = firstTokenOnLine ? 1 : state.quote + 1;
  14987. if (modeCfg.highlightFormatting) state.formatting = "quote";
  14988. stream.eatSpace();
  14989. return getType(state);
  14990. } else if (!isHr && !state.setext && firstTokenOnLine && state.indentation <= maxNonCodeIndentation && (match = stream.match(listRE))) {
  14991. var listType = match[1] ? "ol" : "ul";
  14992. state.indentation = lineIndentation + stream.current().length;
  14993. state.list = true;
  14994. state.quote = 0;
  14995. // Add this list item's content's indentation to the stack
  14996. state.listStack.push(state.indentation);
  14997. if (modeCfg.taskLists && stream.match(taskListRE, false)) {
  14998. state.taskList = true;
  14999. }
  15000. state.f = state.inline;
  15001. if (modeCfg.highlightFormatting) state.formatting = ["list", "list-" + listType];
  15002. return getType(state);
  15003. } else if (firstTokenOnLine && state.indentation <= maxNonCodeIndentation && (match = stream.match(fencedCodeRE, true))) {
  15004. state.quote = 0;
  15005. state.fencedEndRE = new RegExp(match[1] + "+ *$");
  15006. // try switching mode
  15007. state.localMode = modeCfg.fencedCodeBlockHighlighting && getMode(match[2]);
  15008. if (state.localMode) state.localState = CodeMirror.startState(state.localMode);
  15009. state.f = state.block = local;
  15010. if (modeCfg.highlightFormatting) state.formatting = "code-block";
  15011. state.code = -1
  15012. return getType(state);
  15013. // SETEXT has lowest block-scope precedence after HR, so check it after
  15014. // the others (code, blockquote, list...)
  15015. } else if (
  15016. // if setext set, indicates line after ---/===
  15017. state.setext || (
  15018. // line before ---/===
  15019. (!allowsInlineContinuation || !prevLineIsList) && !state.quote && state.list === false &&
  15020. !state.code && !isHr && !linkDefRE.test(stream.string) &&
  15021. (match = stream.lookAhead(1)) && (match = match.match(setextHeaderRE))
  15022. )
  15023. ) {
  15024. if ( !state.setext ) {
  15025. state.header = match[0].charAt(0) == '=' ? 1 : 2;
  15026. state.setext = state.header;
  15027. } else {
  15028. state.header = state.setext;
  15029. // has no effect on type so we can reset it now
  15030. state.setext = 0;
  15031. stream.skipToEnd();
  15032. if (modeCfg.highlightFormatting) state.formatting = "header";
  15033. }
  15034. state.thisLine.header = true;
  15035. state.f = state.inline;
  15036. return getType(state);
  15037. } else if (isHr) {
  15038. stream.skipToEnd();
  15039. state.hr = true;
  15040. state.thisLine.hr = true;
  15041. return tokenTypes.hr;
  15042. } else if (stream.peek() === '[') {
  15043. return switchInline(stream, state, footnoteLink);
  15044. }
  15045. return switchInline(stream, state, state.inline);
  15046. }
  15047. function htmlBlock(stream, state) {
  15048. var style = htmlMode.token(stream, state.htmlState);
  15049. if (!htmlModeMissing) {
  15050. var inner = CodeMirror.innerMode(htmlMode, state.htmlState)
  15051. if ((inner.mode.name == "xml" && inner.state.tagStart === null &&
  15052. (!inner.state.context && inner.state.tokenize.isInText)) ||
  15053. (state.md_inside && stream.current().indexOf(">") > -1)) {
  15054. state.f = inlineNormal;
  15055. state.block = blockNormal;
  15056. state.htmlState = null;
  15057. }
  15058. }
  15059. return style;
  15060. }
  15061. function local(stream, state) {
  15062. var currListInd = state.listStack[state.listStack.length - 1] || 0;
  15063. var hasExitedList = state.indentation < currListInd;
  15064. var maxFencedEndInd = currListInd + 3;
  15065. if (state.fencedEndRE && state.indentation <= maxFencedEndInd && (hasExitedList || stream.match(state.fencedEndRE))) {
  15066. if (modeCfg.highlightFormatting) state.formatting = "code-block";
  15067. var returnType;
  15068. if (!hasExitedList) returnType = getType(state)
  15069. state.localMode = state.localState = null;
  15070. state.block = blockNormal;
  15071. state.f = inlineNormal;
  15072. state.fencedEndRE = null;
  15073. state.code = 0
  15074. state.thisLine.fencedCodeEnd = true;
  15075. if (hasExitedList) return switchBlock(stream, state, state.block);
  15076. return returnType;
  15077. } else if (state.localMode) {
  15078. return state.localMode.token(stream, state.localState);
  15079. } else {
  15080. stream.skipToEnd();
  15081. return tokenTypes.code;
  15082. }
  15083. }
  15084. // Inline
  15085. function getType(state) {
  15086. var styles = [];
  15087. if (state.formatting) {
  15088. styles.push(tokenTypes.formatting);
  15089. if (typeof state.formatting === "string") state.formatting = [state.formatting];
  15090. for (var i = 0; i < state.formatting.length; i++) {
  15091. styles.push(tokenTypes.formatting + "-" + state.formatting[i]);
  15092. if (state.formatting[i] === "header") {
  15093. styles.push(tokenTypes.formatting + "-" + state.formatting[i] + "-" + state.header);
  15094. }
  15095. // Add `formatting-quote` and `formatting-quote-#` for blockquotes
  15096. // Add `error` instead if the maximum blockquote nesting depth is passed
  15097. if (state.formatting[i] === "quote") {
  15098. if (!modeCfg.maxBlockquoteDepth || modeCfg.maxBlockquoteDepth >= state.quote) {
  15099. styles.push(tokenTypes.formatting + "-" + state.formatting[i] + "-" + state.quote);
  15100. } else {
  15101. styles.push("error");
  15102. }
  15103. }
  15104. }
  15105. }
  15106. if (state.taskOpen) {
  15107. styles.push("meta");
  15108. return styles.length ? styles.join(' ') : null;
  15109. }
  15110. if (state.taskClosed) {
  15111. styles.push("property");
  15112. return styles.length ? styles.join(' ') : null;
  15113. }
  15114. if (state.linkHref) {
  15115. styles.push(tokenTypes.linkHref, "url");
  15116. } else { // Only apply inline styles to non-url text
  15117. if (state.strong) { styles.push(tokenTypes.strong); }
  15118. if (state.em) { styles.push(tokenTypes.em); }
  15119. if (state.strikethrough) { styles.push(tokenTypes.strikethrough); }
  15120. if (state.emoji) { styles.push(tokenTypes.emoji); }
  15121. if (state.linkText) { styles.push(tokenTypes.linkText); }
  15122. if (state.code) { styles.push(tokenTypes.code); }
  15123. if (state.image) { styles.push(tokenTypes.image); }
  15124. if (state.imageAltText) { styles.push(tokenTypes.imageAltText, "link"); }
  15125. if (state.imageMarker) { styles.push(tokenTypes.imageMarker); }
  15126. }
  15127. if (state.header) { styles.push(tokenTypes.header, tokenTypes.header + "-" + state.header); }
  15128. if (state.quote) {
  15129. styles.push(tokenTypes.quote);
  15130. // Add `quote-#` where the maximum for `#` is modeCfg.maxBlockquoteDepth
  15131. if (!modeCfg.maxBlockquoteDepth || modeCfg.maxBlockquoteDepth >= state.quote) {
  15132. styles.push(tokenTypes.quote + "-" + state.quote);
  15133. } else {
  15134. styles.push(tokenTypes.quote + "-" + modeCfg.maxBlockquoteDepth);
  15135. }
  15136. }
  15137. if (state.list !== false) {
  15138. var listMod = (state.listStack.length - 1) % 3;
  15139. if (!listMod) {
  15140. styles.push(tokenTypes.list1);
  15141. } else if (listMod === 1) {
  15142. styles.push(tokenTypes.list2);
  15143. } else {
  15144. styles.push(tokenTypes.list3);
  15145. }
  15146. }
  15147. if (state.trailingSpaceNewLine) {
  15148. styles.push("trailing-space-new-line");
  15149. } else if (state.trailingSpace) {
  15150. styles.push("trailing-space-" + (state.trailingSpace % 2 ? "a" : "b"));
  15151. }
  15152. return styles.length ? styles.join(' ') : null;
  15153. }
  15154. function handleText(stream, state) {
  15155. if (stream.match(textRE, true)) {
  15156. return getType(state);
  15157. }
  15158. return undefined;
  15159. }
  15160. function inlineNormal(stream, state) {
  15161. var style = state.text(stream, state);
  15162. if (typeof style !== 'undefined')
  15163. return style;
  15164. if (state.list) { // List marker (*, +, -, 1., etc)
  15165. state.list = null;
  15166. return getType(state);
  15167. }
  15168. if (state.taskList) {
  15169. var taskOpen = stream.match(taskListRE, true)[1] === " ";
  15170. if (taskOpen) state.taskOpen = true;
  15171. else state.taskClosed = true;
  15172. if (modeCfg.highlightFormatting) state.formatting = "task";
  15173. state.taskList = false;
  15174. return getType(state);
  15175. }
  15176. state.taskOpen = false;
  15177. state.taskClosed = false;
  15178. if (state.header && stream.match(/^#+$/, true)) {
  15179. if (modeCfg.highlightFormatting) state.formatting = "header";
  15180. return getType(state);
  15181. }
  15182. var ch = stream.next();
  15183. // Matches link titles present on next line
  15184. if (state.linkTitle) {
  15185. state.linkTitle = false;
  15186. var matchCh = ch;
  15187. if (ch === '(') {
  15188. matchCh = ')';
  15189. }
  15190. matchCh = (matchCh+'').replace(/([.?*+^\[\]\\(){}|-])/g, "\\$1");
  15191. var regex = '^\\s*(?:[^' + matchCh + '\\\\]+|\\\\\\\\|\\\\.)' + matchCh;
  15192. if (stream.match(new RegExp(regex), true)) {
  15193. return tokenTypes.linkHref;
  15194. }
  15195. }
  15196. // If this block is changed, it may need to be updated in GFM mode
  15197. if (ch === '`') {
  15198. var previousFormatting = state.formatting;
  15199. if (modeCfg.highlightFormatting) state.formatting = "code";
  15200. stream.eatWhile('`');
  15201. var count = stream.current().length
  15202. if (state.code == 0 && (!state.quote || count == 1)) {
  15203. state.code = count
  15204. return getType(state)
  15205. } else if (count == state.code) { // Must be exact
  15206. var t = getType(state)
  15207. state.code = 0
  15208. return t
  15209. } else {
  15210. state.formatting = previousFormatting
  15211. return getType(state)
  15212. }
  15213. } else if (state.code) {
  15214. return getType(state);
  15215. }
  15216. if (ch === '\\') {
  15217. stream.next();
  15218. if (modeCfg.highlightFormatting) {
  15219. var type = getType(state);
  15220. var formattingEscape = tokenTypes.formatting + "-escape";
  15221. return type ? type + " " + formattingEscape : formattingEscape;
  15222. }
  15223. }
  15224. if (ch === '!' && stream.match(/\[[^\]]*\] ?(?:\(|\[)/, false)) {
  15225. state.imageMarker = true;
  15226. state.image = true;
  15227. if (modeCfg.highlightFormatting) state.formatting = "image";
  15228. return getType(state);
  15229. }
  15230. if (ch === '[' && state.imageMarker && stream.match(/[^\]]*\](\(.*?\)| ?\[.*?\])/, false)) {
  15231. state.imageMarker = false;
  15232. state.imageAltText = true
  15233. if (modeCfg.highlightFormatting) state.formatting = "image";
  15234. return getType(state);
  15235. }
  15236. if (ch === ']' && state.imageAltText) {
  15237. if (modeCfg.highlightFormatting) state.formatting = "image";
  15238. var type = getType(state);
  15239. state.imageAltText = false;
  15240. state.image = false;
  15241. state.inline = state.f = linkHref;
  15242. return type;
  15243. }
  15244. if (ch === '[' && !state.image) {
  15245. state.linkText = true;
  15246. if (modeCfg.highlightFormatting) state.formatting = "link";
  15247. return getType(state);
  15248. }
  15249. if (ch === ']' && state.linkText) {
  15250. if (modeCfg.highlightFormatting) state.formatting = "link";
  15251. var type = getType(state);
  15252. state.linkText = false;
  15253. state.inline = state.f = stream.match(/\(.*?\)| ?\[.*?\]/, false) ? linkHref : inlineNormal
  15254. return type;
  15255. }
  15256. if (ch === '<' && stream.match(/^(https?|ftps?):\/\/(?:[^\\>]|\\.)+>/, false)) {
  15257. state.f = state.inline = linkInline;
  15258. if (modeCfg.highlightFormatting) state.formatting = "link";
  15259. var type = getType(state);
  15260. if (type){
  15261. type += " ";
  15262. } else {
  15263. type = "";
  15264. }
  15265. return type + tokenTypes.linkInline;
  15266. }
  15267. if (ch === '<' && stream.match(/^[^> \\]+@(?:[^\\>]|\\.)+>/, false)) {
  15268. state.f = state.inline = linkInline;
  15269. if (modeCfg.highlightFormatting) state.formatting = "link";
  15270. var type = getType(state);
  15271. if (type){
  15272. type += " ";
  15273. } else {
  15274. type = "";
  15275. }
  15276. return type + tokenTypes.linkEmail;
  15277. }
  15278. if (modeCfg.xml && ch === '<' && stream.match(/^(!--|[a-z]+(?:\s+[a-z_:.\-]+(?:\s*=\s*[^ >]+)?)*\s*>)/i, false)) {
  15279. var end = stream.string.indexOf(">", stream.pos);
  15280. if (end != -1) {
  15281. var atts = stream.string.substring(stream.start, end);
  15282. if (/markdown\s*=\s*('|"){0,1}1('|"){0,1}/.test(atts)) state.md_inside = true;
  15283. }
  15284. stream.backUp(1);
  15285. state.htmlState = CodeMirror.startState(htmlMode);
  15286. return switchBlock(stream, state, htmlBlock);
  15287. }
  15288. if (modeCfg.xml && ch === '<' && stream.match(/^\/\w*?>/)) {
  15289. state.md_inside = false;
  15290. return "tag";
  15291. } else if (ch === "*" || ch === "_") {
  15292. var len = 1, before = stream.pos == 1 ? " " : stream.string.charAt(stream.pos - 2)
  15293. while (len < 3 && stream.eat(ch)) len++
  15294. var after = stream.peek() || " "
  15295. // See http://spec.commonmark.org/0.27/#emphasis-and-strong-emphasis
  15296. var leftFlanking = !/\s/.test(after) && (!punctuation.test(after) || /\s/.test(before) || punctuation.test(before))
  15297. var rightFlanking = !/\s/.test(before) && (!punctuation.test(before) || /\s/.test(after) || punctuation.test(after))
  15298. var setEm = null, setStrong = null
  15299. if (len % 2) { // Em
  15300. if (!state.em && leftFlanking && (ch === "*" || !rightFlanking || punctuation.test(before)))
  15301. setEm = true
  15302. else if (state.em == ch && rightFlanking && (ch === "*" || !leftFlanking || punctuation.test(after)))
  15303. setEm = false
  15304. }
  15305. if (len > 1) { // Strong
  15306. if (!state.strong && leftFlanking && (ch === "*" || !rightFlanking || punctuation.test(before)))
  15307. setStrong = true
  15308. else if (state.strong == ch && rightFlanking && (ch === "*" || !leftFlanking || punctuation.test(after)))
  15309. setStrong = false
  15310. }
  15311. if (setStrong != null || setEm != null) {
  15312. if (modeCfg.highlightFormatting) state.formatting = setEm == null ? "strong" : setStrong == null ? "em" : "strong em"
  15313. if (setEm === true) state.em = ch
  15314. if (setStrong === true) state.strong = ch
  15315. var t = getType(state)
  15316. if (setEm === false) state.em = false
  15317. if (setStrong === false) state.strong = false
  15318. return t
  15319. }
  15320. } else if (ch === ' ') {
  15321. if (stream.eat('*') || stream.eat('_')) { // Probably surrounded by spaces
  15322. if (stream.peek() === ' ') { // Surrounded by spaces, ignore
  15323. return getType(state);
  15324. } else { // Not surrounded by spaces, back up pointer
  15325. stream.backUp(1);
  15326. }
  15327. }
  15328. }
  15329. if (modeCfg.strikethrough) {
  15330. if (ch === '~' && stream.eatWhile(ch)) {
  15331. if (state.strikethrough) {// Remove strikethrough
  15332. if (modeCfg.highlightFormatting) state.formatting = "strikethrough";
  15333. var t = getType(state);
  15334. state.strikethrough = false;
  15335. return t;
  15336. } else if (stream.match(/^[^\s]/, false)) {// Add strikethrough
  15337. state.strikethrough = true;
  15338. if (modeCfg.highlightFormatting) state.formatting = "strikethrough";
  15339. return getType(state);
  15340. }
  15341. } else if (ch === ' ') {
  15342. if (stream.match(/^~~/, true)) { // Probably surrounded by space
  15343. if (stream.peek() === ' ') { // Surrounded by spaces, ignore
  15344. return getType(state);
  15345. } else { // Not surrounded by spaces, back up pointer
  15346. stream.backUp(2);
  15347. }
  15348. }
  15349. }
  15350. }
  15351. if (modeCfg.emoji && ch === ":" && stream.match(/^[a-z_\d+-]+:/)) {
  15352. state.emoji = true;
  15353. if (modeCfg.highlightFormatting) state.formatting = "emoji";
  15354. var retType = getType(state);
  15355. state.emoji = false;
  15356. return retType;
  15357. }
  15358. if (ch === ' ') {
  15359. if (stream.match(/ +$/, false)) {
  15360. state.trailingSpace++;
  15361. } else if (state.trailingSpace) {
  15362. state.trailingSpaceNewLine = true;
  15363. }
  15364. }
  15365. return getType(state);
  15366. }
  15367. function linkInline(stream, state) {
  15368. var ch = stream.next();
  15369. if (ch === ">") {
  15370. state.f = state.inline = inlineNormal;
  15371. if (modeCfg.highlightFormatting) state.formatting = "link";
  15372. var type = getType(state);
  15373. if (type){
  15374. type += " ";
  15375. } else {
  15376. type = "";
  15377. }
  15378. return type + tokenTypes.linkInline;
  15379. }
  15380. stream.match(/^[^>]+/, true);
  15381. return tokenTypes.linkInline;
  15382. }
  15383. function linkHref(stream, state) {
  15384. // Check if space, and return NULL if so (to avoid marking the space)
  15385. if(stream.eatSpace()){
  15386. return null;
  15387. }
  15388. var ch = stream.next();
  15389. if (ch === '(' || ch === '[') {
  15390. state.f = state.inline = getLinkHrefInside(ch === "(" ? ")" : "]");
  15391. if (modeCfg.highlightFormatting) state.formatting = "link-string";
  15392. state.linkHref = true;
  15393. return getType(state);
  15394. }
  15395. return 'error';
  15396. }
  15397. var linkRE = {
  15398. ")": /^(?:[^\\\(\)]|\\.|\((?:[^\\\(\)]|\\.)*\))*?(?=\))/,
  15399. "]": /^(?:[^\\\[\]]|\\.|\[(?:[^\\\[\]]|\\.)*\])*?(?=\])/
  15400. }
  15401. function getLinkHrefInside(endChar) {
  15402. return function(stream, state) {
  15403. var ch = stream.next();
  15404. if (ch === endChar) {
  15405. state.f = state.inline = inlineNormal;
  15406. if (modeCfg.highlightFormatting) state.formatting = "link-string";
  15407. var returnState = getType(state);
  15408. state.linkHref = false;
  15409. return returnState;
  15410. }
  15411. stream.match(linkRE[endChar])
  15412. state.linkHref = true;
  15413. return getType(state);
  15414. };
  15415. }
  15416. function footnoteLink(stream, state) {
  15417. if (stream.match(/^([^\]\\]|\\.)*\]:/, false)) {
  15418. state.f = footnoteLinkInside;
  15419. stream.next(); // Consume [
  15420. if (modeCfg.highlightFormatting) state.formatting = "link";
  15421. state.linkText = true;
  15422. return getType(state);
  15423. }
  15424. return switchInline(stream, state, inlineNormal);
  15425. }
  15426. function footnoteLinkInside(stream, state) {
  15427. if (stream.match(/^\]:/, true)) {
  15428. state.f = state.inline = footnoteUrl;
  15429. if (modeCfg.highlightFormatting) state.formatting = "link";
  15430. var returnType = getType(state);
  15431. state.linkText = false;
  15432. return returnType;
  15433. }
  15434. stream.match(/^([^\]\\]|\\.)+/, true);
  15435. return tokenTypes.linkText;
  15436. }
  15437. function footnoteUrl(stream, state) {
  15438. // Check if space, and return NULL if so (to avoid marking the space)
  15439. if(stream.eatSpace()){
  15440. return null;
  15441. }
  15442. // Match URL
  15443. stream.match(/^[^\s]+/, true);
  15444. // Check for link title
  15445. if (stream.peek() === undefined) { // End of line, set flag to check next line
  15446. state.linkTitle = true;
  15447. } else { // More content on line, check if link title
  15448. stream.match(/^(?:\s+(?:"(?:[^"\\]|\\\\|\\.)+"|'(?:[^'\\]|\\\\|\\.)+'|\((?:[^)\\]|\\\\|\\.)+\)))?/, true);
  15449. }
  15450. state.f = state.inline = inlineNormal;
  15451. return tokenTypes.linkHref + " url";
  15452. }
  15453. var mode = {
  15454. startState: function() {
  15455. return {
  15456. f: blockNormal,
  15457. prevLine: {stream: null},
  15458. thisLine: {stream: null},
  15459. block: blockNormal,
  15460. htmlState: null,
  15461. indentation: 0,
  15462. inline: inlineNormal,
  15463. text: handleText,
  15464. formatting: false,
  15465. linkText: false,
  15466. linkHref: false,
  15467. linkTitle: false,
  15468. code: 0,
  15469. em: false,
  15470. strong: false,
  15471. header: 0,
  15472. setext: 0,
  15473. hr: false,
  15474. taskList: false,
  15475. list: false,
  15476. listStack: [],
  15477. quote: 0,
  15478. trailingSpace: 0,
  15479. trailingSpaceNewLine: false,
  15480. strikethrough: false,
  15481. emoji: false,
  15482. fencedEndRE: null
  15483. };
  15484. },
  15485. copyState: function(s) {
  15486. return {
  15487. f: s.f,
  15488. prevLine: s.prevLine,
  15489. thisLine: s.thisLine,
  15490. block: s.block,
  15491. htmlState: s.htmlState && CodeMirror.copyState(htmlMode, s.htmlState),
  15492. indentation: s.indentation,
  15493. localMode: s.localMode,
  15494. localState: s.localMode ? CodeMirror.copyState(s.localMode, s.localState) : null,
  15495. inline: s.inline,
  15496. text: s.text,
  15497. formatting: false,
  15498. linkText: s.linkText,
  15499. linkTitle: s.linkTitle,
  15500. code: s.code,
  15501. em: s.em,
  15502. strong: s.strong,
  15503. strikethrough: s.strikethrough,
  15504. emoji: s.emoji,
  15505. header: s.header,
  15506. setext: s.setext,
  15507. hr: s.hr,
  15508. taskList: s.taskList,
  15509. list: s.list,
  15510. listStack: s.listStack.slice(0),
  15511. quote: s.quote,
  15512. indentedCode: s.indentedCode,
  15513. trailingSpace: s.trailingSpace,
  15514. trailingSpaceNewLine: s.trailingSpaceNewLine,
  15515. md_inside: s.md_inside,
  15516. fencedEndRE: s.fencedEndRE
  15517. };
  15518. },
  15519. token: function(stream, state) {
  15520. // Reset state.formatting
  15521. state.formatting = false;
  15522. if (stream != state.thisLine.stream) {
  15523. state.header = 0;
  15524. state.hr = false;
  15525. if (stream.match(/^\s*$/, true)) {
  15526. blankLine(state);
  15527. return null;
  15528. }
  15529. state.prevLine = state.thisLine
  15530. state.thisLine = {stream: stream}
  15531. // Reset state.taskList
  15532. state.taskList = false;
  15533. // Reset state.trailingSpace
  15534. state.trailingSpace = 0;
  15535. state.trailingSpaceNewLine = false;
  15536. if (!state.localState) {
  15537. state.f = state.block;
  15538. if (state.f != htmlBlock) {
  15539. var indentation = stream.match(/^\s*/, true)[0].replace(/\t/g, expandedTab).length;
  15540. state.indentation = indentation;
  15541. state.indentationDiff = null;
  15542. if (indentation > 0) return null;
  15543. }
  15544. }
  15545. }
  15546. return state.f(stream, state);
  15547. },
  15548. innerMode: function(state) {
  15549. if (state.block == htmlBlock) return {state: state.htmlState, mode: htmlMode};
  15550. if (state.localState) return {state: state.localState, mode: state.localMode};
  15551. return {state: state, mode: mode};
  15552. },
  15553. indent: function(state, textAfter, line) {
  15554. if (state.block == htmlBlock && htmlMode.indent) return htmlMode.indent(state.htmlState, textAfter, line)
  15555. if (state.localState && state.localMode.indent) return state.localMode.indent(state.localState, textAfter, line)
  15556. return CodeMirror.Pass
  15557. },
  15558. blankLine: blankLine,
  15559. getType: getType,
  15560. closeBrackets: "()[]{}''\"\"``",
  15561. fold: "markdown"
  15562. };
  15563. return mode;
  15564. }, "xml");
  15565. CodeMirror.defineMIME("text/x-markdown", "markdown");
  15566. });
  15567. /***/ }),
  15568. /* 45 */
  15569. /***/ (function(module, exports, __webpack_require__) {
  15570. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  15571. // Distributed under an MIT license: http://codemirror.net/LICENSE
  15572. (function(mod) {
  15573. if (true) // CommonJS
  15574. mod(__webpack_require__(40));
  15575. else if (typeof define == "function" && define.amd) // AMD
  15576. define(["../../lib/codemirror"], mod);
  15577. else // Plain browser env
  15578. mod(CodeMirror);
  15579. })(function(CodeMirror) {
  15580. "use strict";
  15581. var htmlConfig = {
  15582. autoSelfClosers: {'area': true, 'base': true, 'br': true, 'col': true, 'command': true,
  15583. 'embed': true, 'frame': true, 'hr': true, 'img': true, 'input': true,
  15584. 'keygen': true, 'link': true, 'meta': true, 'param': true, 'source': true,
  15585. 'track': true, 'wbr': true, 'menuitem': true},
  15586. implicitlyClosed: {'dd': true, 'li': true, 'optgroup': true, 'option': true, 'p': true,
  15587. 'rp': true, 'rt': true, 'tbody': true, 'td': true, 'tfoot': true,
  15588. 'th': true, 'tr': true},
  15589. contextGrabbers: {
  15590. 'dd': {'dd': true, 'dt': true},
  15591. 'dt': {'dd': true, 'dt': true},
  15592. 'li': {'li': true},
  15593. 'option': {'option': true, 'optgroup': true},
  15594. 'optgroup': {'optgroup': true},
  15595. 'p': {'address': true, 'article': true, 'aside': true, 'blockquote': true, 'dir': true,
  15596. 'div': true, 'dl': true, 'fieldset': true, 'footer': true, 'form': true,
  15597. 'h1': true, 'h2': true, 'h3': true, 'h4': true, 'h5': true, 'h6': true,
  15598. 'header': true, 'hgroup': true, 'hr': true, 'menu': true, 'nav': true, 'ol': true,
  15599. 'p': true, 'pre': true, 'section': true, 'table': true, 'ul': true},
  15600. 'rp': {'rp': true, 'rt': true},
  15601. 'rt': {'rp': true, 'rt': true},
  15602. 'tbody': {'tbody': true, 'tfoot': true},
  15603. 'td': {'td': true, 'th': true},
  15604. 'tfoot': {'tbody': true},
  15605. 'th': {'td': true, 'th': true},
  15606. 'thead': {'tbody': true, 'tfoot': true},
  15607. 'tr': {'tr': true}
  15608. },
  15609. doNotIndent: {"pre": true},
  15610. allowUnquoted: true,
  15611. allowMissing: true,
  15612. caseFold: true
  15613. }
  15614. var xmlConfig = {
  15615. autoSelfClosers: {},
  15616. implicitlyClosed: {},
  15617. contextGrabbers: {},
  15618. doNotIndent: {},
  15619. allowUnquoted: false,
  15620. allowMissing: false,
  15621. caseFold: false
  15622. }
  15623. CodeMirror.defineMode("xml", function(editorConf, config_) {
  15624. var indentUnit = editorConf.indentUnit
  15625. var config = {}
  15626. var defaults = config_.htmlMode ? htmlConfig : xmlConfig
  15627. for (var prop in defaults) config[prop] = defaults[prop]
  15628. for (var prop in config_) config[prop] = config_[prop]
  15629. // Return variables for tokenizers
  15630. var type, setStyle;
  15631. function inText(stream, state) {
  15632. function chain(parser) {
  15633. state.tokenize = parser;
  15634. return parser(stream, state);
  15635. }
  15636. var ch = stream.next();
  15637. if (ch == "<") {
  15638. if (stream.eat("!")) {
  15639. if (stream.eat("[")) {
  15640. if (stream.match("CDATA[")) return chain(inBlock("atom", "]]>"));
  15641. else return null;
  15642. } else if (stream.match("--")) {
  15643. return chain(inBlock("comment", "-->"));
  15644. } else if (stream.match("DOCTYPE", true, true)) {
  15645. stream.eatWhile(/[\w\._\-]/);
  15646. return chain(doctype(1));
  15647. } else {
  15648. return null;
  15649. }
  15650. } else if (stream.eat("?")) {
  15651. stream.eatWhile(/[\w\._\-]/);
  15652. state.tokenize = inBlock("meta", "?>");
  15653. return "meta";
  15654. } else {
  15655. type = stream.eat("/") ? "closeTag" : "openTag";
  15656. state.tokenize = inTag;
  15657. return "tag bracket";
  15658. }
  15659. } else if (ch == "&") {
  15660. var ok;
  15661. if (stream.eat("#")) {
  15662. if (stream.eat("x")) {
  15663. ok = stream.eatWhile(/[a-fA-F\d]/) && stream.eat(";");
  15664. } else {
  15665. ok = stream.eatWhile(/[\d]/) && stream.eat(";");
  15666. }
  15667. } else {
  15668. ok = stream.eatWhile(/[\w\.\-:]/) && stream.eat(";");
  15669. }
  15670. return ok ? "atom" : "error";
  15671. } else {
  15672. stream.eatWhile(/[^&<]/);
  15673. return null;
  15674. }
  15675. }
  15676. inText.isInText = true;
  15677. function inTag(stream, state) {
  15678. var ch = stream.next();
  15679. if (ch == ">" || (ch == "/" && stream.eat(">"))) {
  15680. state.tokenize = inText;
  15681. type = ch == ">" ? "endTag" : "selfcloseTag";
  15682. return "tag bracket";
  15683. } else if (ch == "=") {
  15684. type = "equals";
  15685. return null;
  15686. } else if (ch == "<") {
  15687. state.tokenize = inText;
  15688. state.state = baseState;
  15689. state.tagName = state.tagStart = null;
  15690. var next = state.tokenize(stream, state);
  15691. return next ? next + " tag error" : "tag error";
  15692. } else if (/[\'\"]/.test(ch)) {
  15693. state.tokenize = inAttribute(ch);
  15694. state.stringStartCol = stream.column();
  15695. return state.tokenize(stream, state);
  15696. } else {
  15697. stream.match(/^[^\s\u00a0=<>\"\']*[^\s\u00a0=<>\"\'\/]/);
  15698. return "word";
  15699. }
  15700. }
  15701. function inAttribute(quote) {
  15702. var closure = function(stream, state) {
  15703. while (!stream.eol()) {
  15704. if (stream.next() == quote) {
  15705. state.tokenize = inTag;
  15706. break;
  15707. }
  15708. }
  15709. return "string";
  15710. };
  15711. closure.isInAttribute = true;
  15712. return closure;
  15713. }
  15714. function inBlock(style, terminator) {
  15715. return function(stream, state) {
  15716. while (!stream.eol()) {
  15717. if (stream.match(terminator)) {
  15718. state.tokenize = inText;
  15719. break;
  15720. }
  15721. stream.next();
  15722. }
  15723. return style;
  15724. };
  15725. }
  15726. function doctype(depth) {
  15727. return function(stream, state) {
  15728. var ch;
  15729. while ((ch = stream.next()) != null) {
  15730. if (ch == "<") {
  15731. state.tokenize = doctype(depth + 1);
  15732. return state.tokenize(stream, state);
  15733. } else if (ch == ">") {
  15734. if (depth == 1) {
  15735. state.tokenize = inText;
  15736. break;
  15737. } else {
  15738. state.tokenize = doctype(depth - 1);
  15739. return state.tokenize(stream, state);
  15740. }
  15741. }
  15742. }
  15743. return "meta";
  15744. };
  15745. }
  15746. function Context(state, tagName, startOfLine) {
  15747. this.prev = state.context;
  15748. this.tagName = tagName;
  15749. this.indent = state.indented;
  15750. this.startOfLine = startOfLine;
  15751. if (config.doNotIndent.hasOwnProperty(tagName) || (state.context && state.context.noIndent))
  15752. this.noIndent = true;
  15753. }
  15754. function popContext(state) {
  15755. if (state.context) state.context = state.context.prev;
  15756. }
  15757. function maybePopContext(state, nextTagName) {
  15758. var parentTagName;
  15759. while (true) {
  15760. if (!state.context) {
  15761. return;
  15762. }
  15763. parentTagName = state.context.tagName;
  15764. if (!config.contextGrabbers.hasOwnProperty(parentTagName) ||
  15765. !config.contextGrabbers[parentTagName].hasOwnProperty(nextTagName)) {
  15766. return;
  15767. }
  15768. popContext(state);
  15769. }
  15770. }
  15771. function baseState(type, stream, state) {
  15772. if (type == "openTag") {
  15773. state.tagStart = stream.column();
  15774. return tagNameState;
  15775. } else if (type == "closeTag") {
  15776. return closeTagNameState;
  15777. } else {
  15778. return baseState;
  15779. }
  15780. }
  15781. function tagNameState(type, stream, state) {
  15782. if (type == "word") {
  15783. state.tagName = stream.current();
  15784. setStyle = "tag";
  15785. return attrState;
  15786. } else {
  15787. setStyle = "error";
  15788. return tagNameState;
  15789. }
  15790. }
  15791. function closeTagNameState(type, stream, state) {
  15792. if (type == "word") {
  15793. var tagName = stream.current();
  15794. if (state.context && state.context.tagName != tagName &&
  15795. config.implicitlyClosed.hasOwnProperty(state.context.tagName))
  15796. popContext(state);
  15797. if ((state.context && state.context.tagName == tagName) || config.matchClosing === false) {
  15798. setStyle = "tag";
  15799. return closeState;
  15800. } else {
  15801. setStyle = "tag error";
  15802. return closeStateErr;
  15803. }
  15804. } else {
  15805. setStyle = "error";
  15806. return closeStateErr;
  15807. }
  15808. }
  15809. function closeState(type, _stream, state) {
  15810. if (type != "endTag") {
  15811. setStyle = "error";
  15812. return closeState;
  15813. }
  15814. popContext(state);
  15815. return baseState;
  15816. }
  15817. function closeStateErr(type, stream, state) {
  15818. setStyle = "error";
  15819. return closeState(type, stream, state);
  15820. }
  15821. function attrState(type, _stream, state) {
  15822. if (type == "word") {
  15823. setStyle = "attribute";
  15824. return attrEqState;
  15825. } else if (type == "endTag" || type == "selfcloseTag") {
  15826. var tagName = state.tagName, tagStart = state.tagStart;
  15827. state.tagName = state.tagStart = null;
  15828. if (type == "selfcloseTag" ||
  15829. config.autoSelfClosers.hasOwnProperty(tagName)) {
  15830. maybePopContext(state, tagName);
  15831. } else {
  15832. maybePopContext(state, tagName);
  15833. state.context = new Context(state, tagName, tagStart == state.indented);
  15834. }
  15835. return baseState;
  15836. }
  15837. setStyle = "error";
  15838. return attrState;
  15839. }
  15840. function attrEqState(type, stream, state) {
  15841. if (type == "equals") return attrValueState;
  15842. if (!config.allowMissing) setStyle = "error";
  15843. return attrState(type, stream, state);
  15844. }
  15845. function attrValueState(type, stream, state) {
  15846. if (type == "string") return attrContinuedState;
  15847. if (type == "word" && config.allowUnquoted) {setStyle = "string"; return attrState;}
  15848. setStyle = "error";
  15849. return attrState(type, stream, state);
  15850. }
  15851. function attrContinuedState(type, stream, state) {
  15852. if (type == "string") return attrContinuedState;
  15853. return attrState(type, stream, state);
  15854. }
  15855. return {
  15856. startState: function(baseIndent) {
  15857. var state = {tokenize: inText,
  15858. state: baseState,
  15859. indented: baseIndent || 0,
  15860. tagName: null, tagStart: null,
  15861. context: null}
  15862. if (baseIndent != null) state.baseIndent = baseIndent
  15863. return state
  15864. },
  15865. token: function(stream, state) {
  15866. if (!state.tagName && stream.sol())
  15867. state.indented = stream.indentation();
  15868. if (stream.eatSpace()) return null;
  15869. type = null;
  15870. var style = state.tokenize(stream, state);
  15871. if ((style || type) && style != "comment") {
  15872. setStyle = null;
  15873. state.state = state.state(type || style, stream, state);
  15874. if (setStyle)
  15875. style = setStyle == "error" ? style + " error" : setStyle;
  15876. }
  15877. return style;
  15878. },
  15879. indent: function(state, textAfter, fullLine) {
  15880. var context = state.context;
  15881. // Indent multi-line strings (e.g. css).
  15882. if (state.tokenize.isInAttribute) {
  15883. if (state.tagStart == state.indented)
  15884. return state.stringStartCol + 1;
  15885. else
  15886. return state.indented + indentUnit;
  15887. }
  15888. if (context && context.noIndent) return CodeMirror.Pass;
  15889. if (state.tokenize != inTag && state.tokenize != inText)
  15890. return fullLine ? fullLine.match(/^(\s*)/)[0].length : 0;
  15891. // Indent the starts of attribute names.
  15892. if (state.tagName) {
  15893. if (config.multilineTagIndentPastTag !== false)
  15894. return state.tagStart + state.tagName.length + 2;
  15895. else
  15896. return state.tagStart + indentUnit * (config.multilineTagIndentFactor || 1);
  15897. }
  15898. if (config.alignCDATA && /<!\[CDATA\[/.test(textAfter)) return 0;
  15899. var tagAfter = textAfter && /^<(\/)?([\w_:\.-]*)/.exec(textAfter);
  15900. if (tagAfter && tagAfter[1]) { // Closing tag spotted
  15901. while (context) {
  15902. if (context.tagName == tagAfter[2]) {
  15903. context = context.prev;
  15904. break;
  15905. } else if (config.implicitlyClosed.hasOwnProperty(context.tagName)) {
  15906. context = context.prev;
  15907. } else {
  15908. break;
  15909. }
  15910. }
  15911. } else if (tagAfter) { // Opening tag spotted
  15912. while (context) {
  15913. var grabbers = config.contextGrabbers[context.tagName];
  15914. if (grabbers && grabbers.hasOwnProperty(tagAfter[2]))
  15915. context = context.prev;
  15916. else
  15917. break;
  15918. }
  15919. }
  15920. while (context && context.prev && !context.startOfLine)
  15921. context = context.prev;
  15922. if (context) return context.indent + indentUnit;
  15923. else return state.baseIndent || 0;
  15924. },
  15925. electricInput: /<\/[\s\w:]+>$/,
  15926. blockCommentStart: "<!--",
  15927. blockCommentEnd: "-->",
  15928. configuration: config.htmlMode ? "html" : "xml",
  15929. helperType: config.htmlMode ? "html" : "xml",
  15930. skipAttribute: function(state) {
  15931. if (state.state == attrValueState)
  15932. state.state = attrState
  15933. }
  15934. };
  15935. });
  15936. CodeMirror.defineMIME("text/xml", "xml");
  15937. CodeMirror.defineMIME("application/xml", "xml");
  15938. if (!CodeMirror.mimeModes.hasOwnProperty("text/html"))
  15939. CodeMirror.defineMIME("text/html", {name: "xml", htmlMode: true});
  15940. });
  15941. /***/ }),
  15942. /* 46 */
  15943. /***/ (function(module, exports, __webpack_require__) {
  15944. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  15945. // Distributed under an MIT license: http://codemirror.net/LICENSE
  15946. (function(mod) {
  15947. if (true) // CommonJS
  15948. mod(__webpack_require__(40));
  15949. else if (typeof define == "function" && define.amd) // AMD
  15950. define(["../lib/codemirror"], mod);
  15951. else // Plain browser env
  15952. mod(CodeMirror);
  15953. })(function(CodeMirror) {
  15954. "use strict";
  15955. CodeMirror.modeInfo = [
  15956. {name: "APL", mime: "text/apl", mode: "apl", ext: ["dyalog", "apl"]},
  15957. {name: "PGP", mimes: ["application/pgp", "application/pgp-encrypted", "application/pgp-keys", "application/pgp-signature"], mode: "asciiarmor", ext: ["asc", "pgp", "sig"]},
  15958. {name: "ASN.1", mime: "text/x-ttcn-asn", mode: "asn.1", ext: ["asn", "asn1"]},
  15959. {name: "Asterisk", mime: "text/x-asterisk", mode: "asterisk", file: /^extensions\.conf$/i},
  15960. {name: "Brainfuck", mime: "text/x-brainfuck", mode: "brainfuck", ext: ["b", "bf"]},
  15961. {name: "C", mime: "text/x-csrc", mode: "clike", ext: ["c", "h"]},
  15962. {name: "C++", mime: "text/x-c++src", mode: "clike", ext: ["cpp", "c++", "cc", "cxx", "hpp", "h++", "hh", "hxx"], alias: ["cpp"]},
  15963. {name: "Cobol", mime: "text/x-cobol", mode: "cobol", ext: ["cob", "cpy"]},
  15964. {name: "C#", mime: "text/x-csharp", mode: "clike", ext: ["cs"], alias: ["csharp"]},
  15965. {name: "Clojure", mime: "text/x-clojure", mode: "clojure", ext: ["clj", "cljc", "cljx"]},
  15966. {name: "ClojureScript", mime: "text/x-clojurescript", mode: "clojure", ext: ["cljs"]},
  15967. {name: "Closure Stylesheets (GSS)", mime: "text/x-gss", mode: "css", ext: ["gss"]},
  15968. {name: "CMake", mime: "text/x-cmake", mode: "cmake", ext: ["cmake", "cmake.in"], file: /^CMakeLists.txt$/},
  15969. {name: "CoffeeScript", mimes: ["application/vnd.coffeescript", "text/coffeescript", "text/x-coffeescript"], mode: "coffeescript", ext: ["coffee"], alias: ["coffee", "coffee-script"]},
  15970. {name: "Common Lisp", mime: "text/x-common-lisp", mode: "commonlisp", ext: ["cl", "lisp", "el"], alias: ["lisp"]},
  15971. {name: "Cypher", mime: "application/x-cypher-query", mode: "cypher", ext: ["cyp", "cypher"]},
  15972. {name: "Cython", mime: "text/x-cython", mode: "python", ext: ["pyx", "pxd", "pxi"]},
  15973. {name: "Crystal", mime: "text/x-crystal", mode: "crystal", ext: ["cr"]},
  15974. {name: "CSS", mime: "text/css", mode: "css", ext: ["css"]},
  15975. {name: "CQL", mime: "text/x-cassandra", mode: "sql", ext: ["cql"]},
  15976. {name: "D", mime: "text/x-d", mode: "d", ext: ["d"]},
  15977. {name: "Dart", mimes: ["application/dart", "text/x-dart"], mode: "dart", ext: ["dart"]},
  15978. {name: "diff", mime: "text/x-diff", mode: "diff", ext: ["diff", "patch"]},
  15979. {name: "Django", mime: "text/x-django", mode: "django"},
  15980. {name: "Dockerfile", mime: "text/x-dockerfile", mode: "dockerfile", file: /^Dockerfile$/},
  15981. {name: "DTD", mime: "application/xml-dtd", mode: "dtd", ext: ["dtd"]},
  15982. {name: "Dylan", mime: "text/x-dylan", mode: "dylan", ext: ["dylan", "dyl", "intr"]},
  15983. {name: "EBNF", mime: "text/x-ebnf", mode: "ebnf"},
  15984. {name: "ECL", mime: "text/x-ecl", mode: "ecl", ext: ["ecl"]},
  15985. {name: "edn", mime: "application/edn", mode: "clojure", ext: ["edn"]},
  15986. {name: "Eiffel", mime: "text/x-eiffel", mode: "eiffel", ext: ["e"]},
  15987. {name: "Elm", mime: "text/x-elm", mode: "elm", ext: ["elm"]},
  15988. {name: "Embedded Javascript", mime: "application/x-ejs", mode: "htmlembedded", ext: ["ejs"]},
  15989. {name: "Embedded Ruby", mime: "application/x-erb", mode: "htmlembedded", ext: ["erb"]},
  15990. {name: "Erlang", mime: "text/x-erlang", mode: "erlang", ext: ["erl"]},
  15991. {name: "Esper", mime: "text/x-esper", mode: "sql"},
  15992. {name: "Factor", mime: "text/x-factor", mode: "factor", ext: ["factor"]},
  15993. {name: "FCL", mime: "text/x-fcl", mode: "fcl"},
  15994. {name: "Forth", mime: "text/x-forth", mode: "forth", ext: ["forth", "fth", "4th"]},
  15995. {name: "Fortran", mime: "text/x-fortran", mode: "fortran", ext: ["f", "for", "f77", "f90"]},
  15996. {name: "F#", mime: "text/x-fsharp", mode: "mllike", ext: ["fs"], alias: ["fsharp"]},
  15997. {name: "Gas", mime: "text/x-gas", mode: "gas", ext: ["s"]},
  15998. {name: "Gherkin", mime: "text/x-feature", mode: "gherkin", ext: ["feature"]},
  15999. {name: "GitHub Flavored Markdown", mime: "text/x-gfm", mode: "gfm", file: /^(readme|contributing|history).md$/i},
  16000. {name: "Go", mime: "text/x-go", mode: "go", ext: ["go"]},
  16001. {name: "Groovy", mime: "text/x-groovy", mode: "groovy", ext: ["groovy", "gradle"], file: /^Jenkinsfile$/},
  16002. {name: "HAML", mime: "text/x-haml", mode: "haml", ext: ["haml"]},
  16003. {name: "Haskell", mime: "text/x-haskell", mode: "haskell", ext: ["hs"]},
  16004. {name: "Haskell (Literate)", mime: "text/x-literate-haskell", mode: "haskell-literate", ext: ["lhs"]},
  16005. {name: "Haxe", mime: "text/x-haxe", mode: "haxe", ext: ["hx"]},
  16006. {name: "HXML", mime: "text/x-hxml", mode: "haxe", ext: ["hxml"]},
  16007. {name: "ASP.NET", mime: "application/x-aspx", mode: "htmlembedded", ext: ["aspx"], alias: ["asp", "aspx"]},
  16008. {name: "HTML", mime: "text/html", mode: "htmlmixed", ext: ["html", "htm"], alias: ["xhtml"]},
  16009. {name: "HTTP", mime: "message/http", mode: "http"},
  16010. {name: "IDL", mime: "text/x-idl", mode: "idl", ext: ["pro"]},
  16011. {name: "Pug", mime: "text/x-pug", mode: "pug", ext: ["jade", "pug"], alias: ["jade"]},
  16012. {name: "Java", mime: "text/x-java", mode: "clike", ext: ["java"]},
  16013. {name: "Java Server Pages", mime: "application/x-jsp", mode: "htmlembedded", ext: ["jsp"], alias: ["jsp"]},
  16014. {name: "JavaScript", mimes: ["text/javascript", "text/ecmascript", "application/javascript", "application/x-javascript", "application/ecmascript"],
  16015. mode: "javascript", ext: ["js"], alias: ["ecmascript", "js", "node"]},
  16016. {name: "JSON", mimes: ["application/json", "application/x-json"], mode: "javascript", ext: ["json", "map"], alias: ["json5"]},
  16017. {name: "JSON-LD", mime: "application/ld+json", mode: "javascript", ext: ["jsonld"], alias: ["jsonld"]},
  16018. {name: "JSX", mime: "text/jsx", mode: "jsx", ext: ["jsx"]},
  16019. {name: "Jinja2", mime: "null", mode: "jinja2"},
  16020. {name: "Julia", mime: "text/x-julia", mode: "julia", ext: ["jl"]},
  16021. {name: "Kotlin", mime: "text/x-kotlin", mode: "clike", ext: ["kt"]},
  16022. {name: "LESS", mime: "text/x-less", mode: "css", ext: ["less"]},
  16023. {name: "LiveScript", mime: "text/x-livescript", mode: "livescript", ext: ["ls"], alias: ["ls"]},
  16024. {name: "Lua", mime: "text/x-lua", mode: "lua", ext: ["lua"]},
  16025. {name: "Markdown", mime: "text/x-markdown", mode: "markdown", ext: ["markdown", "md", "mkd"]},
  16026. {name: "mIRC", mime: "text/mirc", mode: "mirc"},
  16027. {name: "MariaDB SQL", mime: "text/x-mariadb", mode: "sql"},
  16028. {name: "Mathematica", mime: "text/x-mathematica", mode: "mathematica", ext: ["m", "nb"]},
  16029. {name: "Modelica", mime: "text/x-modelica", mode: "modelica", ext: ["mo"]},
  16030. {name: "MUMPS", mime: "text/x-mumps", mode: "mumps", ext: ["mps"]},
  16031. {name: "MS SQL", mime: "text/x-mssql", mode: "sql"},
  16032. {name: "mbox", mime: "application/mbox", mode: "mbox", ext: ["mbox"]},
  16033. {name: "MySQL", mime: "text/x-mysql", mode: "sql"},
  16034. {name: "Nginx", mime: "text/x-nginx-conf", mode: "nginx", file: /nginx.*\.conf$/i},
  16035. {name: "NSIS", mime: "text/x-nsis", mode: "nsis", ext: ["nsh", "nsi"]},
  16036. {name: "NTriples", mimes: ["application/n-triples", "application/n-quads", "text/n-triples"],
  16037. mode: "ntriples", ext: ["nt", "nq"]},
  16038. {name: "Objective C", mime: "text/x-objectivec", mode: "clike", ext: ["m", "mm"], alias: ["objective-c", "objc"]},
  16039. {name: "OCaml", mime: "text/x-ocaml", mode: "mllike", ext: ["ml", "mli", "mll", "mly"]},
  16040. {name: "Octave", mime: "text/x-octave", mode: "octave", ext: ["m"]},
  16041. {name: "Oz", mime: "text/x-oz", mode: "oz", ext: ["oz"]},
  16042. {name: "Pascal", mime: "text/x-pascal", mode: "pascal", ext: ["p", "pas"]},
  16043. {name: "PEG.js", mime: "null", mode: "pegjs", ext: ["jsonld"]},
  16044. {name: "Perl", mime: "text/x-perl", mode: "perl", ext: ["pl", "pm"]},
  16045. {name: "PHP", mime: ["application/x-httpd-php", "text/x-php"], mode: "php", ext: ["php", "php3", "php4", "php5", "php7", "phtml"]},
  16046. {name: "Pig", mime: "text/x-pig", mode: "pig", ext: ["pig"]},
  16047. {name: "Plain Text", mime: "text/plain", mode: "null", ext: ["txt", "text", "conf", "def", "list", "log"]},
  16048. {name: "PLSQL", mime: "text/x-plsql", mode: "sql", ext: ["pls"]},
  16049. {name: "PowerShell", mime: "application/x-powershell", mode: "powershell", ext: ["ps1", "psd1", "psm1"]},
  16050. {name: "Properties files", mime: "text/x-properties", mode: "properties", ext: ["properties", "ini", "in"], alias: ["ini", "properties"]},
  16051. {name: "ProtoBuf", mime: "text/x-protobuf", mode: "protobuf", ext: ["proto"]},
  16052. {name: "Python", mime: "text/x-python", mode: "python", ext: ["BUILD", "bzl", "py", "pyw"], file: /^(BUCK|BUILD)$/},
  16053. {name: "Puppet", mime: "text/x-puppet", mode: "puppet", ext: ["pp"]},
  16054. {name: "Q", mime: "text/x-q", mode: "q", ext: ["q"]},
  16055. {name: "R", mime: "text/x-rsrc", mode: "r", ext: ["r", "R"], alias: ["rscript"]},
  16056. {name: "reStructuredText", mime: "text/x-rst", mode: "rst", ext: ["rst"], alias: ["rst"]},
  16057. {name: "RPM Changes", mime: "text/x-rpm-changes", mode: "rpm"},
  16058. {name: "RPM Spec", mime: "text/x-rpm-spec", mode: "rpm", ext: ["spec"]},
  16059. {name: "Ruby", mime: "text/x-ruby", mode: "ruby", ext: ["rb"], alias: ["jruby", "macruby", "rake", "rb", "rbx"]},
  16060. {name: "Rust", mime: "text/x-rustsrc", mode: "rust", ext: ["rs"]},
  16061. {name: "SAS", mime: "text/x-sas", mode: "sas", ext: ["sas"]},
  16062. {name: "Sass", mime: "text/x-sass", mode: "sass", ext: ["sass"]},
  16063. {name: "Scala", mime: "text/x-scala", mode: "clike", ext: ["scala"]},
  16064. {name: "Scheme", mime: "text/x-scheme", mode: "scheme", ext: ["scm", "ss"]},
  16065. {name: "SCSS", mime: "text/x-scss", mode: "css", ext: ["scss"]},
  16066. {name: "Shell", mimes: ["text/x-sh", "application/x-sh"], mode: "shell", ext: ["sh", "ksh", "bash"], alias: ["bash", "sh", "zsh"], file: /^PKGBUILD$/},
  16067. {name: "Sieve", mime: "application/sieve", mode: "sieve", ext: ["siv", "sieve"]},
  16068. {name: "Slim", mimes: ["text/x-slim", "application/x-slim"], mode: "slim", ext: ["slim"]},
  16069. {name: "Smalltalk", mime: "text/x-stsrc", mode: "smalltalk", ext: ["st"]},
  16070. {name: "Smarty", mime: "text/x-smarty", mode: "smarty", ext: ["tpl"]},
  16071. {name: "Solr", mime: "text/x-solr", mode: "solr"},
  16072. {name: "Soy", mime: "text/x-soy", mode: "soy", ext: ["soy"], alias: ["closure template"]},
  16073. {name: "SPARQL", mime: "application/sparql-query", mode: "sparql", ext: ["rq", "sparql"], alias: ["sparul"]},
  16074. {name: "Spreadsheet", mime: "text/x-spreadsheet", mode: "spreadsheet", alias: ["excel", "formula"]},
  16075. {name: "SQL", mime: "text/x-sql", mode: "sql", ext: ["sql"]},
  16076. {name: "SQLite", mime: "text/x-sqlite", mode: "sql"},
  16077. {name: "Squirrel", mime: "text/x-squirrel", mode: "clike", ext: ["nut"]},
  16078. {name: "Stylus", mime: "text/x-styl", mode: "stylus", ext: ["styl"]},
  16079. {name: "Swift", mime: "text/x-swift", mode: "swift", ext: ["swift"]},
  16080. {name: "sTeX", mime: "text/x-stex", mode: "stex"},
  16081. {name: "LaTeX", mime: "text/x-latex", mode: "stex", ext: ["text", "ltx"], alias: ["tex"]},
  16082. {name: "SystemVerilog", mime: "text/x-systemverilog", mode: "verilog", ext: ["v", "sv", "svh"]},
  16083. {name: "Tcl", mime: "text/x-tcl", mode: "tcl", ext: ["tcl"]},
  16084. {name: "Textile", mime: "text/x-textile", mode: "textile", ext: ["textile"]},
  16085. {name: "TiddlyWiki ", mime: "text/x-tiddlywiki", mode: "tiddlywiki"},
  16086. {name: "Tiki wiki", mime: "text/tiki", mode: "tiki"},
  16087. {name: "TOML", mime: "text/x-toml", mode: "toml", ext: ["toml"]},
  16088. {name: "Tornado", mime: "text/x-tornado", mode: "tornado"},
  16089. {name: "troff", mime: "text/troff", mode: "troff", ext: ["1", "2", "3", "4", "5", "6", "7", "8", "9"]},
  16090. {name: "TTCN", mime: "text/x-ttcn", mode: "ttcn", ext: ["ttcn", "ttcn3", "ttcnpp"]},
  16091. {name: "TTCN_CFG", mime: "text/x-ttcn-cfg", mode: "ttcn-cfg", ext: ["cfg"]},
  16092. {name: "Turtle", mime: "text/turtle", mode: "turtle", ext: ["ttl"]},
  16093. {name: "TypeScript", mime: "application/typescript", mode: "javascript", ext: ["ts"], alias: ["ts"]},
  16094. {name: "TypeScript-JSX", mime: "text/typescript-jsx", mode: "jsx", ext: ["tsx"], alias: ["tsx"]},
  16095. {name: "Twig", mime: "text/x-twig", mode: "twig"},
  16096. {name: "Web IDL", mime: "text/x-webidl", mode: "webidl", ext: ["webidl"]},
  16097. {name: "VB.NET", mime: "text/x-vb", mode: "vb", ext: ["vb"]},
  16098. {name: "VBScript", mime: "text/vbscript", mode: "vbscript", ext: ["vbs"]},
  16099. {name: "Velocity", mime: "text/velocity", mode: "velocity", ext: ["vtl"]},
  16100. {name: "Verilog", mime: "text/x-verilog", mode: "verilog", ext: ["v"]},
  16101. {name: "VHDL", mime: "text/x-vhdl", mode: "vhdl", ext: ["vhd", "vhdl"]},
  16102. {name: "Vue.js Component", mimes: ["script/x-vue", "text/x-vue"], mode: "vue", ext: ["vue"]},
  16103. {name: "XML", mimes: ["application/xml", "text/xml"], mode: "xml", ext: ["xml", "xsl", "xsd", "svg"], alias: ["rss", "wsdl", "xsd"]},
  16104. {name: "XQuery", mime: "application/xquery", mode: "xquery", ext: ["xy", "xquery"]},
  16105. {name: "Yacas", mime: "text/x-yacas", mode: "yacas", ext: ["ys"]},
  16106. {name: "YAML", mimes: ["text/x-yaml", "text/yaml"], mode: "yaml", ext: ["yaml", "yml"], alias: ["yml"]},
  16107. {name: "Z80", mime: "text/x-z80", mode: "z80", ext: ["z80"]},
  16108. {name: "mscgen", mime: "text/x-mscgen", mode: "mscgen", ext: ["mscgen", "mscin", "msc"]},
  16109. {name: "xu", mime: "text/x-xu", mode: "mscgen", ext: ["xu"]},
  16110. {name: "msgenny", mime: "text/x-msgenny", mode: "mscgen", ext: ["msgenny"]}
  16111. ];
  16112. // Ensure all modes have a mime property for backwards compatibility
  16113. for (var i = 0; i < CodeMirror.modeInfo.length; i++) {
  16114. var info = CodeMirror.modeInfo[i];
  16115. if (info.mimes) info.mime = info.mimes[0];
  16116. }
  16117. CodeMirror.findModeByMIME = function(mime) {
  16118. mime = mime.toLowerCase();
  16119. for (var i = 0; i < CodeMirror.modeInfo.length; i++) {
  16120. var info = CodeMirror.modeInfo[i];
  16121. if (info.mime == mime) return info;
  16122. if (info.mimes) for (var j = 0; j < info.mimes.length; j++)
  16123. if (info.mimes[j] == mime) return info;
  16124. }
  16125. if (/\+xml$/.test(mime)) return CodeMirror.findModeByMIME("application/xml")
  16126. if (/\+json$/.test(mime)) return CodeMirror.findModeByMIME("application/json")
  16127. };
  16128. CodeMirror.findModeByExtension = function(ext) {
  16129. for (var i = 0; i < CodeMirror.modeInfo.length; i++) {
  16130. var info = CodeMirror.modeInfo[i];
  16131. if (info.ext) for (var j = 0; j < info.ext.length; j++)
  16132. if (info.ext[j] == ext) return info;
  16133. }
  16134. };
  16135. CodeMirror.findModeByFileName = function(filename) {
  16136. for (var i = 0; i < CodeMirror.modeInfo.length; i++) {
  16137. var info = CodeMirror.modeInfo[i];
  16138. if (info.file && info.file.test(filename)) return info;
  16139. }
  16140. var dot = filename.lastIndexOf(".");
  16141. var ext = dot > -1 && filename.substring(dot + 1, filename.length);
  16142. if (ext) return CodeMirror.findModeByExtension(ext);
  16143. };
  16144. CodeMirror.findModeByName = function(name) {
  16145. name = name.toLowerCase();
  16146. for (var i = 0; i < CodeMirror.modeInfo.length; i++) {
  16147. var info = CodeMirror.modeInfo[i];
  16148. if (info.name.toLowerCase() == name) return info;
  16149. if (info.alias) for (var j = 0; j < info.alias.length; j++)
  16150. if (info.alias[j].toLowerCase() == name) return info;
  16151. }
  16152. };
  16153. });
  16154. /***/ }),
  16155. /* 47 */
  16156. /***/ (function(module, exports, __webpack_require__) {
  16157. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  16158. // Distributed under an MIT license: http://codemirror.net/LICENSE
  16159. // Utility function that allows modes to be combined. The mode given
  16160. // as the base argument takes care of most of the normal mode
  16161. // functionality, but a second (typically simple) mode is used, which
  16162. // can override the style of text. Both modes get to parse all of the
  16163. // text, but when both assign a non-null style to a piece of code, the
  16164. // overlay wins, unless the combine argument was true and not overridden,
  16165. // or state.overlay.combineTokens was true, in which case the styles are
  16166. // combined.
  16167. (function(mod) {
  16168. if (true) // CommonJS
  16169. mod(__webpack_require__(40));
  16170. else if (typeof define == "function" && define.amd) // AMD
  16171. define(["../../lib/codemirror"], mod);
  16172. else // Plain browser env
  16173. mod(CodeMirror);
  16174. })(function(CodeMirror) {
  16175. "use strict";
  16176. CodeMirror.overlayMode = function(base, overlay, combine) {
  16177. return {
  16178. startState: function() {
  16179. return {
  16180. base: CodeMirror.startState(base),
  16181. overlay: CodeMirror.startState(overlay),
  16182. basePos: 0, baseCur: null,
  16183. overlayPos: 0, overlayCur: null,
  16184. streamSeen: null
  16185. };
  16186. },
  16187. copyState: function(state) {
  16188. return {
  16189. base: CodeMirror.copyState(base, state.base),
  16190. overlay: CodeMirror.copyState(overlay, state.overlay),
  16191. basePos: state.basePos, baseCur: null,
  16192. overlayPos: state.overlayPos, overlayCur: null
  16193. };
  16194. },
  16195. token: function(stream, state) {
  16196. if (stream != state.streamSeen ||
  16197. Math.min(state.basePos, state.overlayPos) < stream.start) {
  16198. state.streamSeen = stream;
  16199. state.basePos = state.overlayPos = stream.start;
  16200. }
  16201. if (stream.start == state.basePos) {
  16202. state.baseCur = base.token(stream, state.base);
  16203. state.basePos = stream.pos;
  16204. }
  16205. if (stream.start == state.overlayPos) {
  16206. stream.pos = stream.start;
  16207. state.overlayCur = overlay.token(stream, state.overlay);
  16208. state.overlayPos = stream.pos;
  16209. }
  16210. stream.pos = Math.min(state.basePos, state.overlayPos);
  16211. // state.overlay.combineTokens always takes precedence over combine,
  16212. // unless set to null
  16213. if (state.overlayCur == null) return state.baseCur;
  16214. else if (state.baseCur != null &&
  16215. state.overlay.combineTokens ||
  16216. combine && state.overlay.combineTokens == null)
  16217. return state.baseCur + " " + state.overlayCur;
  16218. else return state.overlayCur;
  16219. },
  16220. indent: base.indent && function(state, textAfter) {
  16221. return base.indent(state.base, textAfter);
  16222. },
  16223. electricChars: base.electricChars,
  16224. innerMode: function(state) { return {state: state.base, mode: base}; },
  16225. blankLine: function(state) {
  16226. var baseToken, overlayToken;
  16227. if (base.blankLine) baseToken = base.blankLine(state.base);
  16228. if (overlay.blankLine) overlayToken = overlay.blankLine(state.overlay);
  16229. return overlayToken == null ?
  16230. baseToken :
  16231. (combine && baseToken != null ? baseToken + " " + overlayToken : overlayToken);
  16232. }
  16233. };
  16234. };
  16235. });
  16236. /***/ }),
  16237. /* 48 */
  16238. /***/ (function(module, exports, __webpack_require__) {
  16239. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  16240. // Distributed under an MIT license: http://codemirror.net/LICENSE
  16241. (function(mod) {
  16242. if (true) // CommonJS
  16243. mod(__webpack_require__(40));
  16244. else if (typeof define == "function" && define.amd) // AMD
  16245. define(["../../lib/codemirror"], mod);
  16246. else // Plain browser env
  16247. mod(CodeMirror);
  16248. })(function(CodeMirror) {
  16249. CodeMirror.defineOption("placeholder", "", function(cm, val, old) {
  16250. var prev = old && old != CodeMirror.Init;
  16251. if (val && !prev) {
  16252. cm.on("blur", onBlur);
  16253. cm.on("change", onChange);
  16254. cm.on("swapDoc", onChange);
  16255. onChange(cm);
  16256. } else if (!val && prev) {
  16257. cm.off("blur", onBlur);
  16258. cm.off("change", onChange);
  16259. cm.off("swapDoc", onChange);
  16260. clearPlaceholder(cm);
  16261. var wrapper = cm.getWrapperElement();
  16262. wrapper.className = wrapper.className.replace(" CodeMirror-empty", "");
  16263. }
  16264. if (val && !cm.hasFocus()) onBlur(cm);
  16265. });
  16266. function clearPlaceholder(cm) {
  16267. if (cm.state.placeholder) {
  16268. cm.state.placeholder.parentNode.removeChild(cm.state.placeholder);
  16269. cm.state.placeholder = null;
  16270. }
  16271. }
  16272. function setPlaceholder(cm) {
  16273. clearPlaceholder(cm);
  16274. var elt = cm.state.placeholder = document.createElement("pre");
  16275. elt.style.cssText = "height: 0; overflow: visible";
  16276. elt.className = "CodeMirror-placeholder";
  16277. var placeHolder = cm.getOption("placeholder")
  16278. if (typeof placeHolder == "string") placeHolder = document.createTextNode(placeHolder)
  16279. elt.appendChild(placeHolder)
  16280. cm.display.lineSpace.insertBefore(elt, cm.display.lineSpace.firstChild);
  16281. }
  16282. function onBlur(cm) {
  16283. if (isEmpty(cm)) setPlaceholder(cm);
  16284. }
  16285. function onChange(cm) {
  16286. var wrapper = cm.getWrapperElement(), empty = isEmpty(cm);
  16287. wrapper.className = wrapper.className.replace(" CodeMirror-empty", "") + (empty ? " CodeMirror-empty" : "");
  16288. if (empty) setPlaceholder(cm);
  16289. else clearPlaceholder(cm);
  16290. }
  16291. function isEmpty(cm) {
  16292. return (cm.lineCount() === 1) && (cm.getLine(0) === "");
  16293. }
  16294. });
  16295. /***/ }),
  16296. /* 49 */
  16297. /***/ (function(module, exports, __webpack_require__) {
  16298. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  16299. // Distributed under an MIT license: http://codemirror.net/LICENSE
  16300. // Because sometimes you need to mark the selected *text*.
  16301. //
  16302. // Adds an option 'styleSelectedText' which, when enabled, gives
  16303. // selected text the CSS class given as option value, or
  16304. // "CodeMirror-selectedtext" when the value is not a string.
  16305. (function(mod) {
  16306. if (true) // CommonJS
  16307. mod(__webpack_require__(40));
  16308. else if (typeof define == "function" && define.amd) // AMD
  16309. define(["../../lib/codemirror"], mod);
  16310. else // Plain browser env
  16311. mod(CodeMirror);
  16312. })(function(CodeMirror) {
  16313. "use strict";
  16314. CodeMirror.defineOption("styleSelectedText", false, function(cm, val, old) {
  16315. var prev = old && old != CodeMirror.Init;
  16316. if (val && !prev) {
  16317. cm.state.markedSelection = [];
  16318. cm.state.markedSelectionStyle = typeof val == "string" ? val : "CodeMirror-selectedtext";
  16319. reset(cm);
  16320. cm.on("cursorActivity", onCursorActivity);
  16321. cm.on("change", onChange);
  16322. } else if (!val && prev) {
  16323. cm.off("cursorActivity", onCursorActivity);
  16324. cm.off("change", onChange);
  16325. clear(cm);
  16326. cm.state.markedSelection = cm.state.markedSelectionStyle = null;
  16327. }
  16328. });
  16329. function onCursorActivity(cm) {
  16330. if (cm.state.markedSelection)
  16331. cm.operation(function() { update(cm); });
  16332. }
  16333. function onChange(cm) {
  16334. if (cm.state.markedSelection && cm.state.markedSelection.length)
  16335. cm.operation(function() { clear(cm); });
  16336. }
  16337. var CHUNK_SIZE = 8;
  16338. var Pos = CodeMirror.Pos;
  16339. var cmp = CodeMirror.cmpPos;
  16340. function coverRange(cm, from, to, addAt) {
  16341. if (cmp(from, to) == 0) return;
  16342. var array = cm.state.markedSelection;
  16343. var cls = cm.state.markedSelectionStyle;
  16344. for (var line = from.line;;) {
  16345. var start = line == from.line ? from : Pos(line, 0);
  16346. var endLine = line + CHUNK_SIZE, atEnd = endLine >= to.line;
  16347. var end = atEnd ? to : Pos(endLine, 0);
  16348. var mark = cm.markText(start, end, {className: cls});
  16349. if (addAt == null) array.push(mark);
  16350. else array.splice(addAt++, 0, mark);
  16351. if (atEnd) break;
  16352. line = endLine;
  16353. }
  16354. }
  16355. function clear(cm) {
  16356. var array = cm.state.markedSelection;
  16357. for (var i = 0; i < array.length; ++i) array[i].clear();
  16358. array.length = 0;
  16359. }
  16360. function reset(cm) {
  16361. clear(cm);
  16362. var ranges = cm.listSelections();
  16363. for (var i = 0; i < ranges.length; i++)
  16364. coverRange(cm, ranges[i].from(), ranges[i].to());
  16365. }
  16366. function update(cm) {
  16367. if (!cm.somethingSelected()) return clear(cm);
  16368. if (cm.listSelections().length > 1) return reset(cm);
  16369. var from = cm.getCursor("start"), to = cm.getCursor("end");
  16370. var array = cm.state.markedSelection;
  16371. if (!array.length) return coverRange(cm, from, to);
  16372. var coverStart = array[0].find(), coverEnd = array[array.length - 1].find();
  16373. if (!coverStart || !coverEnd || to.line - from.line <= CHUNK_SIZE ||
  16374. cmp(from, coverEnd.to) >= 0 || cmp(to, coverStart.from) <= 0)
  16375. return reset(cm);
  16376. while (cmp(from, coverStart.from) > 0) {
  16377. array.shift().clear();
  16378. coverStart = array[0].find();
  16379. }
  16380. if (cmp(from, coverStart.from) < 0) {
  16381. if (coverStart.to.line - from.line < CHUNK_SIZE) {
  16382. array.shift().clear();
  16383. coverRange(cm, from, coverStart.to, 0);
  16384. } else {
  16385. coverRange(cm, from, coverStart.from, 0);
  16386. }
  16387. }
  16388. while (cmp(to, coverEnd.to) < 0) {
  16389. array.pop().clear();
  16390. coverEnd = array[array.length - 1].find();
  16391. }
  16392. if (cmp(to, coverEnd.to) > 0) {
  16393. if (to.line - coverEnd.from.line < CHUNK_SIZE) {
  16394. array.pop().clear();
  16395. coverRange(cm, coverEnd.from, to);
  16396. } else {
  16397. coverRange(cm, coverEnd.to, to);
  16398. }
  16399. }
  16400. }
  16401. });
  16402. /***/ }),
  16403. /* 50 */
  16404. /***/ (function(module, exports, __webpack_require__) {
  16405. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  16406. // Distributed under an MIT license: http://codemirror.net/LICENSE
  16407. (function(mod) {
  16408. if (true) // CommonJS
  16409. mod(__webpack_require__(40), __webpack_require__(44), __webpack_require__(47));
  16410. else if (typeof define == "function" && define.amd) // AMD
  16411. define(["../../lib/codemirror", "../markdown/markdown", "../../addon/mode/overlay"], mod);
  16412. else // Plain browser env
  16413. mod(CodeMirror);
  16414. })(function(CodeMirror) {
  16415. "use strict";
  16416. 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
  16417. CodeMirror.defineMode("gfm", function(config, modeConfig) {
  16418. var codeDepth = 0;
  16419. function blankLine(state) {
  16420. state.code = false;
  16421. return null;
  16422. }
  16423. var gfmOverlay = {
  16424. startState: function() {
  16425. return {
  16426. code: false,
  16427. codeBlock: false,
  16428. ateSpace: false
  16429. };
  16430. },
  16431. copyState: function(s) {
  16432. return {
  16433. code: s.code,
  16434. codeBlock: s.codeBlock,
  16435. ateSpace: s.ateSpace
  16436. };
  16437. },
  16438. token: function(stream, state) {
  16439. state.combineTokens = null;
  16440. // Hack to prevent formatting override inside code blocks (block and inline)
  16441. if (state.codeBlock) {
  16442. if (stream.match(/^```+/)) {
  16443. state.codeBlock = false;
  16444. return null;
  16445. }
  16446. stream.skipToEnd();
  16447. return null;
  16448. }
  16449. if (stream.sol()) {
  16450. state.code = false;
  16451. }
  16452. if (stream.sol() && stream.match(/^```+/)) {
  16453. stream.skipToEnd();
  16454. state.codeBlock = true;
  16455. return null;
  16456. }
  16457. // If this block is changed, it may need to be updated in Markdown mode
  16458. if (stream.peek() === '`') {
  16459. stream.next();
  16460. var before = stream.pos;
  16461. stream.eatWhile('`');
  16462. var difference = 1 + stream.pos - before;
  16463. if (!state.code) {
  16464. codeDepth = difference;
  16465. state.code = true;
  16466. } else {
  16467. if (difference === codeDepth) { // Must be exact
  16468. state.code = false;
  16469. }
  16470. }
  16471. return null;
  16472. } else if (state.code) {
  16473. stream.next();
  16474. return null;
  16475. }
  16476. // Check if space. If so, links can be formatted later on
  16477. if (stream.eatSpace()) {
  16478. state.ateSpace = true;
  16479. return null;
  16480. }
  16481. if (stream.sol() || state.ateSpace) {
  16482. state.ateSpace = false;
  16483. if (modeConfig.gitHubSpice !== false) {
  16484. if(stream.match(/^(?:[a-zA-Z0-9\-_]+\/)?(?:[a-zA-Z0-9\-_]+@)?(?=.{0,6}\d)(?:[a-f0-9]{7,40}\b)/)) {
  16485. // User/Project@SHA
  16486. // User@SHA
  16487. // SHA
  16488. state.combineTokens = true;
  16489. return "link";
  16490. } else if (stream.match(/^(?:[a-zA-Z0-9\-_]+\/)?(?:[a-zA-Z0-9\-_]+)?#[0-9]+\b/)) {
  16491. // User/Project#Num
  16492. // User#Num
  16493. // #Num
  16494. state.combineTokens = true;
  16495. return "link";
  16496. }
  16497. }
  16498. }
  16499. if (stream.match(urlRE) &&
  16500. stream.string.slice(stream.start - 2, stream.start) != "](" &&
  16501. (stream.start == 0 || /\W/.test(stream.string.charAt(stream.start - 1)))) {
  16502. // URLs
  16503. // Taken from http://daringfireball.net/2010/07/improved_regex_for_matching_urls
  16504. // And then (issue #1160) simplified to make it not crash the Chrome Regexp engine
  16505. // And then limited url schemes to the CommonMark list, so foo:bar isn't matched as a URL
  16506. state.combineTokens = true;
  16507. return "link";
  16508. }
  16509. stream.next();
  16510. return null;
  16511. },
  16512. blankLine: blankLine
  16513. };
  16514. var markdownConfig = {
  16515. taskLists: true,
  16516. strikethrough: true,
  16517. emoji: true
  16518. };
  16519. for (var attr in modeConfig) {
  16520. markdownConfig[attr] = modeConfig[attr];
  16521. }
  16522. markdownConfig.name = "markdown";
  16523. return CodeMirror.overlayMode(CodeMirror.getMode(config, markdownConfig), gfmOverlay);
  16524. }, "markdown");
  16525. CodeMirror.defineMIME("text/x-gfm", "gfm");
  16526. });
  16527. /***/ }),
  16528. /* 51 */
  16529. /***/ (function(module, exports, __webpack_require__) {
  16530. // Use strict mode (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode)
  16531. "use strict";
  16532. // Requires
  16533. var Typo = __webpack_require__(52);
  16534. // Create function
  16535. function CodeMirrorSpellChecker(options) {
  16536. // Initialize
  16537. options = options || {};
  16538. // Verify
  16539. if(typeof options.codeMirrorInstance !== "function" || typeof options.codeMirrorInstance.defineMode !== "function") {
  16540. console.log("CodeMirror Spell Checker: You must provide an instance of CodeMirror via the option `codeMirrorInstance`");
  16541. return;
  16542. }
  16543. // Because some browsers don't support this functionality yet
  16544. if(!String.prototype.includes) {
  16545. String.prototype.includes = function() {
  16546. "use strict";
  16547. return String.prototype.indexOf.apply(this, arguments) !== -1;
  16548. };
  16549. }
  16550. // Define the new mode
  16551. options.codeMirrorInstance.defineMode("spell-checker", function(config) {
  16552. // Load AFF/DIC data
  16553. if(!CodeMirrorSpellChecker.aff_loading) {
  16554. CodeMirrorSpellChecker.aff_loading = true;
  16555. var xhr_aff = new XMLHttpRequest();
  16556. xhr_aff.open("GET", "https://cdn.jsdelivr.net/codemirror.spell-checker/latest/en_US.aff", true);
  16557. xhr_aff.onload = function() {
  16558. if(xhr_aff.readyState === 4 && xhr_aff.status === 200) {
  16559. CodeMirrorSpellChecker.aff_data = xhr_aff.responseText;
  16560. CodeMirrorSpellChecker.num_loaded++;
  16561. if(CodeMirrorSpellChecker.num_loaded == 2) {
  16562. CodeMirrorSpellChecker.typo = new Typo("en_US", CodeMirrorSpellChecker.aff_data, CodeMirrorSpellChecker.dic_data, {
  16563. platform: "any"
  16564. });
  16565. }
  16566. }
  16567. };
  16568. xhr_aff.send(null);
  16569. }
  16570. if(!CodeMirrorSpellChecker.dic_loading) {
  16571. CodeMirrorSpellChecker.dic_loading = true;
  16572. var xhr_dic = new XMLHttpRequest();
  16573. xhr_dic.open("GET", "https://cdn.jsdelivr.net/codemirror.spell-checker/latest/en_US.dic", true);
  16574. xhr_dic.onload = function() {
  16575. if(xhr_dic.readyState === 4 && xhr_dic.status === 200) {
  16576. CodeMirrorSpellChecker.dic_data = xhr_dic.responseText;
  16577. CodeMirrorSpellChecker.num_loaded++;
  16578. if(CodeMirrorSpellChecker.num_loaded == 2) {
  16579. CodeMirrorSpellChecker.typo = new Typo("en_US", CodeMirrorSpellChecker.aff_data, CodeMirrorSpellChecker.dic_data, {
  16580. platform: "any"
  16581. });
  16582. }
  16583. }
  16584. };
  16585. xhr_dic.send(null);
  16586. }
  16587. // Define what separates a word
  16588. var rx_word = "!\"#$%&()*+,-./:;<=>?@[\\]^_`{|}~ ";
  16589. // Create the overlay and such
  16590. var overlay = {
  16591. token: function(stream) {
  16592. var ch = stream.peek();
  16593. var word = "";
  16594. if(rx_word.includes(ch)) {
  16595. stream.next();
  16596. return null;
  16597. }
  16598. while((ch = stream.peek()) != null && !rx_word.includes(ch)) {
  16599. word += ch;
  16600. stream.next();
  16601. }
  16602. if(CodeMirrorSpellChecker.typo && !CodeMirrorSpellChecker.typo.check(word))
  16603. return "spell-error"; // CSS class: cm-spell-error
  16604. return null;
  16605. }
  16606. };
  16607. var mode = options.codeMirrorInstance.getMode(
  16608. config, config.backdrop || "text/plain"
  16609. );
  16610. return options.codeMirrorInstance.overlayMode(mode, overlay, true);
  16611. });
  16612. }
  16613. // Initialize data globally to reduce memory consumption
  16614. CodeMirrorSpellChecker.num_loaded = 0;
  16615. CodeMirrorSpellChecker.aff_loading = false;
  16616. CodeMirrorSpellChecker.dic_loading = false;
  16617. CodeMirrorSpellChecker.aff_data = "";
  16618. CodeMirrorSpellChecker.dic_data = "";
  16619. CodeMirrorSpellChecker.typo;
  16620. // Export
  16621. module.exports = CodeMirrorSpellChecker;
  16622. /***/ }),
  16623. /* 52 */
  16624. /***/ (function(module, exports, __webpack_require__) {
  16625. /* WEBPACK VAR INJECTION */(function(__dirname, Buffer) {/* globals chrome: false */
  16626. /* globals __dirname: false */
  16627. /* globals require: false */
  16628. /* globals Buffer: false */
  16629. /* globals module: false */
  16630. /**
  16631. * Typo is a JavaScript implementation of a spellchecker using hunspell-style
  16632. * dictionaries.
  16633. */
  16634. var Typo;
  16635. (function () {
  16636. "use strict";
  16637. /**
  16638. * Typo constructor.
  16639. *
  16640. * @param {String} [dictionary] The locale code of the dictionary being used. e.g.,
  16641. * "en_US". This is only used to auto-load dictionaries.
  16642. * @param {String} [affData] The data from the dictionary's .aff file. If omitted
  16643. * and Typo.js is being used in a Chrome extension, the .aff
  16644. * file will be loaded automatically from
  16645. * lib/typo/dictionaries/[dictionary]/[dictionary].aff
  16646. * In other environments, it will be loaded from
  16647. * [settings.dictionaryPath]/dictionaries/[dictionary]/[dictionary].aff
  16648. * @param {String} [wordsData] The data from the dictionary's .dic file. If omitted
  16649. * and Typo.js is being used in a Chrome extension, the .dic
  16650. * file will be loaded automatically from
  16651. * lib/typo/dictionaries/[dictionary]/[dictionary].dic
  16652. * In other environments, it will be loaded from
  16653. * [settings.dictionaryPath]/dictionaries/[dictionary]/[dictionary].dic
  16654. * @param {Object} [settings] Constructor settings. Available properties are:
  16655. * {String} [dictionaryPath]: path to load dictionary from in non-chrome
  16656. * environment.
  16657. * {Object} [flags]: flag information.
  16658. * {Boolean} [asyncLoad]: If true, affData and wordsData will be loaded
  16659. * asynchronously.
  16660. * {Function} [loadedCallback]: Called when both affData and wordsData
  16661. * have been loaded. Only used if asyncLoad is set to true. The parameter
  16662. * is the instantiated Typo object.
  16663. *
  16664. * @returns {Typo} A Typo object.
  16665. */
  16666. Typo = function (dictionary, affData, wordsData, settings) {
  16667. settings = settings || {};
  16668. this.dictionary = null;
  16669. this.rules = {};
  16670. this.dictionaryTable = {};
  16671. this.compoundRules = [];
  16672. this.compoundRuleCodes = {};
  16673. this.replacementTable = [];
  16674. this.flags = settings.flags || {};
  16675. this.memoized = {};
  16676. this.loaded = false;
  16677. var self = this;
  16678. var path;
  16679. // Loop-control variables.
  16680. var i, j, _len, _jlen;
  16681. if (dictionary) {
  16682. self.dictionary = dictionary;
  16683. // If the data is preloaded, just setup the Typo object.
  16684. if (affData && wordsData) {
  16685. setup();
  16686. }
  16687. // Loading data for Chrome extentions.
  16688. else if (typeof window !== 'undefined' && 'chrome' in window && 'extension' in window.chrome && 'getURL' in window.chrome.extension) {
  16689. if (settings.dictionaryPath) {
  16690. path = settings.dictionaryPath;
  16691. }
  16692. else {
  16693. path = "typo/dictionaries";
  16694. }
  16695. if (!affData) readDataFile(chrome.extension.getURL(path + "/" + dictionary + "/" + dictionary + ".aff"), setAffData);
  16696. if (!wordsData) readDataFile(chrome.extension.getURL(path + "/" + dictionary + "/" + dictionary + ".dic"), setWordsData);
  16697. }
  16698. else {
  16699. if (settings.dictionaryPath) {
  16700. path = settings.dictionaryPath;
  16701. }
  16702. else if (true) {
  16703. path = __dirname + '/dictionaries';
  16704. }
  16705. else {
  16706. path = './dictionaries';
  16707. }
  16708. if (!affData) readDataFile(path + "/" + dictionary + "/" + dictionary + ".aff", setAffData);
  16709. if (!wordsData) readDataFile(path + "/" + dictionary + "/" + dictionary + ".dic", setWordsData);
  16710. }
  16711. }
  16712. function readDataFile(url, setFunc) {
  16713. var response = self._readFile(url, null, settings.asyncLoad);
  16714. if (settings.asyncLoad) {
  16715. response.then(function(data) {
  16716. setFunc(data);
  16717. });
  16718. }
  16719. else {
  16720. setFunc(response);
  16721. }
  16722. }
  16723. function setAffData(data) {
  16724. affData = data;
  16725. if (wordsData) {
  16726. setup();
  16727. }
  16728. }
  16729. function setWordsData(data) {
  16730. wordsData = data;
  16731. if (affData) {
  16732. setup();
  16733. }
  16734. }
  16735. function setup() {
  16736. self.rules = self._parseAFF(affData);
  16737. // Save the rule codes that are used in compound rules.
  16738. self.compoundRuleCodes = {};
  16739. for (i = 0, _len = self.compoundRules.length; i < _len; i++) {
  16740. var rule = self.compoundRules[i];
  16741. for (j = 0, _jlen = rule.length; j < _jlen; j++) {
  16742. self.compoundRuleCodes[rule[j]] = [];
  16743. }
  16744. }
  16745. // If we add this ONLYINCOMPOUND flag to self.compoundRuleCodes, then _parseDIC
  16746. // will do the work of saving the list of words that are compound-only.
  16747. if ("ONLYINCOMPOUND" in self.flags) {
  16748. self.compoundRuleCodes[self.flags.ONLYINCOMPOUND] = [];
  16749. }
  16750. self.dictionaryTable = self._parseDIC(wordsData);
  16751. // Get rid of any codes from the compound rule codes that are never used
  16752. // (or that were special regex characters). Not especially necessary...
  16753. for (i in self.compoundRuleCodes) {
  16754. if (self.compoundRuleCodes[i].length === 0) {
  16755. delete self.compoundRuleCodes[i];
  16756. }
  16757. }
  16758. // Build the full regular expressions for each compound rule.
  16759. // I have a feeling (but no confirmation yet) that this method of
  16760. // testing for compound words is probably slow.
  16761. for (i = 0, _len = self.compoundRules.length; i < _len; i++) {
  16762. var ruleText = self.compoundRules[i];
  16763. var expressionText = "";
  16764. for (j = 0, _jlen = ruleText.length; j < _jlen; j++) {
  16765. var character = ruleText[j];
  16766. if (character in self.compoundRuleCodes) {
  16767. expressionText += "(" + self.compoundRuleCodes[character].join("|") + ")";
  16768. }
  16769. else {
  16770. expressionText += character;
  16771. }
  16772. }
  16773. self.compoundRules[i] = new RegExp(expressionText, "i");
  16774. }
  16775. self.loaded = true;
  16776. if (settings.asyncLoad && settings.loadedCallback) {
  16777. settings.loadedCallback(self);
  16778. }
  16779. }
  16780. return this;
  16781. };
  16782. Typo.prototype = {
  16783. /**
  16784. * Loads a Typo instance from a hash of all of the Typo properties.
  16785. *
  16786. * @param object obj A hash of Typo properties, probably gotten from a JSON.parse(JSON.stringify(typo_instance)).
  16787. */
  16788. load : function (obj) {
  16789. for (var i in obj) {
  16790. if (obj.hasOwnProperty(i)) {
  16791. this[i] = obj[i];
  16792. }
  16793. }
  16794. return this;
  16795. },
  16796. /**
  16797. * Read the contents of a file.
  16798. *
  16799. * @param {String} path The path (relative) to the file.
  16800. * @param {String} [charset="ISO8859-1"] The expected charset of the file
  16801. * @param {Boolean} async If true, the file will be read asynchronously. For node.js this does nothing, all
  16802. * files are read synchronously.
  16803. * @returns {String} The file data if async is false, otherwise a promise object. If running node.js, the data is
  16804. * always returned.
  16805. */
  16806. _readFile : function (path, charset, async) {
  16807. charset = charset || "utf8";
  16808. if (typeof XMLHttpRequest !== 'undefined') {
  16809. var promise;
  16810. var req = new XMLHttpRequest();
  16811. req.open("GET", path, async);
  16812. if (async) {
  16813. promise = new Promise(function(resolve, reject) {
  16814. req.onload = function() {
  16815. if (req.status === 200) {
  16816. resolve(req.responseText);
  16817. }
  16818. else {
  16819. reject(req.statusText);
  16820. }
  16821. };
  16822. req.onerror = function() {
  16823. reject(req.statusText);
  16824. }
  16825. });
  16826. }
  16827. if (req.overrideMimeType)
  16828. req.overrideMimeType("text/plain; charset=" + charset);
  16829. req.send(null);
  16830. return async ? promise : req.responseText;
  16831. }
  16832. else if (true) {
  16833. // Node.js
  16834. var fs = __webpack_require__(57);
  16835. try {
  16836. if (fs.existsSync(path)) {
  16837. var stats = fs.statSync(path);
  16838. var fileDescriptor = fs.openSync(path, 'r');
  16839. var buffer = new Buffer(stats.size);
  16840. fs.readSync(fileDescriptor, buffer, 0, buffer.length, null);
  16841. return buffer.toString(charset, 0, buffer.length);
  16842. }
  16843. else {
  16844. console.log("Path " + path + " does not exist.");
  16845. }
  16846. } catch (e) {
  16847. console.log(e);
  16848. return '';
  16849. }
  16850. }
  16851. },
  16852. /**
  16853. * Parse the rules out from a .aff file.
  16854. *
  16855. * @param {String} data The contents of the affix file.
  16856. * @returns object The rules from the file.
  16857. */
  16858. _parseAFF : function (data) {
  16859. var rules = {};
  16860. var line, subline, numEntries, lineParts;
  16861. var i, j, _len, _jlen;
  16862. // Remove comment lines
  16863. data = this._removeAffixComments(data);
  16864. var lines = data.split("\n");
  16865. for (i = 0, _len = lines.length; i < _len; i++) {
  16866. line = lines[i];
  16867. var definitionParts = line.split(/\s+/);
  16868. var ruleType = definitionParts[0];
  16869. if (ruleType == "PFX" || ruleType == "SFX") {
  16870. var ruleCode = definitionParts[1];
  16871. var combineable = definitionParts[2];
  16872. numEntries = parseInt(definitionParts[3], 10);
  16873. var entries = [];
  16874. for (j = i + 1, _jlen = i + 1 + numEntries; j < _jlen; j++) {
  16875. subline = lines[j];
  16876. lineParts = subline.split(/\s+/);
  16877. var charactersToRemove = lineParts[2];
  16878. var additionParts = lineParts[3].split("/");
  16879. var charactersToAdd = additionParts[0];
  16880. if (charactersToAdd === "0") charactersToAdd = "";
  16881. var continuationClasses = this.parseRuleCodes(additionParts[1]);
  16882. var regexToMatch = lineParts[4];
  16883. var entry = {};
  16884. entry.add = charactersToAdd;
  16885. if (continuationClasses.length > 0) entry.continuationClasses = continuationClasses;
  16886. if (regexToMatch !== ".") {
  16887. if (ruleType === "SFX") {
  16888. entry.match = new RegExp(regexToMatch + "$");
  16889. }
  16890. else {
  16891. entry.match = new RegExp("^" + regexToMatch);
  16892. }
  16893. }
  16894. if (charactersToRemove != "0") {
  16895. if (ruleType === "SFX") {
  16896. entry.remove = new RegExp(charactersToRemove + "$");
  16897. }
  16898. else {
  16899. entry.remove = charactersToRemove;
  16900. }
  16901. }
  16902. entries.push(entry);
  16903. }
  16904. rules[ruleCode] = { "type" : ruleType, "combineable" : (combineable == "Y"), "entries" : entries };
  16905. i += numEntries;
  16906. }
  16907. else if (ruleType === "COMPOUNDRULE") {
  16908. numEntries = parseInt(definitionParts[1], 10);
  16909. for (j = i + 1, _jlen = i + 1 + numEntries; j < _jlen; j++) {
  16910. line = lines[j];
  16911. lineParts = line.split(/\s+/);
  16912. this.compoundRules.push(lineParts[1]);
  16913. }
  16914. i += numEntries;
  16915. }
  16916. else if (ruleType === "REP") {
  16917. lineParts = line.split(/\s+/);
  16918. if (lineParts.length === 3) {
  16919. this.replacementTable.push([ lineParts[1], lineParts[2] ]);
  16920. }
  16921. }
  16922. else {
  16923. // ONLYINCOMPOUND
  16924. // COMPOUNDMIN
  16925. // FLAG
  16926. // KEEPCASE
  16927. // NEEDAFFIX
  16928. this.flags[ruleType] = definitionParts[1];
  16929. }
  16930. }
  16931. return rules;
  16932. },
  16933. /**
  16934. * Removes comment lines and then cleans up blank lines and trailing whitespace.
  16935. *
  16936. * @param {String} data The data from an affix file.
  16937. * @return {String} The cleaned-up data.
  16938. */
  16939. _removeAffixComments : function (data) {
  16940. // Remove comments
  16941. // This used to remove any string starting with '#' up to the end of the line,
  16942. // but some COMPOUNDRULE definitions include '#' as part of the rule.
  16943. // I haven't seen any affix files that use comments on the same line as real data,
  16944. // so I don't think this will break anything.
  16945. data = data.replace(/^\s*#.*$/mg, "");
  16946. // Trim each line
  16947. data = data.replace(/^\s\s*/m, '').replace(/\s\s*$/m, '');
  16948. // Remove blank lines.
  16949. data = data.replace(/\n{2,}/g, "\n");
  16950. // Trim the entire string
  16951. data = data.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
  16952. return data;
  16953. },
  16954. /**
  16955. * Parses the words out from the .dic file.
  16956. *
  16957. * @param {String} data The data from the dictionary file.
  16958. * @returns object The lookup table containing all of the words and
  16959. * word forms from the dictionary.
  16960. */
  16961. _parseDIC : function (data) {
  16962. data = this._removeDicComments(data);
  16963. var lines = data.split("\n");
  16964. var dictionaryTable = {};
  16965. function addWord(word, rules) {
  16966. // Some dictionaries will list the same word multiple times with different rule sets.
  16967. if (!dictionaryTable.hasOwnProperty(word)) {
  16968. dictionaryTable[word] = null;
  16969. }
  16970. if (rules.length > 0) {
  16971. if (dictionaryTable[word] === null) {
  16972. dictionaryTable[word] = [];
  16973. }
  16974. dictionaryTable[word].push(rules);
  16975. }
  16976. }
  16977. // The first line is the number of words in the dictionary.
  16978. for (var i = 1, _len = lines.length; i < _len; i++) {
  16979. var line = lines[i];
  16980. var parts = line.split("/", 2);
  16981. var word = parts[0];
  16982. // Now for each affix rule, generate that form of the word.
  16983. if (parts.length > 1) {
  16984. var ruleCodesArray = this.parseRuleCodes(parts[1]);
  16985. // Save the ruleCodes for compound word situations.
  16986. if (!("NEEDAFFIX" in this.flags) || ruleCodesArray.indexOf(this.flags.NEEDAFFIX) == -1) {
  16987. addWord(word, ruleCodesArray);
  16988. }
  16989. for (var j = 0, _jlen = ruleCodesArray.length; j < _jlen; j++) {
  16990. var code = ruleCodesArray[j];
  16991. var rule = this.rules[code];
  16992. if (rule) {
  16993. var newWords = this._applyRule(word, rule);
  16994. for (var ii = 0, _iilen = newWords.length; ii < _iilen; ii++) {
  16995. var newWord = newWords[ii];
  16996. addWord(newWord, []);
  16997. if (rule.combineable) {
  16998. for (var k = j + 1; k < _jlen; k++) {
  16999. var combineCode = ruleCodesArray[k];
  17000. var combineRule = this.rules[combineCode];
  17001. if (combineRule) {
  17002. if (combineRule.combineable && (rule.type != combineRule.type)) {
  17003. var otherNewWords = this._applyRule(newWord, combineRule);
  17004. for (var iii = 0, _iiilen = otherNewWords.length; iii < _iiilen; iii++) {
  17005. var otherNewWord = otherNewWords[iii];
  17006. addWord(otherNewWord, []);
  17007. }
  17008. }
  17009. }
  17010. }
  17011. }
  17012. }
  17013. }
  17014. if (code in this.compoundRuleCodes) {
  17015. this.compoundRuleCodes[code].push(word);
  17016. }
  17017. }
  17018. }
  17019. else {
  17020. addWord(word.trim(), []);
  17021. }
  17022. }
  17023. return dictionaryTable;
  17024. },
  17025. /**
  17026. * Removes comment lines and then cleans up blank lines and trailing whitespace.
  17027. *
  17028. * @param {String} data The data from a .dic file.
  17029. * @return {String} The cleaned-up data.
  17030. */
  17031. _removeDicComments : function (data) {
  17032. // I can't find any official documentation on it, but at least the de_DE
  17033. // dictionary uses tab-indented lines as comments.
  17034. // Remove comments
  17035. data = data.replace(/^\t.*$/mg, "");
  17036. return data;
  17037. },
  17038. parseRuleCodes : function (textCodes) {
  17039. if (!textCodes) {
  17040. return [];
  17041. }
  17042. else if (!("FLAG" in this.flags)) {
  17043. return textCodes.split("");
  17044. }
  17045. else if (this.flags.FLAG === "long") {
  17046. var flags = [];
  17047. for (var i = 0, _len = textCodes.length; i < _len; i += 2) {
  17048. flags.push(textCodes.substr(i, 2));
  17049. }
  17050. return flags;
  17051. }
  17052. else if (this.flags.FLAG === "num") {
  17053. return textCodes.split(",");
  17054. }
  17055. },
  17056. /**
  17057. * Applies an affix rule to a word.
  17058. *
  17059. * @param {String} word The base word.
  17060. * @param {Object} rule The affix rule.
  17061. * @returns {String[]} The new words generated by the rule.
  17062. */
  17063. _applyRule : function (word, rule) {
  17064. var entries = rule.entries;
  17065. var newWords = [];
  17066. for (var i = 0, _len = entries.length; i < _len; i++) {
  17067. var entry = entries[i];
  17068. if (!entry.match || word.match(entry.match)) {
  17069. var newWord = word;
  17070. if (entry.remove) {
  17071. newWord = newWord.replace(entry.remove, "");
  17072. }
  17073. if (rule.type === "SFX") {
  17074. newWord = newWord + entry.add;
  17075. }
  17076. else {
  17077. newWord = entry.add + newWord;
  17078. }
  17079. newWords.push(newWord);
  17080. if ("continuationClasses" in entry) {
  17081. for (var j = 0, _jlen = entry.continuationClasses.length; j < _jlen; j++) {
  17082. var continuationRule = this.rules[entry.continuationClasses[j]];
  17083. if (continuationRule) {
  17084. newWords = newWords.concat(this._applyRule(newWord, continuationRule));
  17085. }
  17086. /*
  17087. else {
  17088. // This shouldn't happen, but it does, at least in the de_DE dictionary.
  17089. // I think the author mistakenly supplied lower-case rule codes instead
  17090. // of upper-case.
  17091. }
  17092. */
  17093. }
  17094. }
  17095. }
  17096. }
  17097. return newWords;
  17098. },
  17099. /**
  17100. * Checks whether a word or a capitalization variant exists in the current dictionary.
  17101. * The word is trimmed and several variations of capitalizations are checked.
  17102. * If you want to check a word without any changes made to it, call checkExact()
  17103. *
  17104. * @see http://blog.stevenlevithan.com/archives/faster-trim-javascript re:trimming function
  17105. *
  17106. * @param {String} aWord The word to check.
  17107. * @returns {Boolean}
  17108. */
  17109. check : function (aWord) {
  17110. if (!this.loaded) {
  17111. throw "Dictionary not loaded.";
  17112. }
  17113. // Remove leading and trailing whitespace
  17114. var trimmedWord = aWord.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
  17115. if (this.checkExact(trimmedWord)) {
  17116. return true;
  17117. }
  17118. // The exact word is not in the dictionary.
  17119. if (trimmedWord.toUpperCase() === trimmedWord) {
  17120. // The word was supplied in all uppercase.
  17121. // Check for a capitalized form of the word.
  17122. var capitalizedWord = trimmedWord[0] + trimmedWord.substring(1).toLowerCase();
  17123. if (this.hasFlag(capitalizedWord, "KEEPCASE")) {
  17124. // Capitalization variants are not allowed for this word.
  17125. return false;
  17126. }
  17127. if (this.checkExact(capitalizedWord)) {
  17128. return true;
  17129. }
  17130. }
  17131. var lowercaseWord = trimmedWord.toLowerCase();
  17132. if (lowercaseWord !== trimmedWord) {
  17133. if (this.hasFlag(lowercaseWord, "KEEPCASE")) {
  17134. // Capitalization variants are not allowed for this word.
  17135. return false;
  17136. }
  17137. // Check for a lowercase form
  17138. if (this.checkExact(lowercaseWord)) {
  17139. return true;
  17140. }
  17141. }
  17142. return false;
  17143. },
  17144. /**
  17145. * Checks whether a word exists in the current dictionary.
  17146. *
  17147. * @param {String} word The word to check.
  17148. * @returns {Boolean}
  17149. */
  17150. checkExact : function (word) {
  17151. if (!this.loaded) {
  17152. throw "Dictionary not loaded.";
  17153. }
  17154. var ruleCodes = this.dictionaryTable[word];
  17155. var i, _len;
  17156. if (typeof ruleCodes === 'undefined') {
  17157. // Check if this might be a compound word.
  17158. if ("COMPOUNDMIN" in this.flags && word.length >= this.flags.COMPOUNDMIN) {
  17159. for (i = 0, _len = this.compoundRules.length; i < _len; i++) {
  17160. if (word.match(this.compoundRules[i])) {
  17161. return true;
  17162. }
  17163. }
  17164. }
  17165. }
  17166. else if (ruleCodes === null) {
  17167. // a null (but not undefined) value for an entry in the dictionary table
  17168. // means that the word is in the dictionary but has no flags.
  17169. return true;
  17170. }
  17171. else if (typeof ruleCodes === 'object') { // this.dictionary['hasOwnProperty'] will be a function.
  17172. for (i = 0, _len = ruleCodes.length; i < _len; i++) {
  17173. if (!this.hasFlag(word, "ONLYINCOMPOUND", ruleCodes[i])) {
  17174. return true;
  17175. }
  17176. }
  17177. }
  17178. return false;
  17179. },
  17180. /**
  17181. * Looks up whether a given word is flagged with a given flag.
  17182. *
  17183. * @param {String} word The word in question.
  17184. * @param {String} flag The flag in question.
  17185. * @return {Boolean}
  17186. */
  17187. hasFlag : function (word, flag, wordFlags) {
  17188. if (!this.loaded) {
  17189. throw "Dictionary not loaded.";
  17190. }
  17191. if (flag in this.flags) {
  17192. if (typeof wordFlags === 'undefined') {
  17193. wordFlags = Array.prototype.concat.apply([], this.dictionaryTable[word]);
  17194. }
  17195. if (wordFlags && wordFlags.indexOf(this.flags[flag]) !== -1) {
  17196. return true;
  17197. }
  17198. }
  17199. return false;
  17200. },
  17201. /**
  17202. * Returns a list of suggestions for a misspelled word.
  17203. *
  17204. * @see http://www.norvig.com/spell-correct.html for the basis of this suggestor.
  17205. * This suggestor is primitive, but it works.
  17206. *
  17207. * @param {String} word The misspelling.
  17208. * @param {Number} [limit=5] The maximum number of suggestions to return.
  17209. * @returns {String[]} The array of suggestions.
  17210. */
  17211. alphabet : "",
  17212. suggest : function (word, limit) {
  17213. if (!this.loaded) {
  17214. throw "Dictionary not loaded.";
  17215. }
  17216. limit = limit || 5;
  17217. if (this.memoized.hasOwnProperty(word)) {
  17218. var memoizedLimit = this.memoized[word]['limit'];
  17219. // Only return the cached list if it's big enough or if there weren't enough suggestions
  17220. // to fill a smaller limit.
  17221. if (limit <= memoizedLimit || this.memoized[word]['suggestions'].length < memoizedLimit) {
  17222. return this.memoized[word]['suggestions'].slice(0, limit);
  17223. }
  17224. }
  17225. if (this.check(word)) return [];
  17226. // Check the replacement table.
  17227. for (var i = 0, _len = this.replacementTable.length; i < _len; i++) {
  17228. var replacementEntry = this.replacementTable[i];
  17229. if (word.indexOf(replacementEntry[0]) !== -1) {
  17230. var correctedWord = word.replace(replacementEntry[0], replacementEntry[1]);
  17231. if (this.check(correctedWord)) {
  17232. return [ correctedWord ];
  17233. }
  17234. }
  17235. }
  17236. var self = this;
  17237. self.alphabet = "abcdefghijklmnopqrstuvwxyz";
  17238. /*
  17239. if (!self.alphabet) {
  17240. // Use the alphabet as implicitly defined by the words in the dictionary.
  17241. var alphaHash = {};
  17242. for (var i in self.dictionaryTable) {
  17243. for (var j = 0, _len = i.length; j < _len; j++) {
  17244. alphaHash[i[j]] = true;
  17245. }
  17246. }
  17247. for (var i in alphaHash) {
  17248. self.alphabet += i;
  17249. }
  17250. var alphaArray = self.alphabet.split("");
  17251. alphaArray.sort();
  17252. self.alphabet = alphaArray.join("");
  17253. }
  17254. */
  17255. function edits1(words) {
  17256. var rv = [];
  17257. var ii, i, j, _iilen, _len, _jlen;
  17258. for (ii = 0, _iilen = words.length; ii < _iilen; ii++) {
  17259. var word = words[ii];
  17260. for (i = 0, _len = word.length + 1; i < _len; i++) {
  17261. var s = [ word.substring(0, i), word.substring(i) ];
  17262. if (s[1]) {
  17263. rv.push(s[0] + s[1].substring(1));
  17264. }
  17265. // Eliminate transpositions of identical letters
  17266. if (s[1].length > 1 && s[1][1] !== s[1][0]) {
  17267. rv.push(s[0] + s[1][1] + s[1][0] + s[1].substring(2));
  17268. }
  17269. if (s[1]) {
  17270. for (j = 0, _jlen = self.alphabet.length; j < _jlen; j++) {
  17271. // Eliminate replacement of a letter by itself
  17272. if (self.alphabet[j] != s[1].substring(0,1)){
  17273. rv.push(s[0] + self.alphabet[j] + s[1].substring(1));
  17274. }
  17275. }
  17276. }
  17277. if (s[1]) {
  17278. for (j = 0, _jlen = self.alphabet.length; j < _jlen; j++) {
  17279. rv.push(s[0] + self.alphabet[j] + s[1]);
  17280. }
  17281. }
  17282. }
  17283. }
  17284. return rv;
  17285. }
  17286. function known(words) {
  17287. var rv = [];
  17288. for (var i = 0, _len = words.length; i < _len; i++) {
  17289. if (self.check(words[i])) {
  17290. rv.push(words[i]);
  17291. }
  17292. }
  17293. return rv;
  17294. }
  17295. function correct(word) {
  17296. // Get the edit-distance-1 and edit-distance-2 forms of this word.
  17297. var ed1 = edits1([word]);
  17298. var ed2 = edits1(ed1);
  17299. var corrections = known(ed1.concat(ed2));
  17300. var i, _len;
  17301. // Sort the edits based on how many different ways they were created.
  17302. var weighted_corrections = {};
  17303. for (i = 0, _len = corrections.length; i < _len; i++) {
  17304. if (!(corrections[i] in weighted_corrections)) {
  17305. weighted_corrections[corrections[i]] = 1;
  17306. }
  17307. else {
  17308. weighted_corrections[corrections[i]] += 1;
  17309. }
  17310. }
  17311. var sorted_corrections = [];
  17312. for (i in weighted_corrections) {
  17313. if (weighted_corrections.hasOwnProperty(i)) {
  17314. sorted_corrections.push([ i, weighted_corrections[i] ]);
  17315. }
  17316. }
  17317. function sorter(a, b) {
  17318. if (a[1] < b[1]) {
  17319. return -1;
  17320. }
  17321. return 1;
  17322. }
  17323. sorted_corrections.sort(sorter).reverse();
  17324. var rv = [];
  17325. var capitalization_scheme = "lowercase";
  17326. if (word.toUpperCase() === word) {
  17327. capitalization_scheme = "uppercase";
  17328. }
  17329. else if (word.substr(0, 1).toUpperCase() + word.substr(1).toLowerCase() === word) {
  17330. capitalization_scheme = "capitalized";
  17331. }
  17332. for (i = 0, _len = Math.min(limit, sorted_corrections.length); i < _len; i++) {
  17333. if ("uppercase" === capitalization_scheme) {
  17334. sorted_corrections[i][0] = sorted_corrections[i][0].toUpperCase();
  17335. }
  17336. else if ("capitalized" === capitalization_scheme) {
  17337. sorted_corrections[i][0] = sorted_corrections[i][0].substr(0, 1).toUpperCase() + sorted_corrections[i][0].substr(1);
  17338. }
  17339. if (!self.hasFlag(sorted_corrections[i][0], "NOSUGGEST")) {
  17340. rv.push(sorted_corrections[i][0]);
  17341. }
  17342. }
  17343. return rv;
  17344. }
  17345. this.memoized[word] = {
  17346. 'suggestions': correct(word),
  17347. 'limit': limit
  17348. };
  17349. return this.memoized[word]['suggestions'];
  17350. }
  17351. };
  17352. })();
  17353. // Support for use as a node.js module.
  17354. if (true) {
  17355. module.exports = Typo;
  17356. }
  17357. /* WEBPACK VAR INJECTION */}.call(exports, "/", __webpack_require__(53).Buffer))
  17358. /***/ }),
  17359. /* 53 */
  17360. /***/ (function(module, exports, __webpack_require__) {
  17361. /* WEBPACK VAR INJECTION */(function(global) {/*!
  17362. * The buffer module from node.js, for the browser.
  17363. *
  17364. * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
  17365. * @license MIT
  17366. */
  17367. /* eslint-disable no-proto */
  17368. 'use strict'
  17369. var base64 = __webpack_require__(54)
  17370. var ieee754 = __webpack_require__(55)
  17371. var isArray = __webpack_require__(56)
  17372. exports.Buffer = Buffer
  17373. exports.SlowBuffer = SlowBuffer
  17374. exports.INSPECT_MAX_BYTES = 50
  17375. /**
  17376. * If `Buffer.TYPED_ARRAY_SUPPORT`:
  17377. * === true Use Uint8Array implementation (fastest)
  17378. * === false Use Object implementation (most compatible, even IE6)
  17379. *
  17380. * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
  17381. * Opera 11.6+, iOS 4.2+.
  17382. *
  17383. * Due to various browser bugs, sometimes the Object implementation will be used even
  17384. * when the browser supports typed arrays.
  17385. *
  17386. * Note:
  17387. *
  17388. * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,
  17389. * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
  17390. *
  17391. * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
  17392. *
  17393. * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
  17394. * incorrect length in some situations.
  17395. * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they
  17396. * get the Object implementation, which is slower but behaves correctly.
  17397. */
  17398. Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined
  17399. ? global.TYPED_ARRAY_SUPPORT
  17400. : typedArraySupport()
  17401. /*
  17402. * Export kMaxLength after typed array support is determined.
  17403. */
  17404. exports.kMaxLength = kMaxLength()
  17405. function typedArraySupport () {
  17406. try {
  17407. var arr = new Uint8Array(1)
  17408. arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }}
  17409. return arr.foo() === 42 && // typed array instances can be augmented
  17410. typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`
  17411. arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`
  17412. } catch (e) {
  17413. return false
  17414. }
  17415. }
  17416. function kMaxLength () {
  17417. return Buffer.TYPED_ARRAY_SUPPORT
  17418. ? 0x7fffffff
  17419. : 0x3fffffff
  17420. }
  17421. function createBuffer (that, length) {
  17422. if (kMaxLength() < length) {
  17423. throw new RangeError('Invalid typed array length')
  17424. }
  17425. if (Buffer.TYPED_ARRAY_SUPPORT) {
  17426. // Return an augmented `Uint8Array` instance, for best performance
  17427. that = new Uint8Array(length)
  17428. that.__proto__ = Buffer.prototype
  17429. } else {
  17430. // Fallback: Return an object instance of the Buffer class
  17431. if (that === null) {
  17432. that = new Buffer(length)
  17433. }
  17434. that.length = length
  17435. }
  17436. return that
  17437. }
  17438. /**
  17439. * The Buffer constructor returns instances of `Uint8Array` that have their
  17440. * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
  17441. * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
  17442. * and the `Uint8Array` methods. Square bracket notation works as expected -- it
  17443. * returns a single octet.
  17444. *
  17445. * The `Uint8Array` prototype remains unmodified.
  17446. */
  17447. function Buffer (arg, encodingOrOffset, length) {
  17448. if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) {
  17449. return new Buffer(arg, encodingOrOffset, length)
  17450. }
  17451. // Common case.
  17452. if (typeof arg === 'number') {
  17453. if (typeof encodingOrOffset === 'string') {
  17454. throw new Error(
  17455. 'If encoding is specified then the first argument must be a string'
  17456. )
  17457. }
  17458. return allocUnsafe(this, arg)
  17459. }
  17460. return from(this, arg, encodingOrOffset, length)
  17461. }
  17462. Buffer.poolSize = 8192 // not used by this implementation
  17463. // TODO: Legacy, not needed anymore. Remove in next major version.
  17464. Buffer._augment = function (arr) {
  17465. arr.__proto__ = Buffer.prototype
  17466. return arr
  17467. }
  17468. function from (that, value, encodingOrOffset, length) {
  17469. if (typeof value === 'number') {
  17470. throw new TypeError('"value" argument must not be a number')
  17471. }
  17472. if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {
  17473. return fromArrayBuffer(that, value, encodingOrOffset, length)
  17474. }
  17475. if (typeof value === 'string') {
  17476. return fromString(that, value, encodingOrOffset)
  17477. }
  17478. return fromObject(that, value)
  17479. }
  17480. /**
  17481. * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
  17482. * if value is a number.
  17483. * Buffer.from(str[, encoding])
  17484. * Buffer.from(array)
  17485. * Buffer.from(buffer)
  17486. * Buffer.from(arrayBuffer[, byteOffset[, length]])
  17487. **/
  17488. Buffer.from = function (value, encodingOrOffset, length) {
  17489. return from(null, value, encodingOrOffset, length)
  17490. }
  17491. if (Buffer.TYPED_ARRAY_SUPPORT) {
  17492. Buffer.prototype.__proto__ = Uint8Array.prototype
  17493. Buffer.__proto__ = Uint8Array
  17494. if (typeof Symbol !== 'undefined' && Symbol.species &&
  17495. Buffer[Symbol.species] === Buffer) {
  17496. // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
  17497. Object.defineProperty(Buffer, Symbol.species, {
  17498. value: null,
  17499. configurable: true
  17500. })
  17501. }
  17502. }
  17503. function assertSize (size) {
  17504. if (typeof size !== 'number') {
  17505. throw new TypeError('"size" argument must be a number')
  17506. } else if (size < 0) {
  17507. throw new RangeError('"size" argument must not be negative')
  17508. }
  17509. }
  17510. function alloc (that, size, fill, encoding) {
  17511. assertSize(size)
  17512. if (size <= 0) {
  17513. return createBuffer(that, size)
  17514. }
  17515. if (fill !== undefined) {
  17516. // Only pay attention to encoding if it's a string. This
  17517. // prevents accidentally sending in a number that would
  17518. // be interpretted as a start offset.
  17519. return typeof encoding === 'string'
  17520. ? createBuffer(that, size).fill(fill, encoding)
  17521. : createBuffer(that, size).fill(fill)
  17522. }
  17523. return createBuffer(that, size)
  17524. }
  17525. /**
  17526. * Creates a new filled Buffer instance.
  17527. * alloc(size[, fill[, encoding]])
  17528. **/
  17529. Buffer.alloc = function (size, fill, encoding) {
  17530. return alloc(null, size, fill, encoding)
  17531. }
  17532. function allocUnsafe (that, size) {
  17533. assertSize(size)
  17534. that = createBuffer(that, size < 0 ? 0 : checked(size) | 0)
  17535. if (!Buffer.TYPED_ARRAY_SUPPORT) {
  17536. for (var i = 0; i < size; ++i) {
  17537. that[i] = 0
  17538. }
  17539. }
  17540. return that
  17541. }
  17542. /**
  17543. * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
  17544. * */
  17545. Buffer.allocUnsafe = function (size) {
  17546. return allocUnsafe(null, size)
  17547. }
  17548. /**
  17549. * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
  17550. */
  17551. Buffer.allocUnsafeSlow = function (size) {
  17552. return allocUnsafe(null, size)
  17553. }
  17554. function fromString (that, string, encoding) {
  17555. if (typeof encoding !== 'string' || encoding === '') {
  17556. encoding = 'utf8'
  17557. }
  17558. if (!Buffer.isEncoding(encoding)) {
  17559. throw new TypeError('"encoding" must be a valid string encoding')
  17560. }
  17561. var length = byteLength(string, encoding) | 0
  17562. that = createBuffer(that, length)
  17563. var actual = that.write(string, encoding)
  17564. if (actual !== length) {
  17565. // Writing a hex string, for example, that contains invalid characters will
  17566. // cause everything after the first invalid character to be ignored. (e.g.
  17567. // 'abxxcd' will be treated as 'ab')
  17568. that = that.slice(0, actual)
  17569. }
  17570. return that
  17571. }
  17572. function fromArrayLike (that, array) {
  17573. var length = array.length < 0 ? 0 : checked(array.length) | 0
  17574. that = createBuffer(that, length)
  17575. for (var i = 0; i < length; i += 1) {
  17576. that[i] = array[i] & 255
  17577. }
  17578. return that
  17579. }
  17580. function fromArrayBuffer (that, array, byteOffset, length) {
  17581. array.byteLength // this throws if `array` is not a valid ArrayBuffer
  17582. if (byteOffset < 0 || array.byteLength < byteOffset) {
  17583. throw new RangeError('\'offset\' is out of bounds')
  17584. }
  17585. if (array.byteLength < byteOffset + (length || 0)) {
  17586. throw new RangeError('\'length\' is out of bounds')
  17587. }
  17588. if (byteOffset === undefined && length === undefined) {
  17589. array = new Uint8Array(array)
  17590. } else if (length === undefined) {
  17591. array = new Uint8Array(array, byteOffset)
  17592. } else {
  17593. array = new Uint8Array(array, byteOffset, length)
  17594. }
  17595. if (Buffer.TYPED_ARRAY_SUPPORT) {
  17596. // Return an augmented `Uint8Array` instance, for best performance
  17597. that = array
  17598. that.__proto__ = Buffer.prototype
  17599. } else {
  17600. // Fallback: Return an object instance of the Buffer class
  17601. that = fromArrayLike(that, array)
  17602. }
  17603. return that
  17604. }
  17605. function fromObject (that, obj) {
  17606. if (Buffer.isBuffer(obj)) {
  17607. var len = checked(obj.length) | 0
  17608. that = createBuffer(that, len)
  17609. if (that.length === 0) {
  17610. return that
  17611. }
  17612. obj.copy(that, 0, 0, len)
  17613. return that
  17614. }
  17615. if (obj) {
  17616. if ((typeof ArrayBuffer !== 'undefined' &&
  17617. obj.buffer instanceof ArrayBuffer) || 'length' in obj) {
  17618. if (typeof obj.length !== 'number' || isnan(obj.length)) {
  17619. return createBuffer(that, 0)
  17620. }
  17621. return fromArrayLike(that, obj)
  17622. }
  17623. if (obj.type === 'Buffer' && isArray(obj.data)) {
  17624. return fromArrayLike(that, obj.data)
  17625. }
  17626. }
  17627. throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')
  17628. }
  17629. function checked (length) {
  17630. // Note: cannot use `length < kMaxLength()` here because that fails when
  17631. // length is NaN (which is otherwise coerced to zero.)
  17632. if (length >= kMaxLength()) {
  17633. throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
  17634. 'size: 0x' + kMaxLength().toString(16) + ' bytes')
  17635. }
  17636. return length | 0
  17637. }
  17638. function SlowBuffer (length) {
  17639. if (+length != length) { // eslint-disable-line eqeqeq
  17640. length = 0
  17641. }
  17642. return Buffer.alloc(+length)
  17643. }
  17644. Buffer.isBuffer = function isBuffer (b) {
  17645. return !!(b != null && b._isBuffer)
  17646. }
  17647. Buffer.compare = function compare (a, b) {
  17648. if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
  17649. throw new TypeError('Arguments must be Buffers')
  17650. }
  17651. if (a === b) return 0
  17652. var x = a.length
  17653. var y = b.length
  17654. for (var i = 0, len = Math.min(x, y); i < len; ++i) {
  17655. if (a[i] !== b[i]) {
  17656. x = a[i]
  17657. y = b[i]
  17658. break
  17659. }
  17660. }
  17661. if (x < y) return -1
  17662. if (y < x) return 1
  17663. return 0
  17664. }
  17665. Buffer.isEncoding = function isEncoding (encoding) {
  17666. switch (String(encoding).toLowerCase()) {
  17667. case 'hex':
  17668. case 'utf8':
  17669. case 'utf-8':
  17670. case 'ascii':
  17671. case 'latin1':
  17672. case 'binary':
  17673. case 'base64':
  17674. case 'ucs2':
  17675. case 'ucs-2':
  17676. case 'utf16le':
  17677. case 'utf-16le':
  17678. return true
  17679. default:
  17680. return false
  17681. }
  17682. }
  17683. Buffer.concat = function concat (list, length) {
  17684. if (!isArray(list)) {
  17685. throw new TypeError('"list" argument must be an Array of Buffers')
  17686. }
  17687. if (list.length === 0) {
  17688. return Buffer.alloc(0)
  17689. }
  17690. var i
  17691. if (length === undefined) {
  17692. length = 0
  17693. for (i = 0; i < list.length; ++i) {
  17694. length += list[i].length
  17695. }
  17696. }
  17697. var buffer = Buffer.allocUnsafe(length)
  17698. var pos = 0
  17699. for (i = 0; i < list.length; ++i) {
  17700. var buf = list[i]
  17701. if (!Buffer.isBuffer(buf)) {
  17702. throw new TypeError('"list" argument must be an Array of Buffers')
  17703. }
  17704. buf.copy(buffer, pos)
  17705. pos += buf.length
  17706. }
  17707. return buffer
  17708. }
  17709. function byteLength (string, encoding) {
  17710. if (Buffer.isBuffer(string)) {
  17711. return string.length
  17712. }
  17713. if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' &&
  17714. (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) {
  17715. return string.byteLength
  17716. }
  17717. if (typeof string !== 'string') {
  17718. string = '' + string
  17719. }
  17720. var len = string.length
  17721. if (len === 0) return 0
  17722. // Use a for loop to avoid recursion
  17723. var loweredCase = false
  17724. for (;;) {
  17725. switch (encoding) {
  17726. case 'ascii':
  17727. case 'latin1':
  17728. case 'binary':
  17729. return len
  17730. case 'utf8':
  17731. case 'utf-8':
  17732. case undefined:
  17733. return utf8ToBytes(string).length
  17734. case 'ucs2':
  17735. case 'ucs-2':
  17736. case 'utf16le':
  17737. case 'utf-16le':
  17738. return len * 2
  17739. case 'hex':
  17740. return len >>> 1
  17741. case 'base64':
  17742. return base64ToBytes(string).length
  17743. default:
  17744. if (loweredCase) return utf8ToBytes(string).length // assume utf8
  17745. encoding = ('' + encoding).toLowerCase()
  17746. loweredCase = true
  17747. }
  17748. }
  17749. }
  17750. Buffer.byteLength = byteLength
  17751. function slowToString (encoding, start, end) {
  17752. var loweredCase = false
  17753. // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
  17754. // property of a typed array.
  17755. // This behaves neither like String nor Uint8Array in that we set start/end
  17756. // to their upper/lower bounds if the value passed is out of range.
  17757. // undefined is handled specially as per ECMA-262 6th Edition,
  17758. // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
  17759. if (start === undefined || start < 0) {
  17760. start = 0
  17761. }
  17762. // Return early if start > this.length. Done here to prevent potential uint32
  17763. // coercion fail below.
  17764. if (start > this.length) {
  17765. return ''
  17766. }
  17767. if (end === undefined || end > this.length) {
  17768. end = this.length
  17769. }
  17770. if (end <= 0) {
  17771. return ''
  17772. }
  17773. // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
  17774. end >>>= 0
  17775. start >>>= 0
  17776. if (end <= start) {
  17777. return ''
  17778. }
  17779. if (!encoding) encoding = 'utf8'
  17780. while (true) {
  17781. switch (encoding) {
  17782. case 'hex':
  17783. return hexSlice(this, start, end)
  17784. case 'utf8':
  17785. case 'utf-8':
  17786. return utf8Slice(this, start, end)
  17787. case 'ascii':
  17788. return asciiSlice(this, start, end)
  17789. case 'latin1':
  17790. case 'binary':
  17791. return latin1Slice(this, start, end)
  17792. case 'base64':
  17793. return base64Slice(this, start, end)
  17794. case 'ucs2':
  17795. case 'ucs-2':
  17796. case 'utf16le':
  17797. case 'utf-16le':
  17798. return utf16leSlice(this, start, end)
  17799. default:
  17800. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  17801. encoding = (encoding + '').toLowerCase()
  17802. loweredCase = true
  17803. }
  17804. }
  17805. }
  17806. // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect
  17807. // Buffer instances.
  17808. Buffer.prototype._isBuffer = true
  17809. function swap (b, n, m) {
  17810. var i = b[n]
  17811. b[n] = b[m]
  17812. b[m] = i
  17813. }
  17814. Buffer.prototype.swap16 = function swap16 () {
  17815. var len = this.length
  17816. if (len % 2 !== 0) {
  17817. throw new RangeError('Buffer size must be a multiple of 16-bits')
  17818. }
  17819. for (var i = 0; i < len; i += 2) {
  17820. swap(this, i, i + 1)
  17821. }
  17822. return this
  17823. }
  17824. Buffer.prototype.swap32 = function swap32 () {
  17825. var len = this.length
  17826. if (len % 4 !== 0) {
  17827. throw new RangeError('Buffer size must be a multiple of 32-bits')
  17828. }
  17829. for (var i = 0; i < len; i += 4) {
  17830. swap(this, i, i + 3)
  17831. swap(this, i + 1, i + 2)
  17832. }
  17833. return this
  17834. }
  17835. Buffer.prototype.swap64 = function swap64 () {
  17836. var len = this.length
  17837. if (len % 8 !== 0) {
  17838. throw new RangeError('Buffer size must be a multiple of 64-bits')
  17839. }
  17840. for (var i = 0; i < len; i += 8) {
  17841. swap(this, i, i + 7)
  17842. swap(this, i + 1, i + 6)
  17843. swap(this, i + 2, i + 5)
  17844. swap(this, i + 3, i + 4)
  17845. }
  17846. return this
  17847. }
  17848. Buffer.prototype.toString = function toString () {
  17849. var length = this.length | 0
  17850. if (length === 0) return ''
  17851. if (arguments.length === 0) return utf8Slice(this, 0, length)
  17852. return slowToString.apply(this, arguments)
  17853. }
  17854. Buffer.prototype.equals = function equals (b) {
  17855. if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
  17856. if (this === b) return true
  17857. return Buffer.compare(this, b) === 0
  17858. }
  17859. Buffer.prototype.inspect = function inspect () {
  17860. var str = ''
  17861. var max = exports.INSPECT_MAX_BYTES
  17862. if (this.length > 0) {
  17863. str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')
  17864. if (this.length > max) str += ' ... '
  17865. }
  17866. return '<Buffer ' + str + '>'
  17867. }
  17868. Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
  17869. if (!Buffer.isBuffer(target)) {
  17870. throw new TypeError('Argument must be a Buffer')
  17871. }
  17872. if (start === undefined) {
  17873. start = 0
  17874. }
  17875. if (end === undefined) {
  17876. end = target ? target.length : 0
  17877. }
  17878. if (thisStart === undefined) {
  17879. thisStart = 0
  17880. }
  17881. if (thisEnd === undefined) {
  17882. thisEnd = this.length
  17883. }
  17884. if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
  17885. throw new RangeError('out of range index')
  17886. }
  17887. if (thisStart >= thisEnd && start >= end) {
  17888. return 0
  17889. }
  17890. if (thisStart >= thisEnd) {
  17891. return -1
  17892. }
  17893. if (start >= end) {
  17894. return 1
  17895. }
  17896. start >>>= 0
  17897. end >>>= 0
  17898. thisStart >>>= 0
  17899. thisEnd >>>= 0
  17900. if (this === target) return 0
  17901. var x = thisEnd - thisStart
  17902. var y = end - start
  17903. var len = Math.min(x, y)
  17904. var thisCopy = this.slice(thisStart, thisEnd)
  17905. var targetCopy = target.slice(start, end)
  17906. for (var i = 0; i < len; ++i) {
  17907. if (thisCopy[i] !== targetCopy[i]) {
  17908. x = thisCopy[i]
  17909. y = targetCopy[i]
  17910. break
  17911. }
  17912. }
  17913. if (x < y) return -1
  17914. if (y < x) return 1
  17915. return 0
  17916. }
  17917. // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
  17918. // OR the last index of `val` in `buffer` at offset <= `byteOffset`.
  17919. //
  17920. // Arguments:
  17921. // - buffer - a Buffer to search
  17922. // - val - a string, Buffer, or number
  17923. // - byteOffset - an index into `buffer`; will be clamped to an int32
  17924. // - encoding - an optional encoding, relevant is val is a string
  17925. // - dir - true for indexOf, false for lastIndexOf
  17926. function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
  17927. // Empty buffer means no match
  17928. if (buffer.length === 0) return -1
  17929. // Normalize byteOffset
  17930. if (typeof byteOffset === 'string') {
  17931. encoding = byteOffset
  17932. byteOffset = 0
  17933. } else if (byteOffset > 0x7fffffff) {
  17934. byteOffset = 0x7fffffff
  17935. } else if (byteOffset < -0x80000000) {
  17936. byteOffset = -0x80000000
  17937. }
  17938. byteOffset = +byteOffset // Coerce to Number.
  17939. if (isNaN(byteOffset)) {
  17940. // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
  17941. byteOffset = dir ? 0 : (buffer.length - 1)
  17942. }
  17943. // Normalize byteOffset: negative offsets start from the end of the buffer
  17944. if (byteOffset < 0) byteOffset = buffer.length + byteOffset
  17945. if (byteOffset >= buffer.length) {
  17946. if (dir) return -1
  17947. else byteOffset = buffer.length - 1
  17948. } else if (byteOffset < 0) {
  17949. if (dir) byteOffset = 0
  17950. else return -1
  17951. }
  17952. // Normalize val
  17953. if (typeof val === 'string') {
  17954. val = Buffer.from(val, encoding)
  17955. }
  17956. // Finally, search either indexOf (if dir is true) or lastIndexOf
  17957. if (Buffer.isBuffer(val)) {
  17958. // Special case: looking for empty string/buffer always fails
  17959. if (val.length === 0) {
  17960. return -1
  17961. }
  17962. return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
  17963. } else if (typeof val === 'number') {
  17964. val = val & 0xFF // Search for a byte value [0-255]
  17965. if (Buffer.TYPED_ARRAY_SUPPORT &&
  17966. typeof Uint8Array.prototype.indexOf === 'function') {
  17967. if (dir) {
  17968. return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
  17969. } else {
  17970. return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
  17971. }
  17972. }
  17973. return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
  17974. }
  17975. throw new TypeError('val must be string, number or Buffer')
  17976. }
  17977. function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
  17978. var indexSize = 1
  17979. var arrLength = arr.length
  17980. var valLength = val.length
  17981. if (encoding !== undefined) {
  17982. encoding = String(encoding).toLowerCase()
  17983. if (encoding === 'ucs2' || encoding === 'ucs-2' ||
  17984. encoding === 'utf16le' || encoding === 'utf-16le') {
  17985. if (arr.length < 2 || val.length < 2) {
  17986. return -1
  17987. }
  17988. indexSize = 2
  17989. arrLength /= 2
  17990. valLength /= 2
  17991. byteOffset /= 2
  17992. }
  17993. }
  17994. function read (buf, i) {
  17995. if (indexSize === 1) {
  17996. return buf[i]
  17997. } else {
  17998. return buf.readUInt16BE(i * indexSize)
  17999. }
  18000. }
  18001. var i
  18002. if (dir) {
  18003. var foundIndex = -1
  18004. for (i = byteOffset; i < arrLength; i++) {
  18005. if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
  18006. if (foundIndex === -1) foundIndex = i
  18007. if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
  18008. } else {
  18009. if (foundIndex !== -1) i -= i - foundIndex
  18010. foundIndex = -1
  18011. }
  18012. }
  18013. } else {
  18014. if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
  18015. for (i = byteOffset; i >= 0; i--) {
  18016. var found = true
  18017. for (var j = 0; j < valLength; j++) {
  18018. if (read(arr, i + j) !== read(val, j)) {
  18019. found = false
  18020. break
  18021. }
  18022. }
  18023. if (found) return i
  18024. }
  18025. }
  18026. return -1
  18027. }
  18028. Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
  18029. return this.indexOf(val, byteOffset, encoding) !== -1
  18030. }
  18031. Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
  18032. return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
  18033. }
  18034. Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
  18035. return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
  18036. }
  18037. function hexWrite (buf, string, offset, length) {
  18038. offset = Number(offset) || 0
  18039. var remaining = buf.length - offset
  18040. if (!length) {
  18041. length = remaining
  18042. } else {
  18043. length = Number(length)
  18044. if (length > remaining) {
  18045. length = remaining
  18046. }
  18047. }
  18048. // must be an even number of digits
  18049. var strLen = string.length
  18050. if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')
  18051. if (length > strLen / 2) {
  18052. length = strLen / 2
  18053. }
  18054. for (var i = 0; i < length; ++i) {
  18055. var parsed = parseInt(string.substr(i * 2, 2), 16)
  18056. if (isNaN(parsed)) return i
  18057. buf[offset + i] = parsed
  18058. }
  18059. return i
  18060. }
  18061. function utf8Write (buf, string, offset, length) {
  18062. return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
  18063. }
  18064. function asciiWrite (buf, string, offset, length) {
  18065. return blitBuffer(asciiToBytes(string), buf, offset, length)
  18066. }
  18067. function latin1Write (buf, string, offset, length) {
  18068. return asciiWrite(buf, string, offset, length)
  18069. }
  18070. function base64Write (buf, string, offset, length) {
  18071. return blitBuffer(base64ToBytes(string), buf, offset, length)
  18072. }
  18073. function ucs2Write (buf, string, offset, length) {
  18074. return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
  18075. }
  18076. Buffer.prototype.write = function write (string, offset, length, encoding) {
  18077. // Buffer#write(string)
  18078. if (offset === undefined) {
  18079. encoding = 'utf8'
  18080. length = this.length
  18081. offset = 0
  18082. // Buffer#write(string, encoding)
  18083. } else if (length === undefined && typeof offset === 'string') {
  18084. encoding = offset
  18085. length = this.length
  18086. offset = 0
  18087. // Buffer#write(string, offset[, length][, encoding])
  18088. } else if (isFinite(offset)) {
  18089. offset = offset | 0
  18090. if (isFinite(length)) {
  18091. length = length | 0
  18092. if (encoding === undefined) encoding = 'utf8'
  18093. } else {
  18094. encoding = length
  18095. length = undefined
  18096. }
  18097. // legacy write(string, encoding, offset, length) - remove in v0.13
  18098. } else {
  18099. throw new Error(
  18100. 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
  18101. )
  18102. }
  18103. var remaining = this.length - offset
  18104. if (length === undefined || length > remaining) length = remaining
  18105. if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
  18106. throw new RangeError('Attempt to write outside buffer bounds')
  18107. }
  18108. if (!encoding) encoding = 'utf8'
  18109. var loweredCase = false
  18110. for (;;) {
  18111. switch (encoding) {
  18112. case 'hex':
  18113. return hexWrite(this, string, offset, length)
  18114. case 'utf8':
  18115. case 'utf-8':
  18116. return utf8Write(this, string, offset, length)
  18117. case 'ascii':
  18118. return asciiWrite(this, string, offset, length)
  18119. case 'latin1':
  18120. case 'binary':
  18121. return latin1Write(this, string, offset, length)
  18122. case 'base64':
  18123. // Warning: maxLength not taken into account in base64Write
  18124. return base64Write(this, string, offset, length)
  18125. case 'ucs2':
  18126. case 'ucs-2':
  18127. case 'utf16le':
  18128. case 'utf-16le':
  18129. return ucs2Write(this, string, offset, length)
  18130. default:
  18131. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  18132. encoding = ('' + encoding).toLowerCase()
  18133. loweredCase = true
  18134. }
  18135. }
  18136. }
  18137. Buffer.prototype.toJSON = function toJSON () {
  18138. return {
  18139. type: 'Buffer',
  18140. data: Array.prototype.slice.call(this._arr || this, 0)
  18141. }
  18142. }
  18143. function base64Slice (buf, start, end) {
  18144. if (start === 0 && end === buf.length) {
  18145. return base64.fromByteArray(buf)
  18146. } else {
  18147. return base64.fromByteArray(buf.slice(start, end))
  18148. }
  18149. }
  18150. function utf8Slice (buf, start, end) {
  18151. end = Math.min(buf.length, end)
  18152. var res = []
  18153. var i = start
  18154. while (i < end) {
  18155. var firstByte = buf[i]
  18156. var codePoint = null
  18157. var bytesPerSequence = (firstByte > 0xEF) ? 4
  18158. : (firstByte > 0xDF) ? 3
  18159. : (firstByte > 0xBF) ? 2
  18160. : 1
  18161. if (i + bytesPerSequence <= end) {
  18162. var secondByte, thirdByte, fourthByte, tempCodePoint
  18163. switch (bytesPerSequence) {
  18164. case 1:
  18165. if (firstByte < 0x80) {
  18166. codePoint = firstByte
  18167. }
  18168. break
  18169. case 2:
  18170. secondByte = buf[i + 1]
  18171. if ((secondByte & 0xC0) === 0x80) {
  18172. tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
  18173. if (tempCodePoint > 0x7F) {
  18174. codePoint = tempCodePoint
  18175. }
  18176. }
  18177. break
  18178. case 3:
  18179. secondByte = buf[i + 1]
  18180. thirdByte = buf[i + 2]
  18181. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
  18182. tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
  18183. if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
  18184. codePoint = tempCodePoint
  18185. }
  18186. }
  18187. break
  18188. case 4:
  18189. secondByte = buf[i + 1]
  18190. thirdByte = buf[i + 2]
  18191. fourthByte = buf[i + 3]
  18192. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
  18193. tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
  18194. if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
  18195. codePoint = tempCodePoint
  18196. }
  18197. }
  18198. }
  18199. }
  18200. if (codePoint === null) {
  18201. // we did not generate a valid codePoint so insert a
  18202. // replacement char (U+FFFD) and advance only 1 byte
  18203. codePoint = 0xFFFD
  18204. bytesPerSequence = 1
  18205. } else if (codePoint > 0xFFFF) {
  18206. // encode to utf16 (surrogate pair dance)
  18207. codePoint -= 0x10000
  18208. res.push(codePoint >>> 10 & 0x3FF | 0xD800)
  18209. codePoint = 0xDC00 | codePoint & 0x3FF
  18210. }
  18211. res.push(codePoint)
  18212. i += bytesPerSequence
  18213. }
  18214. return decodeCodePointsArray(res)
  18215. }
  18216. // Based on http://stackoverflow.com/a/22747272/680742, the browser with
  18217. // the lowest limit is Chrome, with 0x10000 args.
  18218. // We go 1 magnitude less, for safety
  18219. var MAX_ARGUMENTS_LENGTH = 0x1000
  18220. function decodeCodePointsArray (codePoints) {
  18221. var len = codePoints.length
  18222. if (len <= MAX_ARGUMENTS_LENGTH) {
  18223. return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
  18224. }
  18225. // Decode in chunks to avoid "call stack size exceeded".
  18226. var res = ''
  18227. var i = 0
  18228. while (i < len) {
  18229. res += String.fromCharCode.apply(
  18230. String,
  18231. codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
  18232. )
  18233. }
  18234. return res
  18235. }
  18236. function asciiSlice (buf, start, end) {
  18237. var ret = ''
  18238. end = Math.min(buf.length, end)
  18239. for (var i = start; i < end; ++i) {
  18240. ret += String.fromCharCode(buf[i] & 0x7F)
  18241. }
  18242. return ret
  18243. }
  18244. function latin1Slice (buf, start, end) {
  18245. var ret = ''
  18246. end = Math.min(buf.length, end)
  18247. for (var i = start; i < end; ++i) {
  18248. ret += String.fromCharCode(buf[i])
  18249. }
  18250. return ret
  18251. }
  18252. function hexSlice (buf, start, end) {
  18253. var len = buf.length
  18254. if (!start || start < 0) start = 0
  18255. if (!end || end < 0 || end > len) end = len
  18256. var out = ''
  18257. for (var i = start; i < end; ++i) {
  18258. out += toHex(buf[i])
  18259. }
  18260. return out
  18261. }
  18262. function utf16leSlice (buf, start, end) {
  18263. var bytes = buf.slice(start, end)
  18264. var res = ''
  18265. for (var i = 0; i < bytes.length; i += 2) {
  18266. res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)
  18267. }
  18268. return res
  18269. }
  18270. Buffer.prototype.slice = function slice (start, end) {
  18271. var len = this.length
  18272. start = ~~start
  18273. end = end === undefined ? len : ~~end
  18274. if (start < 0) {
  18275. start += len
  18276. if (start < 0) start = 0
  18277. } else if (start > len) {
  18278. start = len
  18279. }
  18280. if (end < 0) {
  18281. end += len
  18282. if (end < 0) end = 0
  18283. } else if (end > len) {
  18284. end = len
  18285. }
  18286. if (end < start) end = start
  18287. var newBuf
  18288. if (Buffer.TYPED_ARRAY_SUPPORT) {
  18289. newBuf = this.subarray(start, end)
  18290. newBuf.__proto__ = Buffer.prototype
  18291. } else {
  18292. var sliceLen = end - start
  18293. newBuf = new Buffer(sliceLen, undefined)
  18294. for (var i = 0; i < sliceLen; ++i) {
  18295. newBuf[i] = this[i + start]
  18296. }
  18297. }
  18298. return newBuf
  18299. }
  18300. /*
  18301. * Need to make sure that buffer isn't trying to write out of bounds.
  18302. */
  18303. function checkOffset (offset, ext, length) {
  18304. if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
  18305. if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
  18306. }
  18307. Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
  18308. offset = offset | 0
  18309. byteLength = byteLength | 0
  18310. if (!noAssert) checkOffset(offset, byteLength, this.length)
  18311. var val = this[offset]
  18312. var mul = 1
  18313. var i = 0
  18314. while (++i < byteLength && (mul *= 0x100)) {
  18315. val += this[offset + i] * mul
  18316. }
  18317. return val
  18318. }
  18319. Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
  18320. offset = offset | 0
  18321. byteLength = byteLength | 0
  18322. if (!noAssert) {
  18323. checkOffset(offset, byteLength, this.length)
  18324. }
  18325. var val = this[offset + --byteLength]
  18326. var mul = 1
  18327. while (byteLength > 0 && (mul *= 0x100)) {
  18328. val += this[offset + --byteLength] * mul
  18329. }
  18330. return val
  18331. }
  18332. Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
  18333. if (!noAssert) checkOffset(offset, 1, this.length)
  18334. return this[offset]
  18335. }
  18336. Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
  18337. if (!noAssert) checkOffset(offset, 2, this.length)
  18338. return this[offset] | (this[offset + 1] << 8)
  18339. }
  18340. Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
  18341. if (!noAssert) checkOffset(offset, 2, this.length)
  18342. return (this[offset] << 8) | this[offset + 1]
  18343. }
  18344. Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
  18345. if (!noAssert) checkOffset(offset, 4, this.length)
  18346. return ((this[offset]) |
  18347. (this[offset + 1] << 8) |
  18348. (this[offset + 2] << 16)) +
  18349. (this[offset + 3] * 0x1000000)
  18350. }
  18351. Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
  18352. if (!noAssert) checkOffset(offset, 4, this.length)
  18353. return (this[offset] * 0x1000000) +
  18354. ((this[offset + 1] << 16) |
  18355. (this[offset + 2] << 8) |
  18356. this[offset + 3])
  18357. }
  18358. Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
  18359. offset = offset | 0
  18360. byteLength = byteLength | 0
  18361. if (!noAssert) checkOffset(offset, byteLength, this.length)
  18362. var val = this[offset]
  18363. var mul = 1
  18364. var i = 0
  18365. while (++i < byteLength && (mul *= 0x100)) {
  18366. val += this[offset + i] * mul
  18367. }
  18368. mul *= 0x80
  18369. if (val >= mul) val -= Math.pow(2, 8 * byteLength)
  18370. return val
  18371. }
  18372. Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
  18373. offset = offset | 0
  18374. byteLength = byteLength | 0
  18375. if (!noAssert) checkOffset(offset, byteLength, this.length)
  18376. var i = byteLength
  18377. var mul = 1
  18378. var val = this[offset + --i]
  18379. while (i > 0 && (mul *= 0x100)) {
  18380. val += this[offset + --i] * mul
  18381. }
  18382. mul *= 0x80
  18383. if (val >= mul) val -= Math.pow(2, 8 * byteLength)
  18384. return val
  18385. }
  18386. Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
  18387. if (!noAssert) checkOffset(offset, 1, this.length)
  18388. if (!(this[offset] & 0x80)) return (this[offset])
  18389. return ((0xff - this[offset] + 1) * -1)
  18390. }
  18391. Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
  18392. if (!noAssert) checkOffset(offset, 2, this.length)
  18393. var val = this[offset] | (this[offset + 1] << 8)
  18394. return (val & 0x8000) ? val | 0xFFFF0000 : val
  18395. }
  18396. Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
  18397. if (!noAssert) checkOffset(offset, 2, this.length)
  18398. var val = this[offset + 1] | (this[offset] << 8)
  18399. return (val & 0x8000) ? val | 0xFFFF0000 : val
  18400. }
  18401. Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
  18402. if (!noAssert) checkOffset(offset, 4, this.length)
  18403. return (this[offset]) |
  18404. (this[offset + 1] << 8) |
  18405. (this[offset + 2] << 16) |
  18406. (this[offset + 3] << 24)
  18407. }
  18408. Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
  18409. if (!noAssert) checkOffset(offset, 4, this.length)
  18410. return (this[offset] << 24) |
  18411. (this[offset + 1] << 16) |
  18412. (this[offset + 2] << 8) |
  18413. (this[offset + 3])
  18414. }
  18415. Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
  18416. if (!noAssert) checkOffset(offset, 4, this.length)
  18417. return ieee754.read(this, offset, true, 23, 4)
  18418. }
  18419. Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
  18420. if (!noAssert) checkOffset(offset, 4, this.length)
  18421. return ieee754.read(this, offset, false, 23, 4)
  18422. }
  18423. Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
  18424. if (!noAssert) checkOffset(offset, 8, this.length)
  18425. return ieee754.read(this, offset, true, 52, 8)
  18426. }
  18427. Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
  18428. if (!noAssert) checkOffset(offset, 8, this.length)
  18429. return ieee754.read(this, offset, false, 52, 8)
  18430. }
  18431. function checkInt (buf, value, offset, ext, max, min) {
  18432. if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
  18433. if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
  18434. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  18435. }
  18436. Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
  18437. value = +value
  18438. offset = offset | 0
  18439. byteLength = byteLength | 0
  18440. if (!noAssert) {
  18441. var maxBytes = Math.pow(2, 8 * byteLength) - 1
  18442. checkInt(this, value, offset, byteLength, maxBytes, 0)
  18443. }
  18444. var mul = 1
  18445. var i = 0
  18446. this[offset] = value & 0xFF
  18447. while (++i < byteLength && (mul *= 0x100)) {
  18448. this[offset + i] = (value / mul) & 0xFF
  18449. }
  18450. return offset + byteLength
  18451. }
  18452. Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
  18453. value = +value
  18454. offset = offset | 0
  18455. byteLength = byteLength | 0
  18456. if (!noAssert) {
  18457. var maxBytes = Math.pow(2, 8 * byteLength) - 1
  18458. checkInt(this, value, offset, byteLength, maxBytes, 0)
  18459. }
  18460. var i = byteLength - 1
  18461. var mul = 1
  18462. this[offset + i] = value & 0xFF
  18463. while (--i >= 0 && (mul *= 0x100)) {
  18464. this[offset + i] = (value / mul) & 0xFF
  18465. }
  18466. return offset + byteLength
  18467. }
  18468. Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
  18469. value = +value
  18470. offset = offset | 0
  18471. if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
  18472. if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
  18473. this[offset] = (value & 0xff)
  18474. return offset + 1
  18475. }
  18476. function objectWriteUInt16 (buf, value, offset, littleEndian) {
  18477. if (value < 0) value = 0xffff + value + 1
  18478. for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) {
  18479. buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
  18480. (littleEndian ? i : 1 - i) * 8
  18481. }
  18482. }
  18483. Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
  18484. value = +value
  18485. offset = offset | 0
  18486. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  18487. if (Buffer.TYPED_ARRAY_SUPPORT) {
  18488. this[offset] = (value & 0xff)
  18489. this[offset + 1] = (value >>> 8)
  18490. } else {
  18491. objectWriteUInt16(this, value, offset, true)
  18492. }
  18493. return offset + 2
  18494. }
  18495. Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
  18496. value = +value
  18497. offset = offset | 0
  18498. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  18499. if (Buffer.TYPED_ARRAY_SUPPORT) {
  18500. this[offset] = (value >>> 8)
  18501. this[offset + 1] = (value & 0xff)
  18502. } else {
  18503. objectWriteUInt16(this, value, offset, false)
  18504. }
  18505. return offset + 2
  18506. }
  18507. function objectWriteUInt32 (buf, value, offset, littleEndian) {
  18508. if (value < 0) value = 0xffffffff + value + 1
  18509. for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) {
  18510. buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff
  18511. }
  18512. }
  18513. Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
  18514. value = +value
  18515. offset = offset | 0
  18516. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  18517. if (Buffer.TYPED_ARRAY_SUPPORT) {
  18518. this[offset + 3] = (value >>> 24)
  18519. this[offset + 2] = (value >>> 16)
  18520. this[offset + 1] = (value >>> 8)
  18521. this[offset] = (value & 0xff)
  18522. } else {
  18523. objectWriteUInt32(this, value, offset, true)
  18524. }
  18525. return offset + 4
  18526. }
  18527. Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
  18528. value = +value
  18529. offset = offset | 0
  18530. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  18531. if (Buffer.TYPED_ARRAY_SUPPORT) {
  18532. this[offset] = (value >>> 24)
  18533. this[offset + 1] = (value >>> 16)
  18534. this[offset + 2] = (value >>> 8)
  18535. this[offset + 3] = (value & 0xff)
  18536. } else {
  18537. objectWriteUInt32(this, value, offset, false)
  18538. }
  18539. return offset + 4
  18540. }
  18541. Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
  18542. value = +value
  18543. offset = offset | 0
  18544. if (!noAssert) {
  18545. var limit = Math.pow(2, 8 * byteLength - 1)
  18546. checkInt(this, value, offset, byteLength, limit - 1, -limit)
  18547. }
  18548. var i = 0
  18549. var mul = 1
  18550. var sub = 0
  18551. this[offset] = value & 0xFF
  18552. while (++i < byteLength && (mul *= 0x100)) {
  18553. if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
  18554. sub = 1
  18555. }
  18556. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  18557. }
  18558. return offset + byteLength
  18559. }
  18560. Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
  18561. value = +value
  18562. offset = offset | 0
  18563. if (!noAssert) {
  18564. var limit = Math.pow(2, 8 * byteLength - 1)
  18565. checkInt(this, value, offset, byteLength, limit - 1, -limit)
  18566. }
  18567. var i = byteLength - 1
  18568. var mul = 1
  18569. var sub = 0
  18570. this[offset + i] = value & 0xFF
  18571. while (--i >= 0 && (mul *= 0x100)) {
  18572. if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
  18573. sub = 1
  18574. }
  18575. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  18576. }
  18577. return offset + byteLength
  18578. }
  18579. Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
  18580. value = +value
  18581. offset = offset | 0
  18582. if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
  18583. if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
  18584. if (value < 0) value = 0xff + value + 1
  18585. this[offset] = (value & 0xff)
  18586. return offset + 1
  18587. }
  18588. Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
  18589. value = +value
  18590. offset = offset | 0
  18591. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  18592. if (Buffer.TYPED_ARRAY_SUPPORT) {
  18593. this[offset] = (value & 0xff)
  18594. this[offset + 1] = (value >>> 8)
  18595. } else {
  18596. objectWriteUInt16(this, value, offset, true)
  18597. }
  18598. return offset + 2
  18599. }
  18600. Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
  18601. value = +value
  18602. offset = offset | 0
  18603. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  18604. if (Buffer.TYPED_ARRAY_SUPPORT) {
  18605. this[offset] = (value >>> 8)
  18606. this[offset + 1] = (value & 0xff)
  18607. } else {
  18608. objectWriteUInt16(this, value, offset, false)
  18609. }
  18610. return offset + 2
  18611. }
  18612. Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
  18613. value = +value
  18614. offset = offset | 0
  18615. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  18616. if (Buffer.TYPED_ARRAY_SUPPORT) {
  18617. this[offset] = (value & 0xff)
  18618. this[offset + 1] = (value >>> 8)
  18619. this[offset + 2] = (value >>> 16)
  18620. this[offset + 3] = (value >>> 24)
  18621. } else {
  18622. objectWriteUInt32(this, value, offset, true)
  18623. }
  18624. return offset + 4
  18625. }
  18626. Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
  18627. value = +value
  18628. offset = offset | 0
  18629. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  18630. if (value < 0) value = 0xffffffff + value + 1
  18631. if (Buffer.TYPED_ARRAY_SUPPORT) {
  18632. this[offset] = (value >>> 24)
  18633. this[offset + 1] = (value >>> 16)
  18634. this[offset + 2] = (value >>> 8)
  18635. this[offset + 3] = (value & 0xff)
  18636. } else {
  18637. objectWriteUInt32(this, value, offset, false)
  18638. }
  18639. return offset + 4
  18640. }
  18641. function checkIEEE754 (buf, value, offset, ext, max, min) {
  18642. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  18643. if (offset < 0) throw new RangeError('Index out of range')
  18644. }
  18645. function writeFloat (buf, value, offset, littleEndian, noAssert) {
  18646. if (!noAssert) {
  18647. checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
  18648. }
  18649. ieee754.write(buf, value, offset, littleEndian, 23, 4)
  18650. return offset + 4
  18651. }
  18652. Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
  18653. return writeFloat(this, value, offset, true, noAssert)
  18654. }
  18655. Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
  18656. return writeFloat(this, value, offset, false, noAssert)
  18657. }
  18658. function writeDouble (buf, value, offset, littleEndian, noAssert) {
  18659. if (!noAssert) {
  18660. checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
  18661. }
  18662. ieee754.write(buf, value, offset, littleEndian, 52, 8)
  18663. return offset + 8
  18664. }
  18665. Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
  18666. return writeDouble(this, value, offset, true, noAssert)
  18667. }
  18668. Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
  18669. return writeDouble(this, value, offset, false, noAssert)
  18670. }
  18671. // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
  18672. Buffer.prototype.copy = function copy (target, targetStart, start, end) {
  18673. if (!start) start = 0
  18674. if (!end && end !== 0) end = this.length
  18675. if (targetStart >= target.length) targetStart = target.length
  18676. if (!targetStart) targetStart = 0
  18677. if (end > 0 && end < start) end = start
  18678. // Copy 0 bytes; we're done
  18679. if (end === start) return 0
  18680. if (target.length === 0 || this.length === 0) return 0
  18681. // Fatal error conditions
  18682. if (targetStart < 0) {
  18683. throw new RangeError('targetStart out of bounds')
  18684. }
  18685. if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
  18686. if (end < 0) throw new RangeError('sourceEnd out of bounds')
  18687. // Are we oob?
  18688. if (end > this.length) end = this.length
  18689. if (target.length - targetStart < end - start) {
  18690. end = target.length - targetStart + start
  18691. }
  18692. var len = end - start
  18693. var i
  18694. if (this === target && start < targetStart && targetStart < end) {
  18695. // descending copy from end
  18696. for (i = len - 1; i >= 0; --i) {
  18697. target[i + targetStart] = this[i + start]
  18698. }
  18699. } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {
  18700. // ascending copy from start
  18701. for (i = 0; i < len; ++i) {
  18702. target[i + targetStart] = this[i + start]
  18703. }
  18704. } else {
  18705. Uint8Array.prototype.set.call(
  18706. target,
  18707. this.subarray(start, start + len),
  18708. targetStart
  18709. )
  18710. }
  18711. return len
  18712. }
  18713. // Usage:
  18714. // buffer.fill(number[, offset[, end]])
  18715. // buffer.fill(buffer[, offset[, end]])
  18716. // buffer.fill(string[, offset[, end]][, encoding])
  18717. Buffer.prototype.fill = function fill (val, start, end, encoding) {
  18718. // Handle string cases:
  18719. if (typeof val === 'string') {
  18720. if (typeof start === 'string') {
  18721. encoding = start
  18722. start = 0
  18723. end = this.length
  18724. } else if (typeof end === 'string') {
  18725. encoding = end
  18726. end = this.length
  18727. }
  18728. if (val.length === 1) {
  18729. var code = val.charCodeAt(0)
  18730. if (code < 256) {
  18731. val = code
  18732. }
  18733. }
  18734. if (encoding !== undefined && typeof encoding !== 'string') {
  18735. throw new TypeError('encoding must be a string')
  18736. }
  18737. if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
  18738. throw new TypeError('Unknown encoding: ' + encoding)
  18739. }
  18740. } else if (typeof val === 'number') {
  18741. val = val & 255
  18742. }
  18743. // Invalid ranges are not set to a default, so can range check early.
  18744. if (start < 0 || this.length < start || this.length < end) {
  18745. throw new RangeError('Out of range index')
  18746. }
  18747. if (end <= start) {
  18748. return this
  18749. }
  18750. start = start >>> 0
  18751. end = end === undefined ? this.length : end >>> 0
  18752. if (!val) val = 0
  18753. var i
  18754. if (typeof val === 'number') {
  18755. for (i = start; i < end; ++i) {
  18756. this[i] = val
  18757. }
  18758. } else {
  18759. var bytes = Buffer.isBuffer(val)
  18760. ? val
  18761. : utf8ToBytes(new Buffer(val, encoding).toString())
  18762. var len = bytes.length
  18763. for (i = 0; i < end - start; ++i) {
  18764. this[i + start] = bytes[i % len]
  18765. }
  18766. }
  18767. return this
  18768. }
  18769. // HELPER FUNCTIONS
  18770. // ================
  18771. var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g
  18772. function base64clean (str) {
  18773. // Node strips out invalid characters like \n and \t from the string, base64-js does not
  18774. str = stringtrim(str).replace(INVALID_BASE64_RE, '')
  18775. // Node converts strings with length < 2 to ''
  18776. if (str.length < 2) return ''
  18777. // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
  18778. while (str.length % 4 !== 0) {
  18779. str = str + '='
  18780. }
  18781. return str
  18782. }
  18783. function stringtrim (str) {
  18784. if (str.trim) return str.trim()
  18785. return str.replace(/^\s+|\s+$/g, '')
  18786. }
  18787. function toHex (n) {
  18788. if (n < 16) return '0' + n.toString(16)
  18789. return n.toString(16)
  18790. }
  18791. function utf8ToBytes (string, units) {
  18792. units = units || Infinity
  18793. var codePoint
  18794. var length = string.length
  18795. var leadSurrogate = null
  18796. var bytes = []
  18797. for (var i = 0; i < length; ++i) {
  18798. codePoint = string.charCodeAt(i)
  18799. // is surrogate component
  18800. if (codePoint > 0xD7FF && codePoint < 0xE000) {
  18801. // last char was a lead
  18802. if (!leadSurrogate) {
  18803. // no lead yet
  18804. if (codePoint > 0xDBFF) {
  18805. // unexpected trail
  18806. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  18807. continue
  18808. } else if (i + 1 === length) {
  18809. // unpaired lead
  18810. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  18811. continue
  18812. }
  18813. // valid lead
  18814. leadSurrogate = codePoint
  18815. continue
  18816. }
  18817. // 2 leads in a row
  18818. if (codePoint < 0xDC00) {
  18819. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  18820. leadSurrogate = codePoint
  18821. continue
  18822. }
  18823. // valid surrogate pair
  18824. codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
  18825. } else if (leadSurrogate) {
  18826. // valid bmp char, but last char was a lead
  18827. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  18828. }
  18829. leadSurrogate = null
  18830. // encode utf8
  18831. if (codePoint < 0x80) {
  18832. if ((units -= 1) < 0) break
  18833. bytes.push(codePoint)
  18834. } else if (codePoint < 0x800) {
  18835. if ((units -= 2) < 0) break
  18836. bytes.push(
  18837. codePoint >> 0x6 | 0xC0,
  18838. codePoint & 0x3F | 0x80
  18839. )
  18840. } else if (codePoint < 0x10000) {
  18841. if ((units -= 3) < 0) break
  18842. bytes.push(
  18843. codePoint >> 0xC | 0xE0,
  18844. codePoint >> 0x6 & 0x3F | 0x80,
  18845. codePoint & 0x3F | 0x80
  18846. )
  18847. } else if (codePoint < 0x110000) {
  18848. if ((units -= 4) < 0) break
  18849. bytes.push(
  18850. codePoint >> 0x12 | 0xF0,
  18851. codePoint >> 0xC & 0x3F | 0x80,
  18852. codePoint >> 0x6 & 0x3F | 0x80,
  18853. codePoint & 0x3F | 0x80
  18854. )
  18855. } else {
  18856. throw new Error('Invalid code point')
  18857. }
  18858. }
  18859. return bytes
  18860. }
  18861. function asciiToBytes (str) {
  18862. var byteArray = []
  18863. for (var i = 0; i < str.length; ++i) {
  18864. // Node's code seems to be doing this and not & 0x7F..
  18865. byteArray.push(str.charCodeAt(i) & 0xFF)
  18866. }
  18867. return byteArray
  18868. }
  18869. function utf16leToBytes (str, units) {
  18870. var c, hi, lo
  18871. var byteArray = []
  18872. for (var i = 0; i < str.length; ++i) {
  18873. if ((units -= 2) < 0) break
  18874. c = str.charCodeAt(i)
  18875. hi = c >> 8
  18876. lo = c % 256
  18877. byteArray.push(lo)
  18878. byteArray.push(hi)
  18879. }
  18880. return byteArray
  18881. }
  18882. function base64ToBytes (str) {
  18883. return base64.toByteArray(base64clean(str))
  18884. }
  18885. function blitBuffer (src, dst, offset, length) {
  18886. for (var i = 0; i < length; ++i) {
  18887. if ((i + offset >= dst.length) || (i >= src.length)) break
  18888. dst[i + offset] = src[i]
  18889. }
  18890. return i
  18891. }
  18892. function isnan (val) {
  18893. return val !== val // eslint-disable-line no-self-compare
  18894. }
  18895. /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }())))
  18896. /***/ }),
  18897. /* 54 */
  18898. /***/ (function(module, exports) {
  18899. 'use strict'
  18900. exports.byteLength = byteLength
  18901. exports.toByteArray = toByteArray
  18902. exports.fromByteArray = fromByteArray
  18903. var lookup = []
  18904. var revLookup = []
  18905. var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
  18906. var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
  18907. for (var i = 0, len = code.length; i < len; ++i) {
  18908. lookup[i] = code[i]
  18909. revLookup[code.charCodeAt(i)] = i
  18910. }
  18911. revLookup['-'.charCodeAt(0)] = 62
  18912. revLookup['_'.charCodeAt(0)] = 63
  18913. function placeHoldersCount (b64) {
  18914. var len = b64.length
  18915. if (len % 4 > 0) {
  18916. throw new Error('Invalid string. Length must be a multiple of 4')
  18917. }
  18918. // the number of equal signs (place holders)
  18919. // if there are two placeholders, than the two characters before it
  18920. // represent one byte
  18921. // if there is only one, then the three characters before it represent 2 bytes
  18922. // this is just a cheap hack to not do indexOf twice
  18923. return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0
  18924. }
  18925. function byteLength (b64) {
  18926. // base64 is 4/3 + up to two characters of the original data
  18927. return (b64.length * 3 / 4) - placeHoldersCount(b64)
  18928. }
  18929. function toByteArray (b64) {
  18930. var i, l, tmp, placeHolders, arr
  18931. var len = b64.length
  18932. placeHolders = placeHoldersCount(b64)
  18933. arr = new Arr((len * 3 / 4) - placeHolders)
  18934. // if there are placeholders, only get up to the last complete 4 chars
  18935. l = placeHolders > 0 ? len - 4 : len
  18936. var L = 0
  18937. for (i = 0; i < l; i += 4) {
  18938. tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]
  18939. arr[L++] = (tmp >> 16) & 0xFF
  18940. arr[L++] = (tmp >> 8) & 0xFF
  18941. arr[L++] = tmp & 0xFF
  18942. }
  18943. if (placeHolders === 2) {
  18944. tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4)
  18945. arr[L++] = tmp & 0xFF
  18946. } else if (placeHolders === 1) {
  18947. tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2)
  18948. arr[L++] = (tmp >> 8) & 0xFF
  18949. arr[L++] = tmp & 0xFF
  18950. }
  18951. return arr
  18952. }
  18953. function tripletToBase64 (num) {
  18954. return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]
  18955. }
  18956. function encodeChunk (uint8, start, end) {
  18957. var tmp
  18958. var output = []
  18959. for (var i = start; i < end; i += 3) {
  18960. tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2])
  18961. output.push(tripletToBase64(tmp))
  18962. }
  18963. return output.join('')
  18964. }
  18965. function fromByteArray (uint8) {
  18966. var tmp
  18967. var len = uint8.length
  18968. var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
  18969. var output = ''
  18970. var parts = []
  18971. var maxChunkLength = 16383 // must be multiple of 3
  18972. // go through the array every three bytes, we'll deal with trailing stuff later
  18973. for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
  18974. parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))
  18975. }
  18976. // pad the end with zeros, but make sure to not forget the extra bytes
  18977. if (extraBytes === 1) {
  18978. tmp = uint8[len - 1]
  18979. output += lookup[tmp >> 2]
  18980. output += lookup[(tmp << 4) & 0x3F]
  18981. output += '=='
  18982. } else if (extraBytes === 2) {
  18983. tmp = (uint8[len - 2] << 8) + (uint8[len - 1])
  18984. output += lookup[tmp >> 10]
  18985. output += lookup[(tmp >> 4) & 0x3F]
  18986. output += lookup[(tmp << 2) & 0x3F]
  18987. output += '='
  18988. }
  18989. parts.push(output)
  18990. return parts.join('')
  18991. }
  18992. /***/ }),
  18993. /* 55 */
  18994. /***/ (function(module, exports) {
  18995. exports.read = function (buffer, offset, isLE, mLen, nBytes) {
  18996. var e, m
  18997. var eLen = nBytes * 8 - mLen - 1
  18998. var eMax = (1 << eLen) - 1
  18999. var eBias = eMax >> 1
  19000. var nBits = -7
  19001. var i = isLE ? (nBytes - 1) : 0
  19002. var d = isLE ? -1 : 1
  19003. var s = buffer[offset + i]
  19004. i += d
  19005. e = s & ((1 << (-nBits)) - 1)
  19006. s >>= (-nBits)
  19007. nBits += eLen
  19008. for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
  19009. m = e & ((1 << (-nBits)) - 1)
  19010. e >>= (-nBits)
  19011. nBits += mLen
  19012. for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
  19013. if (e === 0) {
  19014. e = 1 - eBias
  19015. } else if (e === eMax) {
  19016. return m ? NaN : ((s ? -1 : 1) * Infinity)
  19017. } else {
  19018. m = m + Math.pow(2, mLen)
  19019. e = e - eBias
  19020. }
  19021. return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
  19022. }
  19023. exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
  19024. var e, m, c
  19025. var eLen = nBytes * 8 - mLen - 1
  19026. var eMax = (1 << eLen) - 1
  19027. var eBias = eMax >> 1
  19028. var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
  19029. var i = isLE ? 0 : (nBytes - 1)
  19030. var d = isLE ? 1 : -1
  19031. var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
  19032. value = Math.abs(value)
  19033. if (isNaN(value) || value === Infinity) {
  19034. m = isNaN(value) ? 1 : 0
  19035. e = eMax
  19036. } else {
  19037. e = Math.floor(Math.log(value) / Math.LN2)
  19038. if (value * (c = Math.pow(2, -e)) < 1) {
  19039. e--
  19040. c *= 2
  19041. }
  19042. if (e + eBias >= 1) {
  19043. value += rt / c
  19044. } else {
  19045. value += rt * Math.pow(2, 1 - eBias)
  19046. }
  19047. if (value * c >= 2) {
  19048. e++
  19049. c /= 2
  19050. }
  19051. if (e + eBias >= eMax) {
  19052. m = 0
  19053. e = eMax
  19054. } else if (e + eBias >= 1) {
  19055. m = (value * c - 1) * Math.pow(2, mLen)
  19056. e = e + eBias
  19057. } else {
  19058. m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
  19059. e = 0
  19060. }
  19061. }
  19062. for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
  19063. e = (e << mLen) | m
  19064. eLen += mLen
  19065. for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
  19066. buffer[offset + i - d] |= s * 128
  19067. }
  19068. /***/ }),
  19069. /* 56 */
  19070. /***/ (function(module, exports) {
  19071. var toString = {}.toString;
  19072. module.exports = Array.isArray || function (arr) {
  19073. return toString.call(arr) == '[object Array]';
  19074. };
  19075. /***/ }),
  19076. /* 57 */
  19077. /***/ (function(module, exports) {
  19078. /* (ignored) */
  19079. /***/ }),
  19080. /* 58 */
  19081. /***/ (function(module, exports, __webpack_require__) {
  19082. /* WEBPACK VAR INJECTION */(function(global) {/**
  19083. * marked - a markdown parser
  19084. * Copyright (c) 2011-2014, Christopher Jeffrey. (MIT Licensed)
  19085. * https://github.com/chjj/marked
  19086. */
  19087. ;(function() {
  19088. /**
  19089. * Block-Level Grammar
  19090. */
  19091. var block = {
  19092. newline: /^\n+/,
  19093. code: /^( {4}[^\n]+\n*)+/,
  19094. fences: noop,
  19095. hr: /^( *[-*_]){3,} *(?:\n+|$)/,
  19096. heading: /^ *(#{1,6}) *([^\n]+?) *#* *(?:\n+|$)/,
  19097. nptable: noop,
  19098. lheading: /^([^\n]+)\n *(=|-){2,} *(?:\n+|$)/,
  19099. blockquote: /^( *>[^\n]+(\n(?!def)[^\n]+)*\n*)+/,
  19100. list: /^( *)(bull) [\s\S]+?(?:hr|def|\n{2,}(?! )(?!\1bull )\n*|\s*$)/,
  19101. html: /^ *(?:comment *(?:\n|\s*$)|closed *(?:\n{2,}|\s*$)|closing *(?:\n{2,}|\s*$))/,
  19102. def: /^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +["(]([^\n]+)[")])? *(?:\n+|$)/,
  19103. table: noop,
  19104. paragraph: /^((?:[^\n]+\n?(?!hr|heading|lheading|blockquote|tag|def))+)\n*/,
  19105. text: /^[^\n]+/
  19106. };
  19107. block.bullet = /(?:[*+-]|\d+\.)/;
  19108. block.item = /^( *)(bull) [^\n]*(?:\n(?!\1bull )[^\n]*)*/;
  19109. block.item = replace(block.item, 'gm')
  19110. (/bull/g, block.bullet)
  19111. ();
  19112. block.list = replace(block.list)
  19113. (/bull/g, block.bullet)
  19114. ('hr', '\\n+(?=\\1?(?:[-*_] *){3,}(?:\\n+|$))')
  19115. ('def', '\\n+(?=' + block.def.source + ')')
  19116. ();
  19117. block.blockquote = replace(block.blockquote)
  19118. ('def', block.def)
  19119. ();
  19120. block._tag = '(?!(?:'
  19121. + 'a|em|strong|small|s|cite|q|dfn|abbr|data|time|code'
  19122. + '|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo'
  19123. + '|span|br|wbr|ins|del|img)\\b)\\w+(?!:/|[^\\w\\s@]*@)\\b';
  19124. block.html = replace(block.html)
  19125. ('comment', /<!--[\s\S]*?-->/)
  19126. ('closed', /<(tag)[\s\S]+?<\/\1>/)
  19127. ('closing', /<tag(?:"[^"]*"|'[^']*'|[^'">])*?>/)
  19128. (/tag/g, block._tag)
  19129. ();
  19130. block.paragraph = replace(block.paragraph)
  19131. ('hr', block.hr)
  19132. ('heading', block.heading)
  19133. ('lheading', block.lheading)
  19134. ('blockquote', block.blockquote)
  19135. ('tag', '<' + block._tag)
  19136. ('def', block.def)
  19137. ();
  19138. /**
  19139. * Normal Block Grammar
  19140. */
  19141. block.normal = merge({}, block);
  19142. /**
  19143. * GFM Block Grammar
  19144. */
  19145. block.gfm = merge({}, block.normal, {
  19146. fences: /^ *(`{3,}|~{3,})[ \.]*(\S+)? *\n([\s\S]*?)\s*\1 *(?:\n+|$)/,
  19147. paragraph: /^/,
  19148. heading: /^ *(#{1,6}) +([^\n]+?) *#* *(?:\n+|$)/
  19149. });
  19150. block.gfm.paragraph = replace(block.paragraph)
  19151. ('(?!', '(?!'
  19152. + block.gfm.fences.source.replace('\\1', '\\2') + '|'
  19153. + block.list.source.replace('\\1', '\\3') + '|')
  19154. ();
  19155. /**
  19156. * GFM + Tables Block Grammar
  19157. */
  19158. block.tables = merge({}, block.gfm, {
  19159. nptable: /^ *(\S.*\|.*)\n *([-:]+ *\|[-| :]*)\n((?:.*\|.*(?:\n|$))*)\n*/,
  19160. table: /^ *\|(.+)\n *\|( *[-:]+[-| :]*)\n((?: *\|.*(?:\n|$))*)\n*/
  19161. });
  19162. /**
  19163. * Block Lexer
  19164. */
  19165. function Lexer(options) {
  19166. this.tokens = [];
  19167. this.tokens.links = {};
  19168. this.options = options || marked.defaults;
  19169. this.rules = block.normal;
  19170. if (this.options.gfm) {
  19171. if (this.options.tables) {
  19172. this.rules = block.tables;
  19173. } else {
  19174. this.rules = block.gfm;
  19175. }
  19176. }
  19177. }
  19178. /**
  19179. * Expose Block Rules
  19180. */
  19181. Lexer.rules = block;
  19182. /**
  19183. * Static Lex Method
  19184. */
  19185. Lexer.lex = function(src, options) {
  19186. var lexer = new Lexer(options);
  19187. return lexer.lex(src);
  19188. };
  19189. /**
  19190. * Preprocessing
  19191. */
  19192. Lexer.prototype.lex = function(src) {
  19193. src = src
  19194. .replace(/\r\n|\r/g, '\n')
  19195. .replace(/\t/g, ' ')
  19196. .replace(/\u00a0/g, ' ')
  19197. .replace(/\u2424/g, '\n');
  19198. return this.token(src, true);
  19199. };
  19200. /**
  19201. * Lexing
  19202. */
  19203. Lexer.prototype.token = function(src, top, bq) {
  19204. var src = src.replace(/^ +$/gm, '')
  19205. , next
  19206. , loose
  19207. , cap
  19208. , bull
  19209. , b
  19210. , item
  19211. , space
  19212. , i
  19213. , l;
  19214. while (src) {
  19215. // newline
  19216. if (cap = this.rules.newline.exec(src)) {
  19217. src = src.substring(cap[0].length);
  19218. if (cap[0].length > 1) {
  19219. this.tokens.push({
  19220. type: 'space'
  19221. });
  19222. }
  19223. }
  19224. // code
  19225. if (cap = this.rules.code.exec(src)) {
  19226. src = src.substring(cap[0].length);
  19227. cap = cap[0].replace(/^ {4}/gm, '');
  19228. this.tokens.push({
  19229. type: 'code',
  19230. text: !this.options.pedantic
  19231. ? cap.replace(/\n+$/, '')
  19232. : cap
  19233. });
  19234. continue;
  19235. }
  19236. // fences (gfm)
  19237. if (cap = this.rules.fences.exec(src)) {
  19238. src = src.substring(cap[0].length);
  19239. this.tokens.push({
  19240. type: 'code',
  19241. lang: cap[2],
  19242. text: cap[3] || ''
  19243. });
  19244. continue;
  19245. }
  19246. // heading
  19247. if (cap = this.rules.heading.exec(src)) {
  19248. src = src.substring(cap[0].length);
  19249. this.tokens.push({
  19250. type: 'heading',
  19251. depth: cap[1].length,
  19252. text: cap[2]
  19253. });
  19254. continue;
  19255. }
  19256. // table no leading pipe (gfm)
  19257. if (top && (cap = this.rules.nptable.exec(src))) {
  19258. src = src.substring(cap[0].length);
  19259. item = {
  19260. type: 'table',
  19261. header: cap[1].replace(/^ *| *\| *$/g, '').split(/ *\| */),
  19262. align: cap[2].replace(/^ *|\| *$/g, '').split(/ *\| */),
  19263. cells: cap[3].replace(/\n$/, '').split('\n')
  19264. };
  19265. for (i = 0; i < item.align.length; i++) {
  19266. if (/^ *-+: *$/.test(item.align[i])) {
  19267. item.align[i] = 'right';
  19268. } else if (/^ *:-+: *$/.test(item.align[i])) {
  19269. item.align[i] = 'center';
  19270. } else if (/^ *:-+ *$/.test(item.align[i])) {
  19271. item.align[i] = 'left';
  19272. } else {
  19273. item.align[i] = null;
  19274. }
  19275. }
  19276. for (i = 0; i < item.cells.length; i++) {
  19277. item.cells[i] = item.cells[i].split(/ *\| */);
  19278. }
  19279. this.tokens.push(item);
  19280. continue;
  19281. }
  19282. // lheading
  19283. if (cap = this.rules.lheading.exec(src)) {
  19284. src = src.substring(cap[0].length);
  19285. this.tokens.push({
  19286. type: 'heading',
  19287. depth: cap[2] === '=' ? 1 : 2,
  19288. text: cap[1]
  19289. });
  19290. continue;
  19291. }
  19292. // hr
  19293. if (cap = this.rules.hr.exec(src)) {
  19294. src = src.substring(cap[0].length);
  19295. this.tokens.push({
  19296. type: 'hr'
  19297. });
  19298. continue;
  19299. }
  19300. // blockquote
  19301. if (cap = this.rules.blockquote.exec(src)) {
  19302. src = src.substring(cap[0].length);
  19303. this.tokens.push({
  19304. type: 'blockquote_start'
  19305. });
  19306. cap = cap[0].replace(/^ *> ?/gm, '');
  19307. // Pass `top` to keep the current
  19308. // "toplevel" state. This is exactly
  19309. // how markdown.pl works.
  19310. this.token(cap, top, true);
  19311. this.tokens.push({
  19312. type: 'blockquote_end'
  19313. });
  19314. continue;
  19315. }
  19316. // list
  19317. if (cap = this.rules.list.exec(src)) {
  19318. src = src.substring(cap[0].length);
  19319. bull = cap[2];
  19320. this.tokens.push({
  19321. type: 'list_start',
  19322. ordered: bull.length > 1
  19323. });
  19324. // Get each top-level item.
  19325. cap = cap[0].match(this.rules.item);
  19326. next = false;
  19327. l = cap.length;
  19328. i = 0;
  19329. for (; i < l; i++) {
  19330. item = cap[i];
  19331. // Remove the list item's bullet
  19332. // so it is seen as the next token.
  19333. space = item.length;
  19334. item = item.replace(/^ *([*+-]|\d+\.) +/, '');
  19335. // Outdent whatever the
  19336. // list item contains. Hacky.
  19337. if (~item.indexOf('\n ')) {
  19338. space -= item.length;
  19339. item = !this.options.pedantic
  19340. ? item.replace(new RegExp('^ {1,' + space + '}', 'gm'), '')
  19341. : item.replace(/^ {1,4}/gm, '');
  19342. }
  19343. // Determine whether the next list item belongs here.
  19344. // Backpedal if it does not belong in this list.
  19345. if (this.options.smartLists && i !== l - 1) {
  19346. b = block.bullet.exec(cap[i + 1])[0];
  19347. if (bull !== b && !(bull.length > 1 && b.length > 1)) {
  19348. src = cap.slice(i + 1).join('\n') + src;
  19349. i = l - 1;
  19350. }
  19351. }
  19352. // Determine whether item is loose or not.
  19353. // Use: /(^|\n)(?! )[^\n]+\n\n(?!\s*$)/
  19354. // for discount behavior.
  19355. loose = next || /\n\n(?!\s*$)/.test(item);
  19356. if (i !== l - 1) {
  19357. next = item.charAt(item.length - 1) === '\n';
  19358. if (!loose) loose = next;
  19359. }
  19360. this.tokens.push({
  19361. type: loose
  19362. ? 'loose_item_start'
  19363. : 'list_item_start'
  19364. });
  19365. // Recurse.
  19366. this.token(item, false, bq);
  19367. this.tokens.push({
  19368. type: 'list_item_end'
  19369. });
  19370. }
  19371. this.tokens.push({
  19372. type: 'list_end'
  19373. });
  19374. continue;
  19375. }
  19376. // html
  19377. if (cap = this.rules.html.exec(src)) {
  19378. src = src.substring(cap[0].length);
  19379. this.tokens.push({
  19380. type: this.options.sanitize
  19381. ? 'paragraph'
  19382. : 'html',
  19383. pre: !this.options.sanitizer
  19384. && (cap[1] === 'pre' || cap[1] === 'script' || cap[1] === 'style'),
  19385. text: cap[0]
  19386. });
  19387. continue;
  19388. }
  19389. // def
  19390. if ((!bq && top) && (cap = this.rules.def.exec(src))) {
  19391. src = src.substring(cap[0].length);
  19392. this.tokens.links[cap[1].toLowerCase()] = {
  19393. href: cap[2],
  19394. title: cap[3]
  19395. };
  19396. continue;
  19397. }
  19398. // table (gfm)
  19399. if (top && (cap = this.rules.table.exec(src))) {
  19400. src = src.substring(cap[0].length);
  19401. item = {
  19402. type: 'table',
  19403. header: cap[1].replace(/^ *| *\| *$/g, '').split(/ *\| */),
  19404. align: cap[2].replace(/^ *|\| *$/g, '').split(/ *\| */),
  19405. cells: cap[3].replace(/(?: *\| *)?\n$/, '').split('\n')
  19406. };
  19407. for (i = 0; i < item.align.length; i++) {
  19408. if (/^ *-+: *$/.test(item.align[i])) {
  19409. item.align[i] = 'right';
  19410. } else if (/^ *:-+: *$/.test(item.align[i])) {
  19411. item.align[i] = 'center';
  19412. } else if (/^ *:-+ *$/.test(item.align[i])) {
  19413. item.align[i] = 'left';
  19414. } else {
  19415. item.align[i] = null;
  19416. }
  19417. }
  19418. for (i = 0; i < item.cells.length; i++) {
  19419. item.cells[i] = item.cells[i]
  19420. .replace(/^ *\| *| *\| *$/g, '')
  19421. .split(/ *\| */);
  19422. }
  19423. this.tokens.push(item);
  19424. continue;
  19425. }
  19426. // top-level paragraph
  19427. if (top && (cap = this.rules.paragraph.exec(src))) {
  19428. src = src.substring(cap[0].length);
  19429. this.tokens.push({
  19430. type: 'paragraph',
  19431. text: cap[1].charAt(cap[1].length - 1) === '\n'
  19432. ? cap[1].slice(0, -1)
  19433. : cap[1]
  19434. });
  19435. continue;
  19436. }
  19437. // text
  19438. if (cap = this.rules.text.exec(src)) {
  19439. // Top-level should never reach here.
  19440. src = src.substring(cap[0].length);
  19441. this.tokens.push({
  19442. type: 'text',
  19443. text: cap[0]
  19444. });
  19445. continue;
  19446. }
  19447. if (src) {
  19448. throw new
  19449. Error('Infinite loop on byte: ' + src.charCodeAt(0));
  19450. }
  19451. }
  19452. return this.tokens;
  19453. };
  19454. /**
  19455. * Inline-Level Grammar
  19456. */
  19457. var inline = {
  19458. escape: /^\\([\\`*{}\[\]()#+\-.!_>])/,
  19459. autolink: /^<([^ >]+(@|:\/)[^ >]+)>/,
  19460. url: noop,
  19461. tag: /^<!--[\s\S]*?-->|^<\/?\w+(?:"[^"]*"|'[^']*'|[^'">])*?>/,
  19462. link: /^!?\[(inside)\]\(href\)/,
  19463. reflink: /^!?\[(inside)\]\s*\[([^\]]*)\]/,
  19464. nolink: /^!?\[((?:\[[^\]]*\]|[^\[\]])*)\]/,
  19465. strong: /^__([\s\S]+?)__(?!_)|^\*\*([\s\S]+?)\*\*(?!\*)/,
  19466. em: /^\b_((?:[^_]|__)+?)_\b|^\*((?:\*\*|[\s\S])+?)\*(?!\*)/,
  19467. code: /^(`+)\s*([\s\S]*?[^`])\s*\1(?!`)/,
  19468. br: /^ {2,}\n(?!\s*$)/,
  19469. del: noop,
  19470. text: /^[\s\S]+?(?=[\\<!\[_*`]| {2,}\n|$)/
  19471. };
  19472. inline._inside = /(?:\[[^\]]*\]|[^\[\]]|\](?=[^\[]*\]))*/;
  19473. inline._href = /\s*<?([\s\S]*?)>?(?:\s+['"]([\s\S]*?)['"])?\s*/;
  19474. inline.link = replace(inline.link)
  19475. ('inside', inline._inside)
  19476. ('href', inline._href)
  19477. ();
  19478. inline.reflink = replace(inline.reflink)
  19479. ('inside', inline._inside)
  19480. ();
  19481. /**
  19482. * Normal Inline Grammar
  19483. */
  19484. inline.normal = merge({}, inline);
  19485. /**
  19486. * Pedantic Inline Grammar
  19487. */
  19488. inline.pedantic = merge({}, inline.normal, {
  19489. strong: /^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/,
  19490. em: /^_(?=\S)([\s\S]*?\S)_(?!_)|^\*(?=\S)([\s\S]*?\S)\*(?!\*)/
  19491. });
  19492. /**
  19493. * GFM Inline Grammar
  19494. */
  19495. inline.gfm = merge({}, inline.normal, {
  19496. escape: replace(inline.escape)('])', '~|])')(),
  19497. url: /^(https?:\/\/[^\s<]+[^<.,:;"')\]\s])/,
  19498. del: /^~~(?=\S)([\s\S]*?\S)~~/,
  19499. text: replace(inline.text)
  19500. (']|', '~]|')
  19501. ('|', '|https?://|')
  19502. ()
  19503. });
  19504. /**
  19505. * GFM + Line Breaks Inline Grammar
  19506. */
  19507. inline.breaks = merge({}, inline.gfm, {
  19508. br: replace(inline.br)('{2,}', '*')(),
  19509. text: replace(inline.gfm.text)('{2,}', '*')()
  19510. });
  19511. /**
  19512. * Inline Lexer & Compiler
  19513. */
  19514. function InlineLexer(links, options) {
  19515. this.options = options || marked.defaults;
  19516. this.links = links;
  19517. this.rules = inline.normal;
  19518. this.renderer = this.options.renderer || new Renderer;
  19519. this.renderer.options = this.options;
  19520. if (!this.links) {
  19521. throw new
  19522. Error('Tokens array requires a `links` property.');
  19523. }
  19524. if (this.options.gfm) {
  19525. if (this.options.breaks) {
  19526. this.rules = inline.breaks;
  19527. } else {
  19528. this.rules = inline.gfm;
  19529. }
  19530. } else if (this.options.pedantic) {
  19531. this.rules = inline.pedantic;
  19532. }
  19533. }
  19534. /**
  19535. * Expose Inline Rules
  19536. */
  19537. InlineLexer.rules = inline;
  19538. /**
  19539. * Static Lexing/Compiling Method
  19540. */
  19541. InlineLexer.output = function(src, links, options) {
  19542. var inline = new InlineLexer(links, options);
  19543. return inline.output(src);
  19544. };
  19545. /**
  19546. * Lexing/Compiling
  19547. */
  19548. InlineLexer.prototype.output = function(src) {
  19549. var out = ''
  19550. , link
  19551. , text
  19552. , href
  19553. , cap;
  19554. while (src) {
  19555. // escape
  19556. if (cap = this.rules.escape.exec(src)) {
  19557. src = src.substring(cap[0].length);
  19558. out += cap[1];
  19559. continue;
  19560. }
  19561. // autolink
  19562. if (cap = this.rules.autolink.exec(src)) {
  19563. src = src.substring(cap[0].length);
  19564. if (cap[2] === '@') {
  19565. text = cap[1].charAt(6) === ':'
  19566. ? this.mangle(cap[1].substring(7))
  19567. : this.mangle(cap[1]);
  19568. href = this.mangle('mailto:') + text;
  19569. } else {
  19570. text = escape(cap[1]);
  19571. href = text;
  19572. }
  19573. out += this.renderer.link(href, null, text);
  19574. continue;
  19575. }
  19576. // url (gfm)
  19577. if (!this.inLink && (cap = this.rules.url.exec(src))) {
  19578. src = src.substring(cap[0].length);
  19579. text = escape(cap[1]);
  19580. href = text;
  19581. out += this.renderer.link(href, null, text);
  19582. continue;
  19583. }
  19584. // tag
  19585. if (cap = this.rules.tag.exec(src)) {
  19586. if (!this.inLink && /^<a /i.test(cap[0])) {
  19587. this.inLink = true;
  19588. } else if (this.inLink && /^<\/a>/i.test(cap[0])) {
  19589. this.inLink = false;
  19590. }
  19591. src = src.substring(cap[0].length);
  19592. out += this.options.sanitize
  19593. ? this.options.sanitizer
  19594. ? this.options.sanitizer(cap[0])
  19595. : escape(cap[0])
  19596. : cap[0]
  19597. continue;
  19598. }
  19599. // link
  19600. if (cap = this.rules.link.exec(src)) {
  19601. src = src.substring(cap[0].length);
  19602. this.inLink = true;
  19603. out += this.outputLink(cap, {
  19604. href: cap[2],
  19605. title: cap[3]
  19606. });
  19607. this.inLink = false;
  19608. continue;
  19609. }
  19610. // reflink, nolink
  19611. if ((cap = this.rules.reflink.exec(src))
  19612. || (cap = this.rules.nolink.exec(src))) {
  19613. src = src.substring(cap[0].length);
  19614. link = (cap[2] || cap[1]).replace(/\s+/g, ' ');
  19615. link = this.links[link.toLowerCase()];
  19616. if (!link || !link.href) {
  19617. out += cap[0].charAt(0);
  19618. src = cap[0].substring(1) + src;
  19619. continue;
  19620. }
  19621. this.inLink = true;
  19622. out += this.outputLink(cap, link);
  19623. this.inLink = false;
  19624. continue;
  19625. }
  19626. // strong
  19627. if (cap = this.rules.strong.exec(src)) {
  19628. src = src.substring(cap[0].length);
  19629. out += this.renderer.strong(this.output(cap[2] || cap[1]));
  19630. continue;
  19631. }
  19632. // em
  19633. if (cap = this.rules.em.exec(src)) {
  19634. src = src.substring(cap[0].length);
  19635. out += this.renderer.em(this.output(cap[2] || cap[1]));
  19636. continue;
  19637. }
  19638. // code
  19639. if (cap = this.rules.code.exec(src)) {
  19640. src = src.substring(cap[0].length);
  19641. out += this.renderer.codespan(escape(cap[2], true));
  19642. continue;
  19643. }
  19644. // br
  19645. if (cap = this.rules.br.exec(src)) {
  19646. src = src.substring(cap[0].length);
  19647. out += this.renderer.br();
  19648. continue;
  19649. }
  19650. // del (gfm)
  19651. if (cap = this.rules.del.exec(src)) {
  19652. src = src.substring(cap[0].length);
  19653. out += this.renderer.del(this.output(cap[1]));
  19654. continue;
  19655. }
  19656. // text
  19657. if (cap = this.rules.text.exec(src)) {
  19658. src = src.substring(cap[0].length);
  19659. out += this.renderer.text(escape(this.smartypants(cap[0])));
  19660. continue;
  19661. }
  19662. if (src) {
  19663. throw new
  19664. Error('Infinite loop on byte: ' + src.charCodeAt(0));
  19665. }
  19666. }
  19667. return out;
  19668. };
  19669. /**
  19670. * Compile Link
  19671. */
  19672. InlineLexer.prototype.outputLink = function(cap, link) {
  19673. var href = escape(link.href)
  19674. , title = link.title ? escape(link.title) : null;
  19675. return cap[0].charAt(0) !== '!'
  19676. ? this.renderer.link(href, title, this.output(cap[1]))
  19677. : this.renderer.image(href, title, escape(cap[1]));
  19678. };
  19679. /**
  19680. * Smartypants Transformations
  19681. */
  19682. InlineLexer.prototype.smartypants = function(text) {
  19683. if (!this.options.smartypants) return text;
  19684. return text
  19685. // em-dashes
  19686. .replace(/---/g, '\u2014')
  19687. // en-dashes
  19688. .replace(/--/g, '\u2013')
  19689. // opening singles
  19690. .replace(/(^|[-\u2014/(\[{"\s])'/g, '$1\u2018')
  19691. // closing singles & apostrophes
  19692. .replace(/'/g, '\u2019')
  19693. // opening doubles
  19694. .replace(/(^|[-\u2014/(\[{\u2018\s])"/g, '$1\u201c')
  19695. // closing doubles
  19696. .replace(/"/g, '\u201d')
  19697. // ellipses
  19698. .replace(/\.{3}/g, '\u2026');
  19699. };
  19700. /**
  19701. * Mangle Links
  19702. */
  19703. InlineLexer.prototype.mangle = function(text) {
  19704. if (!this.options.mangle) return text;
  19705. var out = ''
  19706. , l = text.length
  19707. , i = 0
  19708. , ch;
  19709. for (; i < l; i++) {
  19710. ch = text.charCodeAt(i);
  19711. if (Math.random() > 0.5) {
  19712. ch = 'x' + ch.toString(16);
  19713. }
  19714. out += '&#' + ch + ';';
  19715. }
  19716. return out;
  19717. };
  19718. /**
  19719. * Renderer
  19720. */
  19721. function Renderer(options) {
  19722. this.options = options || {};
  19723. }
  19724. Renderer.prototype.code = function(code, lang, escaped) {
  19725. if (this.options.highlight) {
  19726. var out = this.options.highlight(code, lang);
  19727. if (out != null && out !== code) {
  19728. escaped = true;
  19729. code = out;
  19730. }
  19731. }
  19732. if (!lang) {
  19733. return '<pre><code>'
  19734. + (escaped ? code : escape(code, true))
  19735. + '\n</code></pre>';
  19736. }
  19737. return '<pre><code class="'
  19738. + this.options.langPrefix
  19739. + escape(lang, true)
  19740. + '">'
  19741. + (escaped ? code : escape(code, true))
  19742. + '\n</code></pre>\n';
  19743. };
  19744. Renderer.prototype.blockquote = function(quote) {
  19745. return '<blockquote>\n' + quote + '</blockquote>\n';
  19746. };
  19747. Renderer.prototype.html = function(html) {
  19748. return html;
  19749. };
  19750. Renderer.prototype.heading = function(text, level, raw) {
  19751. return '<h'
  19752. + level
  19753. + ' id="'
  19754. + this.options.headerPrefix
  19755. + raw.toLowerCase().replace(/[^\w]+/g, '-')
  19756. + '">'
  19757. + text
  19758. + '</h'
  19759. + level
  19760. + '>\n';
  19761. };
  19762. Renderer.prototype.hr = function() {
  19763. return this.options.xhtml ? '<hr/>\n' : '<hr>\n';
  19764. };
  19765. Renderer.prototype.list = function(body, ordered) {
  19766. var type = ordered ? 'ol' : 'ul';
  19767. return '<' + type + '>\n' + body + '</' + type + '>\n';
  19768. };
  19769. Renderer.prototype.listitem = function(text) {
  19770. return '<li>' + text + '</li>\n';
  19771. };
  19772. Renderer.prototype.paragraph = function(text) {
  19773. return '<p>' + text + '</p>\n';
  19774. };
  19775. Renderer.prototype.table = function(header, body) {
  19776. return '<table>\n'
  19777. + '<thead>\n'
  19778. + header
  19779. + '</thead>\n'
  19780. + '<tbody>\n'
  19781. + body
  19782. + '</tbody>\n'
  19783. + '</table>\n';
  19784. };
  19785. Renderer.prototype.tablerow = function(content) {
  19786. return '<tr>\n' + content + '</tr>\n';
  19787. };
  19788. Renderer.prototype.tablecell = function(content, flags) {
  19789. var type = flags.header ? 'th' : 'td';
  19790. var tag = flags.align
  19791. ? '<' + type + ' style="text-align:' + flags.align + '">'
  19792. : '<' + type + '>';
  19793. return tag + content + '</' + type + '>\n';
  19794. };
  19795. // span level renderer
  19796. Renderer.prototype.strong = function(text) {
  19797. return '<strong>' + text + '</strong>';
  19798. };
  19799. Renderer.prototype.em = function(text) {
  19800. return '<em>' + text + '</em>';
  19801. };
  19802. Renderer.prototype.codespan = function(text) {
  19803. return '<code>' + text + '</code>';
  19804. };
  19805. Renderer.prototype.br = function() {
  19806. return this.options.xhtml ? '<br/>' : '<br>';
  19807. };
  19808. Renderer.prototype.del = function(text) {
  19809. return '<del>' + text + '</del>';
  19810. };
  19811. Renderer.prototype.link = function(href, title, text) {
  19812. if (this.options.sanitize) {
  19813. try {
  19814. var prot = decodeURIComponent(unescape(href))
  19815. .replace(/[^\w:]/g, '')
  19816. .toLowerCase();
  19817. } catch (e) {
  19818. return '';
  19819. }
  19820. if (prot.indexOf('javascript:') === 0 || prot.indexOf('vbscript:') === 0 || prot.indexOf('data:') === 0) {
  19821. return '';
  19822. }
  19823. }
  19824. var out = '<a href="' + href + '"';
  19825. if (title) {
  19826. out += ' title="' + title + '"';
  19827. }
  19828. out += '>' + text + '</a>';
  19829. return out;
  19830. };
  19831. Renderer.prototype.image = function(href, title, text) {
  19832. var out = '<img src="' + href + '" alt="' + text + '"';
  19833. if (title) {
  19834. out += ' title="' + title + '"';
  19835. }
  19836. out += this.options.xhtml ? '/>' : '>';
  19837. return out;
  19838. };
  19839. Renderer.prototype.text = function(text) {
  19840. return text;
  19841. };
  19842. /**
  19843. * Parsing & Compiling
  19844. */
  19845. function Parser(options) {
  19846. this.tokens = [];
  19847. this.token = null;
  19848. this.options = options || marked.defaults;
  19849. this.options.renderer = this.options.renderer || new Renderer;
  19850. this.renderer = this.options.renderer;
  19851. this.renderer.options = this.options;
  19852. }
  19853. /**
  19854. * Static Parse Method
  19855. */
  19856. Parser.parse = function(src, options, renderer) {
  19857. var parser = new Parser(options, renderer);
  19858. return parser.parse(src);
  19859. };
  19860. /**
  19861. * Parse Loop
  19862. */
  19863. Parser.prototype.parse = function(src) {
  19864. this.inline = new InlineLexer(src.links, this.options, this.renderer);
  19865. this.tokens = src.reverse();
  19866. var out = '';
  19867. while (this.next()) {
  19868. out += this.tok();
  19869. }
  19870. return out;
  19871. };
  19872. /**
  19873. * Next Token
  19874. */
  19875. Parser.prototype.next = function() {
  19876. return this.token = this.tokens.pop();
  19877. };
  19878. /**
  19879. * Preview Next Token
  19880. */
  19881. Parser.prototype.peek = function() {
  19882. return this.tokens[this.tokens.length - 1] || 0;
  19883. };
  19884. /**
  19885. * Parse Text Tokens
  19886. */
  19887. Parser.prototype.parseText = function() {
  19888. var body = this.token.text;
  19889. while (this.peek().type === 'text') {
  19890. body += '\n' + this.next().text;
  19891. }
  19892. return this.inline.output(body);
  19893. };
  19894. /**
  19895. * Parse Current Token
  19896. */
  19897. Parser.prototype.tok = function() {
  19898. switch (this.token.type) {
  19899. case 'space': {
  19900. return '';
  19901. }
  19902. case 'hr': {
  19903. return this.renderer.hr();
  19904. }
  19905. case 'heading': {
  19906. return this.renderer.heading(
  19907. this.inline.output(this.token.text),
  19908. this.token.depth,
  19909. this.token.text);
  19910. }
  19911. case 'code': {
  19912. return this.renderer.code(this.token.text,
  19913. this.token.lang,
  19914. this.token.escaped);
  19915. }
  19916. case 'table': {
  19917. var header = ''
  19918. , body = ''
  19919. , i
  19920. , row
  19921. , cell
  19922. , flags
  19923. , j;
  19924. // header
  19925. cell = '';
  19926. for (i = 0; i < this.token.header.length; i++) {
  19927. flags = { header: true, align: this.token.align[i] };
  19928. cell += this.renderer.tablecell(
  19929. this.inline.output(this.token.header[i]),
  19930. { header: true, align: this.token.align[i] }
  19931. );
  19932. }
  19933. header += this.renderer.tablerow(cell);
  19934. for (i = 0; i < this.token.cells.length; i++) {
  19935. row = this.token.cells[i];
  19936. cell = '';
  19937. for (j = 0; j < row.length; j++) {
  19938. cell += this.renderer.tablecell(
  19939. this.inline.output(row[j]),
  19940. { header: false, align: this.token.align[j] }
  19941. );
  19942. }
  19943. body += this.renderer.tablerow(cell);
  19944. }
  19945. return this.renderer.table(header, body);
  19946. }
  19947. case 'blockquote_start': {
  19948. var body = '';
  19949. while (this.next().type !== 'blockquote_end') {
  19950. body += this.tok();
  19951. }
  19952. return this.renderer.blockquote(body);
  19953. }
  19954. case 'list_start': {
  19955. var body = ''
  19956. , ordered = this.token.ordered;
  19957. while (this.next().type !== 'list_end') {
  19958. body += this.tok();
  19959. }
  19960. return this.renderer.list(body, ordered);
  19961. }
  19962. case 'list_item_start': {
  19963. var body = '';
  19964. while (this.next().type !== 'list_item_end') {
  19965. body += this.token.type === 'text'
  19966. ? this.parseText()
  19967. : this.tok();
  19968. }
  19969. return this.renderer.listitem(body);
  19970. }
  19971. case 'loose_item_start': {
  19972. var body = '';
  19973. while (this.next().type !== 'list_item_end') {
  19974. body += this.tok();
  19975. }
  19976. return this.renderer.listitem(body);
  19977. }
  19978. case 'html': {
  19979. var html = !this.token.pre && !this.options.pedantic
  19980. ? this.inline.output(this.token.text)
  19981. : this.token.text;
  19982. return this.renderer.html(html);
  19983. }
  19984. case 'paragraph': {
  19985. return this.renderer.paragraph(this.inline.output(this.token.text));
  19986. }
  19987. case 'text': {
  19988. return this.renderer.paragraph(this.parseText());
  19989. }
  19990. }
  19991. };
  19992. /**
  19993. * Helpers
  19994. */
  19995. function escape(html, encode) {
  19996. return html
  19997. .replace(!encode ? /&(?!#?\w+;)/g : /&/g, '&amp;')
  19998. .replace(/</g, '&lt;')
  19999. .replace(/>/g, '&gt;')
  20000. .replace(/"/g, '&quot;')
  20001. .replace(/'/g, '&#39;');
  20002. }
  20003. function unescape(html) {
  20004. // explicitly match decimal, hex, and named HTML entities
  20005. return html.replace(/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/g, function(_, n) {
  20006. n = n.toLowerCase();
  20007. if (n === 'colon') return ':';
  20008. if (n.charAt(0) === '#') {
  20009. return n.charAt(1) === 'x'
  20010. ? String.fromCharCode(parseInt(n.substring(2), 16))
  20011. : String.fromCharCode(+n.substring(1));
  20012. }
  20013. return '';
  20014. });
  20015. }
  20016. function replace(regex, opt) {
  20017. regex = regex.source;
  20018. opt = opt || '';
  20019. return function self(name, val) {
  20020. if (!name) return new RegExp(regex, opt);
  20021. val = val.source || val;
  20022. val = val.replace(/(^|[^\[])\^/g, '$1');
  20023. regex = regex.replace(name, val);
  20024. return self;
  20025. };
  20026. }
  20027. function noop() {}
  20028. noop.exec = noop;
  20029. function merge(obj) {
  20030. var i = 1
  20031. , target
  20032. , key;
  20033. for (; i < arguments.length; i++) {
  20034. target = arguments[i];
  20035. for (key in target) {
  20036. if (Object.prototype.hasOwnProperty.call(target, key)) {
  20037. obj[key] = target[key];
  20038. }
  20039. }
  20040. }
  20041. return obj;
  20042. }
  20043. /**
  20044. * Marked
  20045. */
  20046. function marked(src, opt, callback) {
  20047. if (callback || typeof opt === 'function') {
  20048. if (!callback) {
  20049. callback = opt;
  20050. opt = null;
  20051. }
  20052. opt = merge({}, marked.defaults, opt || {});
  20053. var highlight = opt.highlight
  20054. , tokens
  20055. , pending
  20056. , i = 0;
  20057. try {
  20058. tokens = Lexer.lex(src, opt)
  20059. } catch (e) {
  20060. return callback(e);
  20061. }
  20062. pending = tokens.length;
  20063. var done = function(err) {
  20064. if (err) {
  20065. opt.highlight = highlight;
  20066. return callback(err);
  20067. }
  20068. var out;
  20069. try {
  20070. out = Parser.parse(tokens, opt);
  20071. } catch (e) {
  20072. err = e;
  20073. }
  20074. opt.highlight = highlight;
  20075. return err
  20076. ? callback(err)
  20077. : callback(null, out);
  20078. };
  20079. if (!highlight || highlight.length < 3) {
  20080. return done();
  20081. }
  20082. delete opt.highlight;
  20083. if (!pending) return done();
  20084. for (; i < tokens.length; i++) {
  20085. (function(token) {
  20086. if (token.type !== 'code') {
  20087. return --pending || done();
  20088. }
  20089. return highlight(token.text, token.lang, function(err, code) {
  20090. if (err) return done(err);
  20091. if (code == null || code === token.text) {
  20092. return --pending || done();
  20093. }
  20094. token.text = code;
  20095. token.escaped = true;
  20096. --pending || done();
  20097. });
  20098. })(tokens[i]);
  20099. }
  20100. return;
  20101. }
  20102. try {
  20103. if (opt) opt = merge({}, marked.defaults, opt);
  20104. return Parser.parse(Lexer.lex(src, opt), opt);
  20105. } catch (e) {
  20106. e.message += '\nPlease report this to https://github.com/chjj/marked.';
  20107. if ((opt || marked.defaults).silent) {
  20108. return '<p>An error occured:</p><pre>'
  20109. + escape(e.message + '', true)
  20110. + '</pre>';
  20111. }
  20112. throw e;
  20113. }
  20114. }
  20115. /**
  20116. * Options
  20117. */
  20118. marked.options =
  20119. marked.setOptions = function(opt) {
  20120. merge(marked.defaults, opt);
  20121. return marked;
  20122. };
  20123. marked.defaults = {
  20124. gfm: true,
  20125. tables: true,
  20126. breaks: false,
  20127. pedantic: false,
  20128. sanitize: false,
  20129. sanitizer: null,
  20130. mangle: true,
  20131. smartLists: false,
  20132. silent: false,
  20133. highlight: null,
  20134. langPrefix: 'lang-',
  20135. smartypants: false,
  20136. headerPrefix: '',
  20137. renderer: new Renderer,
  20138. xhtml: false
  20139. };
  20140. /**
  20141. * Expose
  20142. */
  20143. marked.Parser = Parser;
  20144. marked.parser = Parser.parse;
  20145. marked.Renderer = Renderer;
  20146. marked.Lexer = Lexer;
  20147. marked.lexer = Lexer.lex;
  20148. marked.InlineLexer = InlineLexer;
  20149. marked.inlineLexer = InlineLexer.output;
  20150. marked.parse = marked;
  20151. if (true) {
  20152. module.exports = marked;
  20153. } else if (typeof define === 'function' && define.amd) {
  20154. define(function() { return marked; });
  20155. } else {
  20156. this.marked = marked;
  20157. }
  20158. }).call(function() {
  20159. return this || (typeof window !== 'undefined' ? window : global);
  20160. }());
  20161. /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }())))
  20162. /***/ })
  20163. /******/ ])
  20164. });
  20165. ;
  20166. //# sourceMappingURL=react-simplemde-editor.min.js.map