simplemde.js 601 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037
  1. /**
  2. * safe-simplemde v0.1.0
  3. * Copyright
  4. * @link https://github.com/wrnice/safe-simplemde
  5. * @license MIT
  6. */
  7. (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.SimpleMDE = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
  8. 'use strict'
  9. exports.byteLength = byteLength
  10. exports.toByteArray = toByteArray
  11. exports.fromByteArray = fromByteArray
  12. var lookup = []
  13. var revLookup = []
  14. var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
  15. var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
  16. for (var i = 0, len = code.length; i < len; ++i) {
  17. lookup[i] = code[i]
  18. revLookup[code.charCodeAt(i)] = i
  19. }
  20. revLookup['-'.charCodeAt(0)] = 62
  21. revLookup['_'.charCodeAt(0)] = 63
  22. function placeHoldersCount (b64) {
  23. var len = b64.length
  24. if (len % 4 > 0) {
  25. throw new Error('Invalid string. Length must be a multiple of 4')
  26. }
  27. // the number of equal signs (place holders)
  28. // if there are two placeholders, than the two characters before it
  29. // represent one byte
  30. // if there is only one, then the three characters before it represent 2 bytes
  31. // this is just a cheap hack to not do indexOf twice
  32. return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0
  33. }
  34. function byteLength (b64) {
  35. // base64 is 4/3 + up to two characters of the original data
  36. return (b64.length * 3 / 4) - placeHoldersCount(b64)
  37. }
  38. function toByteArray (b64) {
  39. var i, l, tmp, placeHolders, arr
  40. var len = b64.length
  41. placeHolders = placeHoldersCount(b64)
  42. arr = new Arr((len * 3 / 4) - placeHolders)
  43. // if there are placeholders, only get up to the last complete 4 chars
  44. l = placeHolders > 0 ? len - 4 : len
  45. var L = 0
  46. for (i = 0; i < l; i += 4) {
  47. tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]
  48. arr[L++] = (tmp >> 16) & 0xFF
  49. arr[L++] = (tmp >> 8) & 0xFF
  50. arr[L++] = tmp & 0xFF
  51. }
  52. if (placeHolders === 2) {
  53. tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4)
  54. arr[L++] = tmp & 0xFF
  55. } else if (placeHolders === 1) {
  56. tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2)
  57. arr[L++] = (tmp >> 8) & 0xFF
  58. arr[L++] = tmp & 0xFF
  59. }
  60. return arr
  61. }
  62. function tripletToBase64 (num) {
  63. return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]
  64. }
  65. function encodeChunk (uint8, start, end) {
  66. var tmp
  67. var output = []
  68. for (var i = start; i < end; i += 3) {
  69. tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2])
  70. output.push(tripletToBase64(tmp))
  71. }
  72. return output.join('')
  73. }
  74. function fromByteArray (uint8) {
  75. var tmp
  76. var len = uint8.length
  77. var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
  78. var output = ''
  79. var parts = []
  80. var maxChunkLength = 16383 // must be multiple of 3
  81. // go through the array every three bytes, we'll deal with trailing stuff later
  82. for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
  83. parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))
  84. }
  85. // pad the end with zeros, but make sure to not forget the extra bytes
  86. if (extraBytes === 1) {
  87. tmp = uint8[len - 1]
  88. output += lookup[tmp >> 2]
  89. output += lookup[(tmp << 4) & 0x3F]
  90. output += '=='
  91. } else if (extraBytes === 2) {
  92. tmp = (uint8[len - 2] << 8) + (uint8[len - 1])
  93. output += lookup[tmp >> 10]
  94. output += lookup[(tmp >> 4) & 0x3F]
  95. output += lookup[(tmp << 2) & 0x3F]
  96. output += '='
  97. }
  98. parts.push(output)
  99. return parts.join('')
  100. }
  101. },{}],2:[function(require,module,exports){
  102. },{}],3:[function(require,module,exports){
  103. /*!
  104. * The buffer module from node.js, for the browser.
  105. *
  106. * @author Feross Aboukhadijeh <https://feross.org>
  107. * @license MIT
  108. */
  109. /* eslint-disable no-proto */
  110. 'use strict'
  111. var base64 = require('base64-js')
  112. var ieee754 = require('ieee754')
  113. exports.Buffer = Buffer
  114. exports.SlowBuffer = SlowBuffer
  115. exports.INSPECT_MAX_BYTES = 50
  116. var K_MAX_LENGTH = 0x7fffffff
  117. exports.kMaxLength = K_MAX_LENGTH
  118. /**
  119. * If `Buffer.TYPED_ARRAY_SUPPORT`:
  120. * === true Use Uint8Array implementation (fastest)
  121. * === false Print warning and recommend using `buffer` v4.x which has an Object
  122. * implementation (most compatible, even IE6)
  123. *
  124. * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
  125. * Opera 11.6+, iOS 4.2+.
  126. *
  127. * We report that the browser does not support typed arrays if the are not subclassable
  128. * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
  129. * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
  130. * for __proto__ and has a buggy typed array implementation.
  131. */
  132. Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport()
  133. if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&
  134. typeof console.error === 'function') {
  135. console.error(
  136. 'This browser lacks typed array (Uint8Array) support which is required by ' +
  137. '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'
  138. )
  139. }
  140. function typedArraySupport () {
  141. // Can typed array instances can be augmented?
  142. try {
  143. var arr = new Uint8Array(1)
  144. arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }}
  145. return arr.foo() === 42
  146. } catch (e) {
  147. return false
  148. }
  149. }
  150. function createBuffer (length) {
  151. if (length > K_MAX_LENGTH) {
  152. throw new RangeError('Invalid typed array length')
  153. }
  154. // Return an augmented `Uint8Array` instance
  155. var buf = new Uint8Array(length)
  156. buf.__proto__ = Buffer.prototype
  157. return buf
  158. }
  159. /**
  160. * The Buffer constructor returns instances of `Uint8Array` that have their
  161. * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
  162. * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
  163. * and the `Uint8Array` methods. Square bracket notation works as expected -- it
  164. * returns a single octet.
  165. *
  166. * The `Uint8Array` prototype remains unmodified.
  167. */
  168. function Buffer (arg, encodingOrOffset, length) {
  169. // Common case.
  170. if (typeof arg === 'number') {
  171. if (typeof encodingOrOffset === 'string') {
  172. throw new Error(
  173. 'If encoding is specified then the first argument must be a string'
  174. )
  175. }
  176. return allocUnsafe(arg)
  177. }
  178. return from(arg, encodingOrOffset, length)
  179. }
  180. // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
  181. if (typeof Symbol !== 'undefined' && Symbol.species &&
  182. Buffer[Symbol.species] === Buffer) {
  183. Object.defineProperty(Buffer, Symbol.species, {
  184. value: null,
  185. configurable: true,
  186. enumerable: false,
  187. writable: false
  188. })
  189. }
  190. Buffer.poolSize = 8192 // not used by this implementation
  191. function from (value, encodingOrOffset, length) {
  192. if (typeof value === 'number') {
  193. throw new TypeError('"value" argument must not be a number')
  194. }
  195. if (isArrayBuffer(value)) {
  196. return fromArrayBuffer(value, encodingOrOffset, length)
  197. }
  198. if (typeof value === 'string') {
  199. return fromString(value, encodingOrOffset)
  200. }
  201. return fromObject(value)
  202. }
  203. /**
  204. * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
  205. * if value is a number.
  206. * Buffer.from(str[, encoding])
  207. * Buffer.from(array)
  208. * Buffer.from(buffer)
  209. * Buffer.from(arrayBuffer[, byteOffset[, length]])
  210. **/
  211. Buffer.from = function (value, encodingOrOffset, length) {
  212. return from(value, encodingOrOffset, length)
  213. }
  214. // Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
  215. // https://github.com/feross/buffer/pull/148
  216. Buffer.prototype.__proto__ = Uint8Array.prototype
  217. Buffer.__proto__ = Uint8Array
  218. function assertSize (size) {
  219. if (typeof size !== 'number') {
  220. throw new TypeError('"size" argument must be a number')
  221. } else if (size < 0) {
  222. throw new RangeError('"size" argument must not be negative')
  223. }
  224. }
  225. function alloc (size, fill, encoding) {
  226. assertSize(size)
  227. if (size <= 0) {
  228. return createBuffer(size)
  229. }
  230. if (fill !== undefined) {
  231. // Only pay attention to encoding if it's a string. This
  232. // prevents accidentally sending in a number that would
  233. // be interpretted as a start offset.
  234. return typeof encoding === 'string'
  235. ? createBuffer(size).fill(fill, encoding)
  236. : createBuffer(size).fill(fill)
  237. }
  238. return createBuffer(size)
  239. }
  240. /**
  241. * Creates a new filled Buffer instance.
  242. * alloc(size[, fill[, encoding]])
  243. **/
  244. Buffer.alloc = function (size, fill, encoding) {
  245. return alloc(size, fill, encoding)
  246. }
  247. function allocUnsafe (size) {
  248. assertSize(size)
  249. return createBuffer(size < 0 ? 0 : checked(size) | 0)
  250. }
  251. /**
  252. * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
  253. * */
  254. Buffer.allocUnsafe = function (size) {
  255. return allocUnsafe(size)
  256. }
  257. /**
  258. * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
  259. */
  260. Buffer.allocUnsafeSlow = function (size) {
  261. return allocUnsafe(size)
  262. }
  263. function fromString (string, encoding) {
  264. if (typeof encoding !== 'string' || encoding === '') {
  265. encoding = 'utf8'
  266. }
  267. if (!Buffer.isEncoding(encoding)) {
  268. throw new TypeError('"encoding" must be a valid string encoding')
  269. }
  270. var length = byteLength(string, encoding) | 0
  271. var buf = createBuffer(length)
  272. var actual = buf.write(string, encoding)
  273. if (actual !== length) {
  274. // Writing a hex string, for example, that contains invalid characters will
  275. // cause everything after the first invalid character to be ignored. (e.g.
  276. // 'abxxcd' will be treated as 'ab')
  277. buf = buf.slice(0, actual)
  278. }
  279. return buf
  280. }
  281. function fromArrayLike (array) {
  282. var length = array.length < 0 ? 0 : checked(array.length) | 0
  283. var buf = createBuffer(length)
  284. for (var i = 0; i < length; i += 1) {
  285. buf[i] = array[i] & 255
  286. }
  287. return buf
  288. }
  289. function fromArrayBuffer (array, byteOffset, length) {
  290. if (byteOffset < 0 || array.byteLength < byteOffset) {
  291. throw new RangeError('\'offset\' is out of bounds')
  292. }
  293. if (array.byteLength < byteOffset + (length || 0)) {
  294. throw new RangeError('\'length\' is out of bounds')
  295. }
  296. var buf
  297. if (byteOffset === undefined && length === undefined) {
  298. buf = new Uint8Array(array)
  299. } else if (length === undefined) {
  300. buf = new Uint8Array(array, byteOffset)
  301. } else {
  302. buf = new Uint8Array(array, byteOffset, length)
  303. }
  304. // Return an augmented `Uint8Array` instance
  305. buf.__proto__ = Buffer.prototype
  306. return buf
  307. }
  308. function fromObject (obj) {
  309. if (Buffer.isBuffer(obj)) {
  310. var len = checked(obj.length) | 0
  311. var buf = createBuffer(len)
  312. if (buf.length === 0) {
  313. return buf
  314. }
  315. obj.copy(buf, 0, 0, len)
  316. return buf
  317. }
  318. if (obj) {
  319. if (isArrayBufferView(obj) || 'length' in obj) {
  320. if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
  321. return createBuffer(0)
  322. }
  323. return fromArrayLike(obj)
  324. }
  325. if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
  326. return fromArrayLike(obj.data)
  327. }
  328. }
  329. throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')
  330. }
  331. function checked (length) {
  332. // Note: cannot use `length < K_MAX_LENGTH` here because that fails when
  333. // length is NaN (which is otherwise coerced to zero.)
  334. if (length >= K_MAX_LENGTH) {
  335. throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
  336. 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')
  337. }
  338. return length | 0
  339. }
  340. function SlowBuffer (length) {
  341. if (+length != length) { // eslint-disable-line eqeqeq
  342. length = 0
  343. }
  344. return Buffer.alloc(+length)
  345. }
  346. Buffer.isBuffer = function isBuffer (b) {
  347. return b != null && b._isBuffer === true
  348. }
  349. Buffer.compare = function compare (a, b) {
  350. if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
  351. throw new TypeError('Arguments must be Buffers')
  352. }
  353. if (a === b) return 0
  354. var x = a.length
  355. var y = b.length
  356. for (var i = 0, len = Math.min(x, y); i < len; ++i) {
  357. if (a[i] !== b[i]) {
  358. x = a[i]
  359. y = b[i]
  360. break
  361. }
  362. }
  363. if (x < y) return -1
  364. if (y < x) return 1
  365. return 0
  366. }
  367. Buffer.isEncoding = function isEncoding (encoding) {
  368. switch (String(encoding).toLowerCase()) {
  369. case 'hex':
  370. case 'utf8':
  371. case 'utf-8':
  372. case 'ascii':
  373. case 'latin1':
  374. case 'binary':
  375. case 'base64':
  376. case 'ucs2':
  377. case 'ucs-2':
  378. case 'utf16le':
  379. case 'utf-16le':
  380. return true
  381. default:
  382. return false
  383. }
  384. }
  385. Buffer.concat = function concat (list, length) {
  386. if (!Array.isArray(list)) {
  387. throw new TypeError('"list" argument must be an Array of Buffers')
  388. }
  389. if (list.length === 0) {
  390. return Buffer.alloc(0)
  391. }
  392. var i
  393. if (length === undefined) {
  394. length = 0
  395. for (i = 0; i < list.length; ++i) {
  396. length += list[i].length
  397. }
  398. }
  399. var buffer = Buffer.allocUnsafe(length)
  400. var pos = 0
  401. for (i = 0; i < list.length; ++i) {
  402. var buf = list[i]
  403. if (!Buffer.isBuffer(buf)) {
  404. throw new TypeError('"list" argument must be an Array of Buffers')
  405. }
  406. buf.copy(buffer, pos)
  407. pos += buf.length
  408. }
  409. return buffer
  410. }
  411. function byteLength (string, encoding) {
  412. if (Buffer.isBuffer(string)) {
  413. return string.length
  414. }
  415. if (isArrayBufferView(string) || isArrayBuffer(string)) {
  416. return string.byteLength
  417. }
  418. if (typeof string !== 'string') {
  419. string = '' + string
  420. }
  421. var len = string.length
  422. if (len === 0) return 0
  423. // Use a for loop to avoid recursion
  424. var loweredCase = false
  425. for (;;) {
  426. switch (encoding) {
  427. case 'ascii':
  428. case 'latin1':
  429. case 'binary':
  430. return len
  431. case 'utf8':
  432. case 'utf-8':
  433. case undefined:
  434. return utf8ToBytes(string).length
  435. case 'ucs2':
  436. case 'ucs-2':
  437. case 'utf16le':
  438. case 'utf-16le':
  439. return len * 2
  440. case 'hex':
  441. return len >>> 1
  442. case 'base64':
  443. return base64ToBytes(string).length
  444. default:
  445. if (loweredCase) return utf8ToBytes(string).length // assume utf8
  446. encoding = ('' + encoding).toLowerCase()
  447. loweredCase = true
  448. }
  449. }
  450. }
  451. Buffer.byteLength = byteLength
  452. function slowToString (encoding, start, end) {
  453. var loweredCase = false
  454. // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
  455. // property of a typed array.
  456. // This behaves neither like String nor Uint8Array in that we set start/end
  457. // to their upper/lower bounds if the value passed is out of range.
  458. // undefined is handled specially as per ECMA-262 6th Edition,
  459. // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
  460. if (start === undefined || start < 0) {
  461. start = 0
  462. }
  463. // Return early if start > this.length. Done here to prevent potential uint32
  464. // coercion fail below.
  465. if (start > this.length) {
  466. return ''
  467. }
  468. if (end === undefined || end > this.length) {
  469. end = this.length
  470. }
  471. if (end <= 0) {
  472. return ''
  473. }
  474. // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
  475. end >>>= 0
  476. start >>>= 0
  477. if (end <= start) {
  478. return ''
  479. }
  480. if (!encoding) encoding = 'utf8'
  481. while (true) {
  482. switch (encoding) {
  483. case 'hex':
  484. return hexSlice(this, start, end)
  485. case 'utf8':
  486. case 'utf-8':
  487. return utf8Slice(this, start, end)
  488. case 'ascii':
  489. return asciiSlice(this, start, end)
  490. case 'latin1':
  491. case 'binary':
  492. return latin1Slice(this, start, end)
  493. case 'base64':
  494. return base64Slice(this, start, end)
  495. case 'ucs2':
  496. case 'ucs-2':
  497. case 'utf16le':
  498. case 'utf-16le':
  499. return utf16leSlice(this, start, end)
  500. default:
  501. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  502. encoding = (encoding + '').toLowerCase()
  503. loweredCase = true
  504. }
  505. }
  506. }
  507. // This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
  508. // to detect a Buffer instance. It's not possible to use `instanceof Buffer`
  509. // reliably in a browserify context because there could be multiple different
  510. // copies of the 'buffer' package in use. This method works even for Buffer
  511. // instances that were created from another copy of the `buffer` package.
  512. // See: https://github.com/feross/buffer/issues/154
  513. Buffer.prototype._isBuffer = true
  514. function swap (b, n, m) {
  515. var i = b[n]
  516. b[n] = b[m]
  517. b[m] = i
  518. }
  519. Buffer.prototype.swap16 = function swap16 () {
  520. var len = this.length
  521. if (len % 2 !== 0) {
  522. throw new RangeError('Buffer size must be a multiple of 16-bits')
  523. }
  524. for (var i = 0; i < len; i += 2) {
  525. swap(this, i, i + 1)
  526. }
  527. return this
  528. }
  529. Buffer.prototype.swap32 = function swap32 () {
  530. var len = this.length
  531. if (len % 4 !== 0) {
  532. throw new RangeError('Buffer size must be a multiple of 32-bits')
  533. }
  534. for (var i = 0; i < len; i += 4) {
  535. swap(this, i, i + 3)
  536. swap(this, i + 1, i + 2)
  537. }
  538. return this
  539. }
  540. Buffer.prototype.swap64 = function swap64 () {
  541. var len = this.length
  542. if (len % 8 !== 0) {
  543. throw new RangeError('Buffer size must be a multiple of 64-bits')
  544. }
  545. for (var i = 0; i < len; i += 8) {
  546. swap(this, i, i + 7)
  547. swap(this, i + 1, i + 6)
  548. swap(this, i + 2, i + 5)
  549. swap(this, i + 3, i + 4)
  550. }
  551. return this
  552. }
  553. Buffer.prototype.toString = function toString () {
  554. var length = this.length
  555. if (length === 0) return ''
  556. if (arguments.length === 0) return utf8Slice(this, 0, length)
  557. return slowToString.apply(this, arguments)
  558. }
  559. Buffer.prototype.equals = function equals (b) {
  560. if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
  561. if (this === b) return true
  562. return Buffer.compare(this, b) === 0
  563. }
  564. Buffer.prototype.inspect = function inspect () {
  565. var str = ''
  566. var max = exports.INSPECT_MAX_BYTES
  567. if (this.length > 0) {
  568. str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')
  569. if (this.length > max) str += ' ... '
  570. }
  571. return '<Buffer ' + str + '>'
  572. }
  573. Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
  574. if (!Buffer.isBuffer(target)) {
  575. throw new TypeError('Argument must be a Buffer')
  576. }
  577. if (start === undefined) {
  578. start = 0
  579. }
  580. if (end === undefined) {
  581. end = target ? target.length : 0
  582. }
  583. if (thisStart === undefined) {
  584. thisStart = 0
  585. }
  586. if (thisEnd === undefined) {
  587. thisEnd = this.length
  588. }
  589. if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
  590. throw new RangeError('out of range index')
  591. }
  592. if (thisStart >= thisEnd && start >= end) {
  593. return 0
  594. }
  595. if (thisStart >= thisEnd) {
  596. return -1
  597. }
  598. if (start >= end) {
  599. return 1
  600. }
  601. start >>>= 0
  602. end >>>= 0
  603. thisStart >>>= 0
  604. thisEnd >>>= 0
  605. if (this === target) return 0
  606. var x = thisEnd - thisStart
  607. var y = end - start
  608. var len = Math.min(x, y)
  609. var thisCopy = this.slice(thisStart, thisEnd)
  610. var targetCopy = target.slice(start, end)
  611. for (var i = 0; i < len; ++i) {
  612. if (thisCopy[i] !== targetCopy[i]) {
  613. x = thisCopy[i]
  614. y = targetCopy[i]
  615. break
  616. }
  617. }
  618. if (x < y) return -1
  619. if (y < x) return 1
  620. return 0
  621. }
  622. // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
  623. // OR the last index of `val` in `buffer` at offset <= `byteOffset`.
  624. //
  625. // Arguments:
  626. // - buffer - a Buffer to search
  627. // - val - a string, Buffer, or number
  628. // - byteOffset - an index into `buffer`; will be clamped to an int32
  629. // - encoding - an optional encoding, relevant is val is a string
  630. // - dir - true for indexOf, false for lastIndexOf
  631. function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
  632. // Empty buffer means no match
  633. if (buffer.length === 0) return -1
  634. // Normalize byteOffset
  635. if (typeof byteOffset === 'string') {
  636. encoding = byteOffset
  637. byteOffset = 0
  638. } else if (byteOffset > 0x7fffffff) {
  639. byteOffset = 0x7fffffff
  640. } else if (byteOffset < -0x80000000) {
  641. byteOffset = -0x80000000
  642. }
  643. byteOffset = +byteOffset // Coerce to Number.
  644. if (numberIsNaN(byteOffset)) {
  645. // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
  646. byteOffset = dir ? 0 : (buffer.length - 1)
  647. }
  648. // Normalize byteOffset: negative offsets start from the end of the buffer
  649. if (byteOffset < 0) byteOffset = buffer.length + byteOffset
  650. if (byteOffset >= buffer.length) {
  651. if (dir) return -1
  652. else byteOffset = buffer.length - 1
  653. } else if (byteOffset < 0) {
  654. if (dir) byteOffset = 0
  655. else return -1
  656. }
  657. // Normalize val
  658. if (typeof val === 'string') {
  659. val = Buffer.from(val, encoding)
  660. }
  661. // Finally, search either indexOf (if dir is true) or lastIndexOf
  662. if (Buffer.isBuffer(val)) {
  663. // Special case: looking for empty string/buffer always fails
  664. if (val.length === 0) {
  665. return -1
  666. }
  667. return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
  668. } else if (typeof val === 'number') {
  669. val = val & 0xFF // Search for a byte value [0-255]
  670. if (typeof Uint8Array.prototype.indexOf === 'function') {
  671. if (dir) {
  672. return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
  673. } else {
  674. return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
  675. }
  676. }
  677. return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
  678. }
  679. throw new TypeError('val must be string, number or Buffer')
  680. }
  681. function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
  682. var indexSize = 1
  683. var arrLength = arr.length
  684. var valLength = val.length
  685. if (encoding !== undefined) {
  686. encoding = String(encoding).toLowerCase()
  687. if (encoding === 'ucs2' || encoding === 'ucs-2' ||
  688. encoding === 'utf16le' || encoding === 'utf-16le') {
  689. if (arr.length < 2 || val.length < 2) {
  690. return -1
  691. }
  692. indexSize = 2
  693. arrLength /= 2
  694. valLength /= 2
  695. byteOffset /= 2
  696. }
  697. }
  698. function read (buf, i) {
  699. if (indexSize === 1) {
  700. return buf[i]
  701. } else {
  702. return buf.readUInt16BE(i * indexSize)
  703. }
  704. }
  705. var i
  706. if (dir) {
  707. var foundIndex = -1
  708. for (i = byteOffset; i < arrLength; i++) {
  709. if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
  710. if (foundIndex === -1) foundIndex = i
  711. if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
  712. } else {
  713. if (foundIndex !== -1) i -= i - foundIndex
  714. foundIndex = -1
  715. }
  716. }
  717. } else {
  718. if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
  719. for (i = byteOffset; i >= 0; i--) {
  720. var found = true
  721. for (var j = 0; j < valLength; j++) {
  722. if (read(arr, i + j) !== read(val, j)) {
  723. found = false
  724. break
  725. }
  726. }
  727. if (found) return i
  728. }
  729. }
  730. return -1
  731. }
  732. Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
  733. return this.indexOf(val, byteOffset, encoding) !== -1
  734. }
  735. Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
  736. return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
  737. }
  738. Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
  739. return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
  740. }
  741. function hexWrite (buf, string, offset, length) {
  742. offset = Number(offset) || 0
  743. var remaining = buf.length - offset
  744. if (!length) {
  745. length = remaining
  746. } else {
  747. length = Number(length)
  748. if (length > remaining) {
  749. length = remaining
  750. }
  751. }
  752. // must be an even number of digits
  753. var strLen = string.length
  754. if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')
  755. if (length > strLen / 2) {
  756. length = strLen / 2
  757. }
  758. for (var i = 0; i < length; ++i) {
  759. var parsed = parseInt(string.substr(i * 2, 2), 16)
  760. if (numberIsNaN(parsed)) return i
  761. buf[offset + i] = parsed
  762. }
  763. return i
  764. }
  765. function utf8Write (buf, string, offset, length) {
  766. return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
  767. }
  768. function asciiWrite (buf, string, offset, length) {
  769. return blitBuffer(asciiToBytes(string), buf, offset, length)
  770. }
  771. function latin1Write (buf, string, offset, length) {
  772. return asciiWrite(buf, string, offset, length)
  773. }
  774. function base64Write (buf, string, offset, length) {
  775. return blitBuffer(base64ToBytes(string), buf, offset, length)
  776. }
  777. function ucs2Write (buf, string, offset, length) {
  778. return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
  779. }
  780. Buffer.prototype.write = function write (string, offset, length, encoding) {
  781. // Buffer#write(string)
  782. if (offset === undefined) {
  783. encoding = 'utf8'
  784. length = this.length
  785. offset = 0
  786. // Buffer#write(string, encoding)
  787. } else if (length === undefined && typeof offset === 'string') {
  788. encoding = offset
  789. length = this.length
  790. offset = 0
  791. // Buffer#write(string, offset[, length][, encoding])
  792. } else if (isFinite(offset)) {
  793. offset = offset >>> 0
  794. if (isFinite(length)) {
  795. length = length >>> 0
  796. if (encoding === undefined) encoding = 'utf8'
  797. } else {
  798. encoding = length
  799. length = undefined
  800. }
  801. } else {
  802. throw new Error(
  803. 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
  804. )
  805. }
  806. var remaining = this.length - offset
  807. if (length === undefined || length > remaining) length = remaining
  808. if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
  809. throw new RangeError('Attempt to write outside buffer bounds')
  810. }
  811. if (!encoding) encoding = 'utf8'
  812. var loweredCase = false
  813. for (;;) {
  814. switch (encoding) {
  815. case 'hex':
  816. return hexWrite(this, string, offset, length)
  817. case 'utf8':
  818. case 'utf-8':
  819. return utf8Write(this, string, offset, length)
  820. case 'ascii':
  821. return asciiWrite(this, string, offset, length)
  822. case 'latin1':
  823. case 'binary':
  824. return latin1Write(this, string, offset, length)
  825. case 'base64':
  826. // Warning: maxLength not taken into account in base64Write
  827. return base64Write(this, string, offset, length)
  828. case 'ucs2':
  829. case 'ucs-2':
  830. case 'utf16le':
  831. case 'utf-16le':
  832. return ucs2Write(this, string, offset, length)
  833. default:
  834. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  835. encoding = ('' + encoding).toLowerCase()
  836. loweredCase = true
  837. }
  838. }
  839. }
  840. Buffer.prototype.toJSON = function toJSON () {
  841. return {
  842. type: 'Buffer',
  843. data: Array.prototype.slice.call(this._arr || this, 0)
  844. }
  845. }
  846. function base64Slice (buf, start, end) {
  847. if (start === 0 && end === buf.length) {
  848. return base64.fromByteArray(buf)
  849. } else {
  850. return base64.fromByteArray(buf.slice(start, end))
  851. }
  852. }
  853. function utf8Slice (buf, start, end) {
  854. end = Math.min(buf.length, end)
  855. var res = []
  856. var i = start
  857. while (i < end) {
  858. var firstByte = buf[i]
  859. var codePoint = null
  860. var bytesPerSequence = (firstByte > 0xEF) ? 4
  861. : (firstByte > 0xDF) ? 3
  862. : (firstByte > 0xBF) ? 2
  863. : 1
  864. if (i + bytesPerSequence <= end) {
  865. var secondByte, thirdByte, fourthByte, tempCodePoint
  866. switch (bytesPerSequence) {
  867. case 1:
  868. if (firstByte < 0x80) {
  869. codePoint = firstByte
  870. }
  871. break
  872. case 2:
  873. secondByte = buf[i + 1]
  874. if ((secondByte & 0xC0) === 0x80) {
  875. tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
  876. if (tempCodePoint > 0x7F) {
  877. codePoint = tempCodePoint
  878. }
  879. }
  880. break
  881. case 3:
  882. secondByte = buf[i + 1]
  883. thirdByte = buf[i + 2]
  884. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
  885. tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
  886. if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
  887. codePoint = tempCodePoint
  888. }
  889. }
  890. break
  891. case 4:
  892. secondByte = buf[i + 1]
  893. thirdByte = buf[i + 2]
  894. fourthByte = buf[i + 3]
  895. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
  896. tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
  897. if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
  898. codePoint = tempCodePoint
  899. }
  900. }
  901. }
  902. }
  903. if (codePoint === null) {
  904. // we did not generate a valid codePoint so insert a
  905. // replacement char (U+FFFD) and advance only 1 byte
  906. codePoint = 0xFFFD
  907. bytesPerSequence = 1
  908. } else if (codePoint > 0xFFFF) {
  909. // encode to utf16 (surrogate pair dance)
  910. codePoint -= 0x10000
  911. res.push(codePoint >>> 10 & 0x3FF | 0xD800)
  912. codePoint = 0xDC00 | codePoint & 0x3FF
  913. }
  914. res.push(codePoint)
  915. i += bytesPerSequence
  916. }
  917. return decodeCodePointsArray(res)
  918. }
  919. // Based on http://stackoverflow.com/a/22747272/680742, the browser with
  920. // the lowest limit is Chrome, with 0x10000 args.
  921. // We go 1 magnitude less, for safety
  922. var MAX_ARGUMENTS_LENGTH = 0x1000
  923. function decodeCodePointsArray (codePoints) {
  924. var len = codePoints.length
  925. if (len <= MAX_ARGUMENTS_LENGTH) {
  926. return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
  927. }
  928. // Decode in chunks to avoid "call stack size exceeded".
  929. var res = ''
  930. var i = 0
  931. while (i < len) {
  932. res += String.fromCharCode.apply(
  933. String,
  934. codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
  935. )
  936. }
  937. return res
  938. }
  939. function asciiSlice (buf, start, end) {
  940. var ret = ''
  941. end = Math.min(buf.length, end)
  942. for (var i = start; i < end; ++i) {
  943. ret += String.fromCharCode(buf[i] & 0x7F)
  944. }
  945. return ret
  946. }
  947. function latin1Slice (buf, start, end) {
  948. var ret = ''
  949. end = Math.min(buf.length, end)
  950. for (var i = start; i < end; ++i) {
  951. ret += String.fromCharCode(buf[i])
  952. }
  953. return ret
  954. }
  955. function hexSlice (buf, start, end) {
  956. var len = buf.length
  957. if (!start || start < 0) start = 0
  958. if (!end || end < 0 || end > len) end = len
  959. var out = ''
  960. for (var i = start; i < end; ++i) {
  961. out += toHex(buf[i])
  962. }
  963. return out
  964. }
  965. function utf16leSlice (buf, start, end) {
  966. var bytes = buf.slice(start, end)
  967. var res = ''
  968. for (var i = 0; i < bytes.length; i += 2) {
  969. res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))
  970. }
  971. return res
  972. }
  973. Buffer.prototype.slice = function slice (start, end) {
  974. var len = this.length
  975. start = ~~start
  976. end = end === undefined ? len : ~~end
  977. if (start < 0) {
  978. start += len
  979. if (start < 0) start = 0
  980. } else if (start > len) {
  981. start = len
  982. }
  983. if (end < 0) {
  984. end += len
  985. if (end < 0) end = 0
  986. } else if (end > len) {
  987. end = len
  988. }
  989. if (end < start) end = start
  990. var newBuf = this.subarray(start, end)
  991. // Return an augmented `Uint8Array` instance
  992. newBuf.__proto__ = Buffer.prototype
  993. return newBuf
  994. }
  995. /*
  996. * Need to make sure that buffer isn't trying to write out of bounds.
  997. */
  998. function checkOffset (offset, ext, length) {
  999. if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
  1000. if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
  1001. }
  1002. Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
  1003. offset = offset >>> 0
  1004. byteLength = byteLength >>> 0
  1005. if (!noAssert) checkOffset(offset, byteLength, this.length)
  1006. var val = this[offset]
  1007. var mul = 1
  1008. var i = 0
  1009. while (++i < byteLength && (mul *= 0x100)) {
  1010. val += this[offset + i] * mul
  1011. }
  1012. return val
  1013. }
  1014. Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
  1015. offset = offset >>> 0
  1016. byteLength = byteLength >>> 0
  1017. if (!noAssert) {
  1018. checkOffset(offset, byteLength, this.length)
  1019. }
  1020. var val = this[offset + --byteLength]
  1021. var mul = 1
  1022. while (byteLength > 0 && (mul *= 0x100)) {
  1023. val += this[offset + --byteLength] * mul
  1024. }
  1025. return val
  1026. }
  1027. Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
  1028. offset = offset >>> 0
  1029. if (!noAssert) checkOffset(offset, 1, this.length)
  1030. return this[offset]
  1031. }
  1032. Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
  1033. offset = offset >>> 0
  1034. if (!noAssert) checkOffset(offset, 2, this.length)
  1035. return this[offset] | (this[offset + 1] << 8)
  1036. }
  1037. Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
  1038. offset = offset >>> 0
  1039. if (!noAssert) checkOffset(offset, 2, this.length)
  1040. return (this[offset] << 8) | this[offset + 1]
  1041. }
  1042. Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
  1043. offset = offset >>> 0
  1044. if (!noAssert) checkOffset(offset, 4, this.length)
  1045. return ((this[offset]) |
  1046. (this[offset + 1] << 8) |
  1047. (this[offset + 2] << 16)) +
  1048. (this[offset + 3] * 0x1000000)
  1049. }
  1050. Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
  1051. offset = offset >>> 0
  1052. if (!noAssert) checkOffset(offset, 4, this.length)
  1053. return (this[offset] * 0x1000000) +
  1054. ((this[offset + 1] << 16) |
  1055. (this[offset + 2] << 8) |
  1056. this[offset + 3])
  1057. }
  1058. Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
  1059. offset = offset >>> 0
  1060. byteLength = byteLength >>> 0
  1061. if (!noAssert) checkOffset(offset, byteLength, this.length)
  1062. var val = this[offset]
  1063. var mul = 1
  1064. var i = 0
  1065. while (++i < byteLength && (mul *= 0x100)) {
  1066. val += this[offset + i] * mul
  1067. }
  1068. mul *= 0x80
  1069. if (val >= mul) val -= Math.pow(2, 8 * byteLength)
  1070. return val
  1071. }
  1072. Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
  1073. offset = offset >>> 0
  1074. byteLength = byteLength >>> 0
  1075. if (!noAssert) checkOffset(offset, byteLength, this.length)
  1076. var i = byteLength
  1077. var mul = 1
  1078. var val = this[offset + --i]
  1079. while (i > 0 && (mul *= 0x100)) {
  1080. val += this[offset + --i] * mul
  1081. }
  1082. mul *= 0x80
  1083. if (val >= mul) val -= Math.pow(2, 8 * byteLength)
  1084. return val
  1085. }
  1086. Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
  1087. offset = offset >>> 0
  1088. if (!noAssert) checkOffset(offset, 1, this.length)
  1089. if (!(this[offset] & 0x80)) return (this[offset])
  1090. return ((0xff - this[offset] + 1) * -1)
  1091. }
  1092. Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
  1093. offset = offset >>> 0
  1094. if (!noAssert) checkOffset(offset, 2, this.length)
  1095. var val = this[offset] | (this[offset + 1] << 8)
  1096. return (val & 0x8000) ? val | 0xFFFF0000 : val
  1097. }
  1098. Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
  1099. offset = offset >>> 0
  1100. if (!noAssert) checkOffset(offset, 2, this.length)
  1101. var val = this[offset + 1] | (this[offset] << 8)
  1102. return (val & 0x8000) ? val | 0xFFFF0000 : val
  1103. }
  1104. Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
  1105. offset = offset >>> 0
  1106. if (!noAssert) checkOffset(offset, 4, this.length)
  1107. return (this[offset]) |
  1108. (this[offset + 1] << 8) |
  1109. (this[offset + 2] << 16) |
  1110. (this[offset + 3] << 24)
  1111. }
  1112. Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
  1113. offset = offset >>> 0
  1114. if (!noAssert) checkOffset(offset, 4, this.length)
  1115. return (this[offset] << 24) |
  1116. (this[offset + 1] << 16) |
  1117. (this[offset + 2] << 8) |
  1118. (this[offset + 3])
  1119. }
  1120. Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
  1121. offset = offset >>> 0
  1122. if (!noAssert) checkOffset(offset, 4, this.length)
  1123. return ieee754.read(this, offset, true, 23, 4)
  1124. }
  1125. Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
  1126. offset = offset >>> 0
  1127. if (!noAssert) checkOffset(offset, 4, this.length)
  1128. return ieee754.read(this, offset, false, 23, 4)
  1129. }
  1130. Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
  1131. offset = offset >>> 0
  1132. if (!noAssert) checkOffset(offset, 8, this.length)
  1133. return ieee754.read(this, offset, true, 52, 8)
  1134. }
  1135. Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
  1136. offset = offset >>> 0
  1137. if (!noAssert) checkOffset(offset, 8, this.length)
  1138. return ieee754.read(this, offset, false, 52, 8)
  1139. }
  1140. function checkInt (buf, value, offset, ext, max, min) {
  1141. if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
  1142. if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
  1143. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  1144. }
  1145. Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
  1146. value = +value
  1147. offset = offset >>> 0
  1148. byteLength = byteLength >>> 0
  1149. if (!noAssert) {
  1150. var maxBytes = Math.pow(2, 8 * byteLength) - 1
  1151. checkInt(this, value, offset, byteLength, maxBytes, 0)
  1152. }
  1153. var mul = 1
  1154. var i = 0
  1155. this[offset] = value & 0xFF
  1156. while (++i < byteLength && (mul *= 0x100)) {
  1157. this[offset + i] = (value / mul) & 0xFF
  1158. }
  1159. return offset + byteLength
  1160. }
  1161. Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
  1162. value = +value
  1163. offset = offset >>> 0
  1164. byteLength = byteLength >>> 0
  1165. if (!noAssert) {
  1166. var maxBytes = Math.pow(2, 8 * byteLength) - 1
  1167. checkInt(this, value, offset, byteLength, maxBytes, 0)
  1168. }
  1169. var i = byteLength - 1
  1170. var mul = 1
  1171. this[offset + i] = value & 0xFF
  1172. while (--i >= 0 && (mul *= 0x100)) {
  1173. this[offset + i] = (value / mul) & 0xFF
  1174. }
  1175. return offset + byteLength
  1176. }
  1177. Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
  1178. value = +value
  1179. offset = offset >>> 0
  1180. if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
  1181. this[offset] = (value & 0xff)
  1182. return offset + 1
  1183. }
  1184. Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
  1185. value = +value
  1186. offset = offset >>> 0
  1187. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  1188. this[offset] = (value & 0xff)
  1189. this[offset + 1] = (value >>> 8)
  1190. return offset + 2
  1191. }
  1192. Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
  1193. value = +value
  1194. offset = offset >>> 0
  1195. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  1196. this[offset] = (value >>> 8)
  1197. this[offset + 1] = (value & 0xff)
  1198. return offset + 2
  1199. }
  1200. Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
  1201. value = +value
  1202. offset = offset >>> 0
  1203. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  1204. this[offset + 3] = (value >>> 24)
  1205. this[offset + 2] = (value >>> 16)
  1206. this[offset + 1] = (value >>> 8)
  1207. this[offset] = (value & 0xff)
  1208. return offset + 4
  1209. }
  1210. Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
  1211. value = +value
  1212. offset = offset >>> 0
  1213. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  1214. this[offset] = (value >>> 24)
  1215. this[offset + 1] = (value >>> 16)
  1216. this[offset + 2] = (value >>> 8)
  1217. this[offset + 3] = (value & 0xff)
  1218. return offset + 4
  1219. }
  1220. Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
  1221. value = +value
  1222. offset = offset >>> 0
  1223. if (!noAssert) {
  1224. var limit = Math.pow(2, (8 * byteLength) - 1)
  1225. checkInt(this, value, offset, byteLength, limit - 1, -limit)
  1226. }
  1227. var i = 0
  1228. var mul = 1
  1229. var sub = 0
  1230. this[offset] = value & 0xFF
  1231. while (++i < byteLength && (mul *= 0x100)) {
  1232. if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
  1233. sub = 1
  1234. }
  1235. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  1236. }
  1237. return offset + byteLength
  1238. }
  1239. Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
  1240. value = +value
  1241. offset = offset >>> 0
  1242. if (!noAssert) {
  1243. var limit = Math.pow(2, (8 * byteLength) - 1)
  1244. checkInt(this, value, offset, byteLength, limit - 1, -limit)
  1245. }
  1246. var i = byteLength - 1
  1247. var mul = 1
  1248. var sub = 0
  1249. this[offset + i] = value & 0xFF
  1250. while (--i >= 0 && (mul *= 0x100)) {
  1251. if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
  1252. sub = 1
  1253. }
  1254. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  1255. }
  1256. return offset + byteLength
  1257. }
  1258. Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
  1259. value = +value
  1260. offset = offset >>> 0
  1261. if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
  1262. if (value < 0) value = 0xff + value + 1
  1263. this[offset] = (value & 0xff)
  1264. return offset + 1
  1265. }
  1266. Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
  1267. value = +value
  1268. offset = offset >>> 0
  1269. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  1270. this[offset] = (value & 0xff)
  1271. this[offset + 1] = (value >>> 8)
  1272. return offset + 2
  1273. }
  1274. Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
  1275. value = +value
  1276. offset = offset >>> 0
  1277. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  1278. this[offset] = (value >>> 8)
  1279. this[offset + 1] = (value & 0xff)
  1280. return offset + 2
  1281. }
  1282. Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
  1283. value = +value
  1284. offset = offset >>> 0
  1285. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  1286. this[offset] = (value & 0xff)
  1287. this[offset + 1] = (value >>> 8)
  1288. this[offset + 2] = (value >>> 16)
  1289. this[offset + 3] = (value >>> 24)
  1290. return offset + 4
  1291. }
  1292. Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
  1293. value = +value
  1294. offset = offset >>> 0
  1295. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  1296. if (value < 0) value = 0xffffffff + value + 1
  1297. this[offset] = (value >>> 24)
  1298. this[offset + 1] = (value >>> 16)
  1299. this[offset + 2] = (value >>> 8)
  1300. this[offset + 3] = (value & 0xff)
  1301. return offset + 4
  1302. }
  1303. function checkIEEE754 (buf, value, offset, ext, max, min) {
  1304. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  1305. if (offset < 0) throw new RangeError('Index out of range')
  1306. }
  1307. function writeFloat (buf, value, offset, littleEndian, noAssert) {
  1308. value = +value
  1309. offset = offset >>> 0
  1310. if (!noAssert) {
  1311. checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
  1312. }
  1313. ieee754.write(buf, value, offset, littleEndian, 23, 4)
  1314. return offset + 4
  1315. }
  1316. Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
  1317. return writeFloat(this, value, offset, true, noAssert)
  1318. }
  1319. Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
  1320. return writeFloat(this, value, offset, false, noAssert)
  1321. }
  1322. function writeDouble (buf, value, offset, littleEndian, noAssert) {
  1323. value = +value
  1324. offset = offset >>> 0
  1325. if (!noAssert) {
  1326. checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
  1327. }
  1328. ieee754.write(buf, value, offset, littleEndian, 52, 8)
  1329. return offset + 8
  1330. }
  1331. Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
  1332. return writeDouble(this, value, offset, true, noAssert)
  1333. }
  1334. Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
  1335. return writeDouble(this, value, offset, false, noAssert)
  1336. }
  1337. // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
  1338. Buffer.prototype.copy = function copy (target, targetStart, start, end) {
  1339. if (!start) start = 0
  1340. if (!end && end !== 0) end = this.length
  1341. if (targetStart >= target.length) targetStart = target.length
  1342. if (!targetStart) targetStart = 0
  1343. if (end > 0 && end < start) end = start
  1344. // Copy 0 bytes; we're done
  1345. if (end === start) return 0
  1346. if (target.length === 0 || this.length === 0) return 0
  1347. // Fatal error conditions
  1348. if (targetStart < 0) {
  1349. throw new RangeError('targetStart out of bounds')
  1350. }
  1351. if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
  1352. if (end < 0) throw new RangeError('sourceEnd out of bounds')
  1353. // Are we oob?
  1354. if (end > this.length) end = this.length
  1355. if (target.length - targetStart < end - start) {
  1356. end = target.length - targetStart + start
  1357. }
  1358. var len = end - start
  1359. var i
  1360. if (this === target && start < targetStart && targetStart < end) {
  1361. // descending copy from end
  1362. for (i = len - 1; i >= 0; --i) {
  1363. target[i + targetStart] = this[i + start]
  1364. }
  1365. } else if (len < 1000) {
  1366. // ascending copy from start
  1367. for (i = 0; i < len; ++i) {
  1368. target[i + targetStart] = this[i + start]
  1369. }
  1370. } else {
  1371. Uint8Array.prototype.set.call(
  1372. target,
  1373. this.subarray(start, start + len),
  1374. targetStart
  1375. )
  1376. }
  1377. return len
  1378. }
  1379. // Usage:
  1380. // buffer.fill(number[, offset[, end]])
  1381. // buffer.fill(buffer[, offset[, end]])
  1382. // buffer.fill(string[, offset[, end]][, encoding])
  1383. Buffer.prototype.fill = function fill (val, start, end, encoding) {
  1384. // Handle string cases:
  1385. if (typeof val === 'string') {
  1386. if (typeof start === 'string') {
  1387. encoding = start
  1388. start = 0
  1389. end = this.length
  1390. } else if (typeof end === 'string') {
  1391. encoding = end
  1392. end = this.length
  1393. }
  1394. if (val.length === 1) {
  1395. var code = val.charCodeAt(0)
  1396. if (code < 256) {
  1397. val = code
  1398. }
  1399. }
  1400. if (encoding !== undefined && typeof encoding !== 'string') {
  1401. throw new TypeError('encoding must be a string')
  1402. }
  1403. if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
  1404. throw new TypeError('Unknown encoding: ' + encoding)
  1405. }
  1406. } else if (typeof val === 'number') {
  1407. val = val & 255
  1408. }
  1409. // Invalid ranges are not set to a default, so can range check early.
  1410. if (start < 0 || this.length < start || this.length < end) {
  1411. throw new RangeError('Out of range index')
  1412. }
  1413. if (end <= start) {
  1414. return this
  1415. }
  1416. start = start >>> 0
  1417. end = end === undefined ? this.length : end >>> 0
  1418. if (!val) val = 0
  1419. var i
  1420. if (typeof val === 'number') {
  1421. for (i = start; i < end; ++i) {
  1422. this[i] = val
  1423. }
  1424. } else {
  1425. var bytes = Buffer.isBuffer(val)
  1426. ? val
  1427. : new Buffer(val, encoding)
  1428. var len = bytes.length
  1429. for (i = 0; i < end - start; ++i) {
  1430. this[i + start] = bytes[i % len]
  1431. }
  1432. }
  1433. return this
  1434. }
  1435. // HELPER FUNCTIONS
  1436. // ================
  1437. var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g
  1438. function base64clean (str) {
  1439. // Node strips out invalid characters like \n and \t from the string, base64-js does not
  1440. str = str.trim().replace(INVALID_BASE64_RE, '')
  1441. // Node converts strings with length < 2 to ''
  1442. if (str.length < 2) return ''
  1443. // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
  1444. while (str.length % 4 !== 0) {
  1445. str = str + '='
  1446. }
  1447. return str
  1448. }
  1449. function toHex (n) {
  1450. if (n < 16) return '0' + n.toString(16)
  1451. return n.toString(16)
  1452. }
  1453. function utf8ToBytes (string, units) {
  1454. units = units || Infinity
  1455. var codePoint
  1456. var length = string.length
  1457. var leadSurrogate = null
  1458. var bytes = []
  1459. for (var i = 0; i < length; ++i) {
  1460. codePoint = string.charCodeAt(i)
  1461. // is surrogate component
  1462. if (codePoint > 0xD7FF && codePoint < 0xE000) {
  1463. // last char was a lead
  1464. if (!leadSurrogate) {
  1465. // no lead yet
  1466. if (codePoint > 0xDBFF) {
  1467. // unexpected trail
  1468. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  1469. continue
  1470. } else if (i + 1 === length) {
  1471. // unpaired lead
  1472. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  1473. continue
  1474. }
  1475. // valid lead
  1476. leadSurrogate = codePoint
  1477. continue
  1478. }
  1479. // 2 leads in a row
  1480. if (codePoint < 0xDC00) {
  1481. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  1482. leadSurrogate = codePoint
  1483. continue
  1484. }
  1485. // valid surrogate pair
  1486. codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
  1487. } else if (leadSurrogate) {
  1488. // valid bmp char, but last char was a lead
  1489. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  1490. }
  1491. leadSurrogate = null
  1492. // encode utf8
  1493. if (codePoint < 0x80) {
  1494. if ((units -= 1) < 0) break
  1495. bytes.push(codePoint)
  1496. } else if (codePoint < 0x800) {
  1497. if ((units -= 2) < 0) break
  1498. bytes.push(
  1499. codePoint >> 0x6 | 0xC0,
  1500. codePoint & 0x3F | 0x80
  1501. )
  1502. } else if (codePoint < 0x10000) {
  1503. if ((units -= 3) < 0) break
  1504. bytes.push(
  1505. codePoint >> 0xC | 0xE0,
  1506. codePoint >> 0x6 & 0x3F | 0x80,
  1507. codePoint & 0x3F | 0x80
  1508. )
  1509. } else if (codePoint < 0x110000) {
  1510. if ((units -= 4) < 0) break
  1511. bytes.push(
  1512. codePoint >> 0x12 | 0xF0,
  1513. codePoint >> 0xC & 0x3F | 0x80,
  1514. codePoint >> 0x6 & 0x3F | 0x80,
  1515. codePoint & 0x3F | 0x80
  1516. )
  1517. } else {
  1518. throw new Error('Invalid code point')
  1519. }
  1520. }
  1521. return bytes
  1522. }
  1523. function asciiToBytes (str) {
  1524. var byteArray = []
  1525. for (var i = 0; i < str.length; ++i) {
  1526. // Node's code seems to be doing this and not & 0x7F..
  1527. byteArray.push(str.charCodeAt(i) & 0xFF)
  1528. }
  1529. return byteArray
  1530. }
  1531. function utf16leToBytes (str, units) {
  1532. var c, hi, lo
  1533. var byteArray = []
  1534. for (var i = 0; i < str.length; ++i) {
  1535. if ((units -= 2) < 0) break
  1536. c = str.charCodeAt(i)
  1537. hi = c >> 8
  1538. lo = c % 256
  1539. byteArray.push(lo)
  1540. byteArray.push(hi)
  1541. }
  1542. return byteArray
  1543. }
  1544. function base64ToBytes (str) {
  1545. return base64.toByteArray(base64clean(str))
  1546. }
  1547. function blitBuffer (src, dst, offset, length) {
  1548. for (var i = 0; i < length; ++i) {
  1549. if ((i + offset >= dst.length) || (i >= src.length)) break
  1550. dst[i + offset] = src[i]
  1551. }
  1552. return i
  1553. }
  1554. // ArrayBuffers from another context (i.e. an iframe) do not pass the `instanceof` check
  1555. // but they should be treated as valid. See: https://github.com/feross/buffer/issues/166
  1556. function isArrayBuffer (obj) {
  1557. return obj instanceof ArrayBuffer ||
  1558. (obj != null && obj.constructor != null && obj.constructor.name === 'ArrayBuffer' &&
  1559. typeof obj.byteLength === 'number')
  1560. }
  1561. // Node 0.10 supports `ArrayBuffer` but lacks `ArrayBuffer.isView`
  1562. function isArrayBufferView (obj) {
  1563. return (typeof ArrayBuffer.isView === 'function') && ArrayBuffer.isView(obj)
  1564. }
  1565. function numberIsNaN (obj) {
  1566. return obj !== obj // eslint-disable-line no-self-compare
  1567. }
  1568. },{"base64-js":1,"ieee754":15}],4:[function(require,module,exports){
  1569. // Use strict mode (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode)
  1570. "use strict";
  1571. // Requires
  1572. var Typo = require("typo-js");
  1573. // Create function
  1574. function CodeMirrorSpellChecker(options) {
  1575. // Initialize
  1576. options = options || {};
  1577. // Verify
  1578. if(typeof options.codeMirrorInstance !== "function" || typeof options.codeMirrorInstance.defineMode !== "function") {
  1579. console.log("CodeMirror Spell Checker: You must provide an instance of CodeMirror via the option `codeMirrorInstance`");
  1580. return;
  1581. }
  1582. // Because some browsers don't support this functionality yet
  1583. if(!String.prototype.includes) {
  1584. String.prototype.includes = function() {
  1585. "use strict";
  1586. return String.prototype.indexOf.apply(this, arguments) !== -1;
  1587. };
  1588. }
  1589. // Define the new mode
  1590. options.codeMirrorInstance.defineMode("spell-checker", function(config) {
  1591. // Load AFF/DIC data
  1592. if(!CodeMirrorSpellChecker.aff_loading) {
  1593. CodeMirrorSpellChecker.aff_loading = true;
  1594. var xhr_aff = new XMLHttpRequest();
  1595. xhr_aff.open("GET", "https://cdn.jsdelivr.net/codemirror.spell-checker/latest/en_US.aff", true);
  1596. xhr_aff.onload = function() {
  1597. if(xhr_aff.readyState === 4 && xhr_aff.status === 200) {
  1598. CodeMirrorSpellChecker.aff_data = xhr_aff.responseText;
  1599. CodeMirrorSpellChecker.num_loaded++;
  1600. if(CodeMirrorSpellChecker.num_loaded == 2) {
  1601. CodeMirrorSpellChecker.typo = new Typo("en_US", CodeMirrorSpellChecker.aff_data, CodeMirrorSpellChecker.dic_data, {
  1602. platform: "any"
  1603. });
  1604. }
  1605. }
  1606. };
  1607. xhr_aff.send(null);
  1608. }
  1609. if(!CodeMirrorSpellChecker.dic_loading) {
  1610. CodeMirrorSpellChecker.dic_loading = true;
  1611. var xhr_dic = new XMLHttpRequest();
  1612. xhr_dic.open("GET", "https://cdn.jsdelivr.net/codemirror.spell-checker/latest/en_US.dic", true);
  1613. xhr_dic.onload = function() {
  1614. if(xhr_dic.readyState === 4 && xhr_dic.status === 200) {
  1615. CodeMirrorSpellChecker.dic_data = xhr_dic.responseText;
  1616. CodeMirrorSpellChecker.num_loaded++;
  1617. if(CodeMirrorSpellChecker.num_loaded == 2) {
  1618. CodeMirrorSpellChecker.typo = new Typo("en_US", CodeMirrorSpellChecker.aff_data, CodeMirrorSpellChecker.dic_data, {
  1619. platform: "any"
  1620. });
  1621. }
  1622. }
  1623. };
  1624. xhr_dic.send(null);
  1625. }
  1626. // Define what separates a word
  1627. var rx_word = "!\"#$%&()*+,-./:;<=>?@[\\]^_`{|}~ ";
  1628. // Create the overlay and such
  1629. var overlay = {
  1630. token: function(stream) {
  1631. var ch = stream.peek();
  1632. var word = "";
  1633. if(rx_word.includes(ch)) {
  1634. stream.next();
  1635. return null;
  1636. }
  1637. while((ch = stream.peek()) != null && !rx_word.includes(ch)) {
  1638. word += ch;
  1639. stream.next();
  1640. }
  1641. if(CodeMirrorSpellChecker.typo && !CodeMirrorSpellChecker.typo.check(word))
  1642. return "spell-error"; // CSS class: cm-spell-error
  1643. return null;
  1644. }
  1645. };
  1646. var mode = options.codeMirrorInstance.getMode(
  1647. config, config.backdrop || "text/plain"
  1648. );
  1649. return options.codeMirrorInstance.overlayMode(mode, overlay, true);
  1650. });
  1651. }
  1652. // Initialize data globally to reduce memory consumption
  1653. CodeMirrorSpellChecker.num_loaded = 0;
  1654. CodeMirrorSpellChecker.aff_loading = false;
  1655. CodeMirrorSpellChecker.dic_loading = false;
  1656. CodeMirrorSpellChecker.aff_data = "";
  1657. CodeMirrorSpellChecker.dic_data = "";
  1658. CodeMirrorSpellChecker.typo;
  1659. // Export
  1660. module.exports = CodeMirrorSpellChecker;
  1661. },{"typo-js":17}],5:[function(require,module,exports){
  1662. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  1663. // Distributed under an MIT license: http://codemirror.net/LICENSE
  1664. (function(mod) {
  1665. if (typeof exports == "object" && typeof module == "object") // CommonJS
  1666. mod(require("../../lib/codemirror"));
  1667. else if (typeof define == "function" && define.amd) // AMD
  1668. define(["../../lib/codemirror"], mod);
  1669. else // Plain browser env
  1670. mod(CodeMirror);
  1671. })(function(CodeMirror) {
  1672. "use strict";
  1673. CodeMirror.defineOption("fullScreen", false, function(cm, val, old) {
  1674. if (old == CodeMirror.Init) old = false;
  1675. if (!old == !val) return;
  1676. if (val) setFullscreen(cm);
  1677. else setNormal(cm);
  1678. });
  1679. function setFullscreen(cm) {
  1680. var wrap = cm.getWrapperElement();
  1681. cm.state.fullScreenRestore = {scrollTop: window.pageYOffset, scrollLeft: window.pageXOffset,
  1682. width: wrap.style.width, height: wrap.style.height};
  1683. wrap.style.width = "";
  1684. wrap.style.height = "auto";
  1685. wrap.className += " CodeMirror-fullscreen";
  1686. document.documentElement.style.overflow = "hidden";
  1687. cm.refresh();
  1688. }
  1689. function setNormal(cm) {
  1690. var wrap = cm.getWrapperElement();
  1691. wrap.className = wrap.className.replace(/\s*CodeMirror-fullscreen\b/, "");
  1692. document.documentElement.style.overflow = "";
  1693. var info = cm.state.fullScreenRestore;
  1694. wrap.style.width = info.width; wrap.style.height = info.height;
  1695. window.scrollTo(info.scrollLeft, info.scrollTop);
  1696. cm.refresh();
  1697. }
  1698. });
  1699. },{"../../lib/codemirror":10}],6:[function(require,module,exports){
  1700. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  1701. // Distributed under an MIT license: http://codemirror.net/LICENSE
  1702. (function(mod) {
  1703. if (typeof exports == "object" && typeof module == "object") // CommonJS
  1704. mod(require("../../lib/codemirror"));
  1705. else if (typeof define == "function" && define.amd) // AMD
  1706. define(["../../lib/codemirror"], mod);
  1707. else // Plain browser env
  1708. mod(CodeMirror);
  1709. })(function(CodeMirror) {
  1710. CodeMirror.defineOption("placeholder", "", function(cm, val, old) {
  1711. var prev = old && old != CodeMirror.Init;
  1712. if (val && !prev) {
  1713. cm.on("blur", onBlur);
  1714. cm.on("change", onChange);
  1715. cm.on("swapDoc", onChange);
  1716. onChange(cm);
  1717. } else if (!val && prev) {
  1718. cm.off("blur", onBlur);
  1719. cm.off("change", onChange);
  1720. cm.off("swapDoc", onChange);
  1721. clearPlaceholder(cm);
  1722. var wrapper = cm.getWrapperElement();
  1723. wrapper.className = wrapper.className.replace(" CodeMirror-empty", "");
  1724. }
  1725. if (val && !cm.hasFocus()) onBlur(cm);
  1726. });
  1727. function clearPlaceholder(cm) {
  1728. if (cm.state.placeholder) {
  1729. cm.state.placeholder.parentNode.removeChild(cm.state.placeholder);
  1730. cm.state.placeholder = null;
  1731. }
  1732. }
  1733. function setPlaceholder(cm) {
  1734. clearPlaceholder(cm);
  1735. var elt = cm.state.placeholder = document.createElement("pre");
  1736. elt.style.cssText = "height: 0; overflow: visible";
  1737. elt.className = "CodeMirror-placeholder";
  1738. var placeHolder = cm.getOption("placeholder")
  1739. if (typeof placeHolder == "string") placeHolder = document.createTextNode(placeHolder)
  1740. elt.appendChild(placeHolder)
  1741. cm.display.lineSpace.insertBefore(elt, cm.display.lineSpace.firstChild);
  1742. }
  1743. function onBlur(cm) {
  1744. if (isEmpty(cm)) setPlaceholder(cm);
  1745. }
  1746. function onChange(cm) {
  1747. var wrapper = cm.getWrapperElement(), empty = isEmpty(cm);
  1748. wrapper.className = wrapper.className.replace(" CodeMirror-empty", "") + (empty ? " CodeMirror-empty" : "");
  1749. if (empty) setPlaceholder(cm);
  1750. else clearPlaceholder(cm);
  1751. }
  1752. function isEmpty(cm) {
  1753. return (cm.lineCount() === 1) && (cm.getLine(0) === "");
  1754. }
  1755. });
  1756. },{"../../lib/codemirror":10}],7:[function(require,module,exports){
  1757. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  1758. // Distributed under an MIT license: http://codemirror.net/LICENSE
  1759. (function(mod) {
  1760. if (typeof exports == "object" && typeof module == "object") // CommonJS
  1761. mod(require("../../lib/codemirror"));
  1762. else if (typeof define == "function" && define.amd) // AMD
  1763. define(["../../lib/codemirror"], mod);
  1764. else // Plain browser env
  1765. mod(CodeMirror);
  1766. })(function(CodeMirror) {
  1767. "use strict";
  1768. var listRE = /^(\s*)(>[> ]*|[*+-] \[[x ]\]\s|[*+-]\s|(\d+)([.)]))(\s*)/,
  1769. emptyListRE = /^(\s*)(>[> ]*|[*+-] \[[x ]\]|[*+-]|(\d+)[.)])(\s*)$/,
  1770. unorderedListRE = /[*+-]\s/;
  1771. CodeMirror.commands.newlineAndIndentContinueMarkdownList = function(cm) {
  1772. if (cm.getOption("disableInput")) return CodeMirror.Pass;
  1773. var ranges = cm.listSelections(), replacements = [];
  1774. for (var i = 0; i < ranges.length; i++) {
  1775. var pos = ranges[i].head;
  1776. var eolState = cm.getStateAfter(pos.line);
  1777. var inList = eolState.list !== false;
  1778. var inQuote = eolState.quote !== 0;
  1779. var line = cm.getLine(pos.line), match = listRE.exec(line);
  1780. var cursorBeforeBullet = /^\s*$/.test(line.slice(0, pos.ch));
  1781. if (!ranges[i].empty() || (!inList && !inQuote) || !match || cursorBeforeBullet) {
  1782. cm.execCommand("newlineAndIndent");
  1783. return;
  1784. }
  1785. if (emptyListRE.test(line)) {
  1786. if (!/>\s*$/.test(line)) cm.replaceRange("", {
  1787. line: pos.line, ch: 0
  1788. }, {
  1789. line: pos.line, ch: pos.ch + 1
  1790. });
  1791. replacements[i] = "\n";
  1792. } else {
  1793. var indent = match[1], after = match[5];
  1794. var bullet = unorderedListRE.test(match[2]) || match[2].indexOf(">") >= 0
  1795. ? match[2].replace("x", " ")
  1796. : (parseInt(match[3], 10) + 1) + match[4];
  1797. replacements[i] = "\n" + indent + bullet + after;
  1798. incrementRemainingMarkdownListNumbers(cm, pos);
  1799. }
  1800. }
  1801. cm.replaceSelections(replacements);
  1802. };
  1803. // Auto-updating Markdown list numbers when a new item is added to the
  1804. // middle of a list
  1805. function incrementRemainingMarkdownListNumbers(cm, pos) {
  1806. var startLine = pos.line, lookAhead = 0, skipCount = 0;
  1807. var startItem = listRE.exec(cm.getLine(startLine)), startIndent = startItem[1];
  1808. do {
  1809. lookAhead += 1;
  1810. var nextLineNumber = startLine + lookAhead;
  1811. var nextLine = cm.getLine(nextLineNumber), nextItem = listRE.exec(nextLine);
  1812. if (nextItem) {
  1813. var nextIndent = nextItem[1];
  1814. var newNumber = (parseInt(startItem[3], 10) + lookAhead - skipCount);
  1815. var nextNumber = (parseInt(nextItem[3], 10)), itemNumber = nextNumber;
  1816. if (startIndent === nextIndent) {
  1817. if (newNumber === nextNumber) itemNumber = nextNumber + 1;
  1818. if (newNumber > nextNumber) itemNumber = newNumber + 1;
  1819. cm.replaceRange(
  1820. nextLine.replace(listRE, nextIndent + itemNumber + nextItem[4] + nextItem[5]),
  1821. {
  1822. line: nextLineNumber, ch: 0
  1823. }, {
  1824. line: nextLineNumber, ch: nextLine.length
  1825. });
  1826. } else {
  1827. if (startIndent.length > nextIndent.length) return;
  1828. // This doesn't run if the next line immediatley indents, as it is
  1829. // not clear of the users intention (new indented item or same level)
  1830. if ((startIndent.length < nextIndent.length) && (lookAhead === 1)) return;
  1831. skipCount += 1;
  1832. }
  1833. }
  1834. } while (nextItem);
  1835. }
  1836. });
  1837. },{"../../lib/codemirror":10}],8:[function(require,module,exports){
  1838. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  1839. // Distributed under an MIT license: http://codemirror.net/LICENSE
  1840. // Utility function that allows modes to be combined. The mode given
  1841. // as the base argument takes care of most of the normal mode
  1842. // functionality, but a second (typically simple) mode is used, which
  1843. // can override the style of text. Both modes get to parse all of the
  1844. // text, but when both assign a non-null style to a piece of code, the
  1845. // overlay wins, unless the combine argument was true and not overridden,
  1846. // or state.overlay.combineTokens was true, in which case the styles are
  1847. // combined.
  1848. (function(mod) {
  1849. if (typeof exports == "object" && typeof module == "object") // CommonJS
  1850. mod(require("../../lib/codemirror"));
  1851. else if (typeof define == "function" && define.amd) // AMD
  1852. define(["../../lib/codemirror"], mod);
  1853. else // Plain browser env
  1854. mod(CodeMirror);
  1855. })(function(CodeMirror) {
  1856. "use strict";
  1857. CodeMirror.overlayMode = function(base, overlay, combine) {
  1858. return {
  1859. startState: function() {
  1860. return {
  1861. base: CodeMirror.startState(base),
  1862. overlay: CodeMirror.startState(overlay),
  1863. basePos: 0, baseCur: null,
  1864. overlayPos: 0, overlayCur: null,
  1865. streamSeen: null
  1866. };
  1867. },
  1868. copyState: function(state) {
  1869. return {
  1870. base: CodeMirror.copyState(base, state.base),
  1871. overlay: CodeMirror.copyState(overlay, state.overlay),
  1872. basePos: state.basePos, baseCur: null,
  1873. overlayPos: state.overlayPos, overlayCur: null
  1874. };
  1875. },
  1876. token: function(stream, state) {
  1877. if (stream != state.streamSeen ||
  1878. Math.min(state.basePos, state.overlayPos) < stream.start) {
  1879. state.streamSeen = stream;
  1880. state.basePos = state.overlayPos = stream.start;
  1881. }
  1882. if (stream.start == state.basePos) {
  1883. state.baseCur = base.token(stream, state.base);
  1884. state.basePos = stream.pos;
  1885. }
  1886. if (stream.start == state.overlayPos) {
  1887. stream.pos = stream.start;
  1888. state.overlayCur = overlay.token(stream, state.overlay);
  1889. state.overlayPos = stream.pos;
  1890. }
  1891. stream.pos = Math.min(state.basePos, state.overlayPos);
  1892. // state.overlay.combineTokens always takes precedence over combine,
  1893. // unless set to null
  1894. if (state.overlayCur == null) return state.baseCur;
  1895. else if (state.baseCur != null &&
  1896. state.overlay.combineTokens ||
  1897. combine && state.overlay.combineTokens == null)
  1898. return state.baseCur + " " + state.overlayCur;
  1899. else return state.overlayCur;
  1900. },
  1901. indent: base.indent && function(state, textAfter) {
  1902. return base.indent(state.base, textAfter);
  1903. },
  1904. electricChars: base.electricChars,
  1905. innerMode: function(state) { return {state: state.base, mode: base}; },
  1906. blankLine: function(state) {
  1907. var baseToken, overlayToken;
  1908. if (base.blankLine) baseToken = base.blankLine(state.base);
  1909. if (overlay.blankLine) overlayToken = overlay.blankLine(state.overlay);
  1910. return overlayToken == null ?
  1911. baseToken :
  1912. (combine && baseToken != null ? baseToken + " " + overlayToken : overlayToken);
  1913. }
  1914. };
  1915. };
  1916. });
  1917. },{"../../lib/codemirror":10}],9:[function(require,module,exports){
  1918. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  1919. // Distributed under an MIT license: http://codemirror.net/LICENSE
  1920. // Because sometimes you need to mark the selected *text*.
  1921. //
  1922. // Adds an option 'styleSelectedText' which, when enabled, gives
  1923. // selected text the CSS class given as option value, or
  1924. // "CodeMirror-selectedtext" when the value is not a string.
  1925. (function(mod) {
  1926. if (typeof exports == "object" && typeof module == "object") // CommonJS
  1927. mod(require("../../lib/codemirror"));
  1928. else if (typeof define == "function" && define.amd) // AMD
  1929. define(["../../lib/codemirror"], mod);
  1930. else // Plain browser env
  1931. mod(CodeMirror);
  1932. })(function(CodeMirror) {
  1933. "use strict";
  1934. CodeMirror.defineOption("styleSelectedText", false, function(cm, val, old) {
  1935. var prev = old && old != CodeMirror.Init;
  1936. if (val && !prev) {
  1937. cm.state.markedSelection = [];
  1938. cm.state.markedSelectionStyle = typeof val == "string" ? val : "CodeMirror-selectedtext";
  1939. reset(cm);
  1940. cm.on("cursorActivity", onCursorActivity);
  1941. cm.on("change", onChange);
  1942. } else if (!val && prev) {
  1943. cm.off("cursorActivity", onCursorActivity);
  1944. cm.off("change", onChange);
  1945. clear(cm);
  1946. cm.state.markedSelection = cm.state.markedSelectionStyle = null;
  1947. }
  1948. });
  1949. function onCursorActivity(cm) {
  1950. if (cm.state.markedSelection)
  1951. cm.operation(function() { update(cm); });
  1952. }
  1953. function onChange(cm) {
  1954. if (cm.state.markedSelection && cm.state.markedSelection.length)
  1955. cm.operation(function() { clear(cm); });
  1956. }
  1957. var CHUNK_SIZE = 8;
  1958. var Pos = CodeMirror.Pos;
  1959. var cmp = CodeMirror.cmpPos;
  1960. function coverRange(cm, from, to, addAt) {
  1961. if (cmp(from, to) == 0) return;
  1962. var array = cm.state.markedSelection;
  1963. var cls = cm.state.markedSelectionStyle;
  1964. for (var line = from.line;;) {
  1965. var start = line == from.line ? from : Pos(line, 0);
  1966. var endLine = line + CHUNK_SIZE, atEnd = endLine >= to.line;
  1967. var end = atEnd ? to : Pos(endLine, 0);
  1968. var mark = cm.markText(start, end, {className: cls});
  1969. if (addAt == null) array.push(mark);
  1970. else array.splice(addAt++, 0, mark);
  1971. if (atEnd) break;
  1972. line = endLine;
  1973. }
  1974. }
  1975. function clear(cm) {
  1976. var array = cm.state.markedSelection;
  1977. for (var i = 0; i < array.length; ++i) array[i].clear();
  1978. array.length = 0;
  1979. }
  1980. function reset(cm) {
  1981. clear(cm);
  1982. var ranges = cm.listSelections();
  1983. for (var i = 0; i < ranges.length; i++)
  1984. coverRange(cm, ranges[i].from(), ranges[i].to());
  1985. }
  1986. function update(cm) {
  1987. if (!cm.somethingSelected()) return clear(cm);
  1988. if (cm.listSelections().length > 1) return reset(cm);
  1989. var from = cm.getCursor("start"), to = cm.getCursor("end");
  1990. var array = cm.state.markedSelection;
  1991. if (!array.length) return coverRange(cm, from, to);
  1992. var coverStart = array[0].find(), coverEnd = array[array.length - 1].find();
  1993. if (!coverStart || !coverEnd || to.line - from.line <= CHUNK_SIZE ||
  1994. cmp(from, coverEnd.to) >= 0 || cmp(to, coverStart.from) <= 0)
  1995. return reset(cm);
  1996. while (cmp(from, coverStart.from) > 0) {
  1997. array.shift().clear();
  1998. coverStart = array[0].find();
  1999. }
  2000. if (cmp(from, coverStart.from) < 0) {
  2001. if (coverStart.to.line - from.line < CHUNK_SIZE) {
  2002. array.shift().clear();
  2003. coverRange(cm, from, coverStart.to, 0);
  2004. } else {
  2005. coverRange(cm, from, coverStart.from, 0);
  2006. }
  2007. }
  2008. while (cmp(to, coverEnd.to) < 0) {
  2009. array.pop().clear();
  2010. coverEnd = array[array.length - 1].find();
  2011. }
  2012. if (cmp(to, coverEnd.to) > 0) {
  2013. if (to.line - coverEnd.from.line < CHUNK_SIZE) {
  2014. array.pop().clear();
  2015. coverRange(cm, coverEnd.from, to);
  2016. } else {
  2017. coverRange(cm, coverEnd.to, to);
  2018. }
  2019. }
  2020. }
  2021. });
  2022. },{"../../lib/codemirror":10}],10:[function(require,module,exports){
  2023. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  2024. // Distributed under an MIT license: http://codemirror.net/LICENSE
  2025. // This is CodeMirror (http://codemirror.net), a code editor
  2026. // implemented in JavaScript on top of the browser's DOM.
  2027. //
  2028. // You can find some technical background for some of the code below
  2029. // at http://marijnhaverbeke.nl/blog/#cm-internals .
  2030. (function (global, factory) {
  2031. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  2032. typeof define === 'function' && define.amd ? define(factory) :
  2033. (global.CodeMirror = factory());
  2034. }(this, (function () { 'use strict';
  2035. // Kludges for bugs and behavior differences that can't be feature
  2036. // detected are enabled based on userAgent etc sniffing.
  2037. var userAgent = navigator.userAgent;
  2038. var platform = navigator.platform;
  2039. var gecko = /gecko\/\d/i.test(userAgent);
  2040. var ie_upto10 = /MSIE \d/.test(userAgent);
  2041. var ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(userAgent);
  2042. var edge = /Edge\/(\d+)/.exec(userAgent);
  2043. var ie = ie_upto10 || ie_11up || edge;
  2044. var ie_version = ie && (ie_upto10 ? document.documentMode || 6 : +(edge || ie_11up)[1]);
  2045. var webkit = !edge && /WebKit\//.test(userAgent);
  2046. var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(userAgent);
  2047. var chrome = !edge && /Chrome\//.test(userAgent);
  2048. var presto = /Opera\//.test(userAgent);
  2049. var safari = /Apple Computer/.test(navigator.vendor);
  2050. var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(userAgent);
  2051. var phantom = /PhantomJS/.test(userAgent);
  2052. var ios = !edge && /AppleWebKit/.test(userAgent) && /Mobile\/\w+/.test(userAgent);
  2053. var android = /Android/.test(userAgent);
  2054. // This is woefully incomplete. Suggestions for alternative methods welcome.
  2055. var mobile = ios || android || /webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(userAgent);
  2056. var mac = ios || /Mac/.test(platform);
  2057. var chromeOS = /\bCrOS\b/.test(userAgent);
  2058. var windows = /win/i.test(platform);
  2059. var presto_version = presto && userAgent.match(/Version\/(\d*\.\d*)/);
  2060. if (presto_version) { presto_version = Number(presto_version[1]); }
  2061. if (presto_version && presto_version >= 15) { presto = false; webkit = true; }
  2062. // Some browsers use the wrong event properties to signal cmd/ctrl on OS X
  2063. var flipCtrlCmd = mac && (qtwebkit || presto && (presto_version == null || presto_version < 12.11));
  2064. var captureRightClick = gecko || (ie && ie_version >= 9);
  2065. function classTest(cls) { return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*") }
  2066. var rmClass = function(node, cls) {
  2067. var current = node.className;
  2068. var match = classTest(cls).exec(current);
  2069. if (match) {
  2070. var after = current.slice(match.index + match[0].length);
  2071. node.className = current.slice(0, match.index) + (after ? match[1] + after : "");
  2072. }
  2073. };
  2074. function removeChildren(e) {
  2075. for (var count = e.childNodes.length; count > 0; --count)
  2076. { e.removeChild(e.firstChild); }
  2077. return e
  2078. }
  2079. function removeChildrenAndAdd(parent, e) {
  2080. return removeChildren(parent).appendChild(e)
  2081. }
  2082. function elt(tag, content, className, style) {
  2083. var e = document.createElement(tag);
  2084. if (className) { e.className = className; }
  2085. if (style) { e.style.cssText = style; }
  2086. if (typeof content == "string") { e.appendChild(document.createTextNode(content)); }
  2087. else if (content) { for (var i = 0; i < content.length; ++i) { e.appendChild(content[i]); } }
  2088. return e
  2089. }
  2090. // wrapper for elt, which removes the elt from the accessibility tree
  2091. function eltP(tag, content, className, style) {
  2092. var e = elt(tag, content, className, style);
  2093. e.setAttribute("role", "presentation");
  2094. return e
  2095. }
  2096. var range;
  2097. if (document.createRange) { range = function(node, start, end, endNode) {
  2098. var r = document.createRange();
  2099. r.setEnd(endNode || node, end);
  2100. r.setStart(node, start);
  2101. return r
  2102. }; }
  2103. else { range = function(node, start, end) {
  2104. var r = document.body.createTextRange();
  2105. try { r.moveToElementText(node.parentNode); }
  2106. catch(e) { return r }
  2107. r.collapse(true);
  2108. r.moveEnd("character", end);
  2109. r.moveStart("character", start);
  2110. return r
  2111. }; }
  2112. function contains(parent, child) {
  2113. if (child.nodeType == 3) // Android browser always returns false when child is a textnode
  2114. { child = child.parentNode; }
  2115. if (parent.contains)
  2116. { return parent.contains(child) }
  2117. do {
  2118. if (child.nodeType == 11) { child = child.host; }
  2119. if (child == parent) { return true }
  2120. } while (child = child.parentNode)
  2121. }
  2122. function activeElt() {
  2123. // IE and Edge may throw an "Unspecified Error" when accessing document.activeElement.
  2124. // IE < 10 will throw when accessed while the page is loading or in an iframe.
  2125. // IE > 9 and Edge will throw when accessed in an iframe if document.body is unavailable.
  2126. var activeElement;
  2127. try {
  2128. activeElement = document.activeElement;
  2129. } catch(e) {
  2130. activeElement = document.body || null;
  2131. }
  2132. while (activeElement && activeElement.shadowRoot && activeElement.shadowRoot.activeElement)
  2133. { activeElement = activeElement.shadowRoot.activeElement; }
  2134. return activeElement
  2135. }
  2136. function addClass(node, cls) {
  2137. var current = node.className;
  2138. if (!classTest(cls).test(current)) { node.className += (current ? " " : "") + cls; }
  2139. }
  2140. function joinClasses(a, b) {
  2141. var as = a.split(" ");
  2142. for (var i = 0; i < as.length; i++)
  2143. { if (as[i] && !classTest(as[i]).test(b)) { b += " " + as[i]; } }
  2144. return b
  2145. }
  2146. var selectInput = function(node) { node.select(); };
  2147. if (ios) // Mobile Safari apparently has a bug where select() is broken.
  2148. { selectInput = function(node) { node.selectionStart = 0; node.selectionEnd = node.value.length; }; }
  2149. else if (ie) // Suppress mysterious IE10 errors
  2150. { selectInput = function(node) { try { node.select(); } catch(_e) {} }; }
  2151. function bind(f) {
  2152. var args = Array.prototype.slice.call(arguments, 1);
  2153. return function(){return f.apply(null, args)}
  2154. }
  2155. function copyObj(obj, target, overwrite) {
  2156. if (!target) { target = {}; }
  2157. for (var prop in obj)
  2158. { if (obj.hasOwnProperty(prop) && (overwrite !== false || !target.hasOwnProperty(prop)))
  2159. { target[prop] = obj[prop]; } }
  2160. return target
  2161. }
  2162. // Counts the column offset in a string, taking tabs into account.
  2163. // Used mostly to find indentation.
  2164. function countColumn(string, end, tabSize, startIndex, startValue) {
  2165. if (end == null) {
  2166. end = string.search(/[^\s\u00a0]/);
  2167. if (end == -1) { end = string.length; }
  2168. }
  2169. for (var i = startIndex || 0, n = startValue || 0;;) {
  2170. var nextTab = string.indexOf("\t", i);
  2171. if (nextTab < 0 || nextTab >= end)
  2172. { return n + (end - i) }
  2173. n += nextTab - i;
  2174. n += tabSize - (n % tabSize);
  2175. i = nextTab + 1;
  2176. }
  2177. }
  2178. var Delayed = function() {this.id = null;};
  2179. Delayed.prototype.set = function (ms, f) {
  2180. clearTimeout(this.id);
  2181. this.id = setTimeout(f, ms);
  2182. };
  2183. function indexOf(array, elt) {
  2184. for (var i = 0; i < array.length; ++i)
  2185. { if (array[i] == elt) { return i } }
  2186. return -1
  2187. }
  2188. // Number of pixels added to scroller and sizer to hide scrollbar
  2189. var scrollerGap = 30;
  2190. // Returned or thrown by various protocols to signal 'I'm not
  2191. // handling this'.
  2192. var Pass = {toString: function(){return "CodeMirror.Pass"}};
  2193. // Reused option objects for setSelection & friends
  2194. var sel_dontScroll = {scroll: false};
  2195. var sel_mouse = {origin: "*mouse"};
  2196. var sel_move = {origin: "+move"};
  2197. // The inverse of countColumn -- find the offset that corresponds to
  2198. // a particular column.
  2199. function findColumn(string, goal, tabSize) {
  2200. for (var pos = 0, col = 0;;) {
  2201. var nextTab = string.indexOf("\t", pos);
  2202. if (nextTab == -1) { nextTab = string.length; }
  2203. var skipped = nextTab - pos;
  2204. if (nextTab == string.length || col + skipped >= goal)
  2205. { return pos + Math.min(skipped, goal - col) }
  2206. col += nextTab - pos;
  2207. col += tabSize - (col % tabSize);
  2208. pos = nextTab + 1;
  2209. if (col >= goal) { return pos }
  2210. }
  2211. }
  2212. var spaceStrs = [""];
  2213. function spaceStr(n) {
  2214. while (spaceStrs.length <= n)
  2215. { spaceStrs.push(lst(spaceStrs) + " "); }
  2216. return spaceStrs[n]
  2217. }
  2218. function lst(arr) { return arr[arr.length-1] }
  2219. function map(array, f) {
  2220. var out = [];
  2221. for (var i = 0; i < array.length; i++) { out[i] = f(array[i], i); }
  2222. return out
  2223. }
  2224. function insertSorted(array, value, score) {
  2225. var pos = 0, priority = score(value);
  2226. while (pos < array.length && score(array[pos]) <= priority) { pos++; }
  2227. array.splice(pos, 0, value);
  2228. }
  2229. function nothing() {}
  2230. function createObj(base, props) {
  2231. var inst;
  2232. if (Object.create) {
  2233. inst = Object.create(base);
  2234. } else {
  2235. nothing.prototype = base;
  2236. inst = new nothing();
  2237. }
  2238. if (props) { copyObj(props, inst); }
  2239. return inst
  2240. }
  2241. var nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;
  2242. function isWordCharBasic(ch) {
  2243. return /\w/.test(ch) || ch > "\x80" &&
  2244. (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch))
  2245. }
  2246. function isWordChar(ch, helper) {
  2247. if (!helper) { return isWordCharBasic(ch) }
  2248. if (helper.source.indexOf("\\w") > -1 && isWordCharBasic(ch)) { return true }
  2249. return helper.test(ch)
  2250. }
  2251. function isEmpty(obj) {
  2252. for (var n in obj) { if (obj.hasOwnProperty(n) && obj[n]) { return false } }
  2253. return true
  2254. }
  2255. // Extending unicode characters. A series of a non-extending char +
  2256. // any number of extending chars is treated as a single unit as far
  2257. // as editing and measuring is concerned. This is not fully correct,
  2258. // since some scripts/fonts/browsers also treat other configurations
  2259. // of code points as a group.
  2260. 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]/;
  2261. function isExtendingChar(ch) { return ch.charCodeAt(0) >= 768 && extendingChars.test(ch) }
  2262. // Returns a number from the range [`0`; `str.length`] unless `pos` is outside that range.
  2263. function skipExtendingChars(str, pos, dir) {
  2264. while ((dir < 0 ? pos > 0 : pos < str.length) && isExtendingChar(str.charAt(pos))) { pos += dir; }
  2265. return pos
  2266. }
  2267. // Returns the value from the range [`from`; `to`] that satisfies
  2268. // `pred` and is closest to `from`. Assumes that at least `to`
  2269. // satisfies `pred`. Supports `from` being greater than `to`.
  2270. function findFirst(pred, from, to) {
  2271. // At any point we are certain `to` satisfies `pred`, don't know
  2272. // whether `from` does.
  2273. var dir = from > to ? -1 : 1;
  2274. for (;;) {
  2275. if (from == to) { return from }
  2276. var midF = (from + to) / 2, mid = dir < 0 ? Math.ceil(midF) : Math.floor(midF);
  2277. if (mid == from) { return pred(mid) ? from : to }
  2278. if (pred(mid)) { to = mid; }
  2279. else { from = mid + dir; }
  2280. }
  2281. }
  2282. // The display handles the DOM integration, both for input reading
  2283. // and content drawing. It holds references to DOM nodes and
  2284. // display-related state.
  2285. function Display(place, doc, input) {
  2286. var d = this;
  2287. this.input = input;
  2288. // Covers bottom-right square when both scrollbars are present.
  2289. d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler");
  2290. d.scrollbarFiller.setAttribute("cm-not-content", "true");
  2291. // Covers bottom of gutter when coverGutterNextToScrollbar is on
  2292. // and h scrollbar is present.
  2293. d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler");
  2294. d.gutterFiller.setAttribute("cm-not-content", "true");
  2295. // Will contain the actual code, positioned to cover the viewport.
  2296. d.lineDiv = eltP("div", null, "CodeMirror-code");
  2297. // Elements are added to these to represent selection and cursors.
  2298. d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1");
  2299. d.cursorDiv = elt("div", null, "CodeMirror-cursors");
  2300. // A visibility: hidden element used to find the size of things.
  2301. d.measure = elt("div", null, "CodeMirror-measure");
  2302. // When lines outside of the viewport are measured, they are drawn in this.
  2303. d.lineMeasure = elt("div", null, "CodeMirror-measure");
  2304. // Wraps everything that needs to exist inside the vertically-padded coordinate system
  2305. d.lineSpace = eltP("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv],
  2306. null, "position: relative; outline: none");
  2307. var lines = eltP("div", [d.lineSpace], "CodeMirror-lines");
  2308. // Moved around its parent to cover visible view.
  2309. d.mover = elt("div", [lines], null, "position: relative");
  2310. // Set to the height of the document, allowing scrolling.
  2311. d.sizer = elt("div", [d.mover], "CodeMirror-sizer");
  2312. d.sizerWidth = null;
  2313. // Behavior of elts with overflow: auto and padding is
  2314. // inconsistent across browsers. This is used to ensure the
  2315. // scrollable area is big enough.
  2316. d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerGap + "px; width: 1px;");
  2317. // Will contain the gutters, if any.
  2318. d.gutters = elt("div", null, "CodeMirror-gutters");
  2319. d.lineGutter = null;
  2320. // Actual scrollable element.
  2321. d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll");
  2322. d.scroller.setAttribute("tabIndex", "-1");
  2323. // The element in which the editor lives.
  2324. d.wrapper = elt("div", [d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror");
  2325. // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported)
  2326. if (ie && ie_version < 8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; }
  2327. if (!webkit && !(gecko && mobile)) { d.scroller.draggable = true; }
  2328. if (place) {
  2329. if (place.appendChild) { place.appendChild(d.wrapper); }
  2330. else { place(d.wrapper); }
  2331. }
  2332. // Current rendered range (may be bigger than the view window).
  2333. d.viewFrom = d.viewTo = doc.first;
  2334. d.reportedViewFrom = d.reportedViewTo = doc.first;
  2335. // Information about the rendered lines.
  2336. d.view = [];
  2337. d.renderedView = null;
  2338. // Holds info about a single rendered line when it was rendered
  2339. // for measurement, while not in view.
  2340. d.externalMeasured = null;
  2341. // Empty space (in pixels) above the view
  2342. d.viewOffset = 0;
  2343. d.lastWrapHeight = d.lastWrapWidth = 0;
  2344. d.updateLineNumbers = null;
  2345. d.nativeBarWidth = d.barHeight = d.barWidth = 0;
  2346. d.scrollbarsClipped = false;
  2347. // Used to only resize the line number gutter when necessary (when
  2348. // the amount of lines crosses a boundary that makes its width change)
  2349. d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null;
  2350. // Set to true when a non-horizontal-scrolling line widget is
  2351. // added. As an optimization, line widget aligning is skipped when
  2352. // this is false.
  2353. d.alignWidgets = false;
  2354. d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
  2355. // Tracks the maximum line length so that the horizontal scrollbar
  2356. // can be kept static when scrolling.
  2357. d.maxLine = null;
  2358. d.maxLineLength = 0;
  2359. d.maxLineChanged = false;
  2360. // Used for measuring wheel scrolling granularity
  2361. d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null;
  2362. // True when shift is held down.
  2363. d.shift = false;
  2364. // Used to track whether anything happened since the context menu
  2365. // was opened.
  2366. d.selForContextMenu = null;
  2367. d.activeTouch = null;
  2368. input.init(d);
  2369. }
  2370. // Find the line object corresponding to the given line number.
  2371. function getLine(doc, n) {
  2372. n -= doc.first;
  2373. if (n < 0 || n >= doc.size) { throw new Error("There is no line " + (n + doc.first) + " in the document.") }
  2374. var chunk = doc;
  2375. while (!chunk.lines) {
  2376. for (var i = 0;; ++i) {
  2377. var child = chunk.children[i], sz = child.chunkSize();
  2378. if (n < sz) { chunk = child; break }
  2379. n -= sz;
  2380. }
  2381. }
  2382. return chunk.lines[n]
  2383. }
  2384. // Get the part of a document between two positions, as an array of
  2385. // strings.
  2386. function getBetween(doc, start, end) {
  2387. var out = [], n = start.line;
  2388. doc.iter(start.line, end.line + 1, function (line) {
  2389. var text = line.text;
  2390. if (n == end.line) { text = text.slice(0, end.ch); }
  2391. if (n == start.line) { text = text.slice(start.ch); }
  2392. out.push(text);
  2393. ++n;
  2394. });
  2395. return out
  2396. }
  2397. // Get the lines between from and to, as array of strings.
  2398. function getLines(doc, from, to) {
  2399. var out = [];
  2400. doc.iter(from, to, function (line) { out.push(line.text); }); // iter aborts when callback returns truthy value
  2401. return out
  2402. }
  2403. // Update the height of a line, propagating the height change
  2404. // upwards to parent nodes.
  2405. function updateLineHeight(line, height) {
  2406. var diff = height - line.height;
  2407. if (diff) { for (var n = line; n; n = n.parent) { n.height += diff; } }
  2408. }
  2409. // Given a line object, find its line number by walking up through
  2410. // its parent links.
  2411. function lineNo(line) {
  2412. if (line.parent == null) { return null }
  2413. var cur = line.parent, no = indexOf(cur.lines, line);
  2414. for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) {
  2415. for (var i = 0;; ++i) {
  2416. if (chunk.children[i] == cur) { break }
  2417. no += chunk.children[i].chunkSize();
  2418. }
  2419. }
  2420. return no + cur.first
  2421. }
  2422. // Find the line at the given vertical position, using the height
  2423. // information in the document tree.
  2424. function lineAtHeight(chunk, h) {
  2425. var n = chunk.first;
  2426. outer: do {
  2427. for (var i$1 = 0; i$1 < chunk.children.length; ++i$1) {
  2428. var child = chunk.children[i$1], ch = child.height;
  2429. if (h < ch) { chunk = child; continue outer }
  2430. h -= ch;
  2431. n += child.chunkSize();
  2432. }
  2433. return n
  2434. } while (!chunk.lines)
  2435. var i = 0;
  2436. for (; i < chunk.lines.length; ++i) {
  2437. var line = chunk.lines[i], lh = line.height;
  2438. if (h < lh) { break }
  2439. h -= lh;
  2440. }
  2441. return n + i
  2442. }
  2443. function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size}
  2444. function lineNumberFor(options, i) {
  2445. return String(options.lineNumberFormatter(i + options.firstLineNumber))
  2446. }
  2447. // A Pos instance represents a position within the text.
  2448. function Pos(line, ch, sticky) {
  2449. if ( sticky === void 0 ) sticky = null;
  2450. if (!(this instanceof Pos)) { return new Pos(line, ch, sticky) }
  2451. this.line = line;
  2452. this.ch = ch;
  2453. this.sticky = sticky;
  2454. }
  2455. // Compare two positions, return 0 if they are the same, a negative
  2456. // number when a is less, and a positive number otherwise.
  2457. function cmp(a, b) { return a.line - b.line || a.ch - b.ch }
  2458. function equalCursorPos(a, b) { return a.sticky == b.sticky && cmp(a, b) == 0 }
  2459. function copyPos(x) {return Pos(x.line, x.ch)}
  2460. function maxPos(a, b) { return cmp(a, b) < 0 ? b : a }
  2461. function minPos(a, b) { return cmp(a, b) < 0 ? a : b }
  2462. // Most of the external API clips given positions to make sure they
  2463. // actually exist within the document.
  2464. function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1))}
  2465. function clipPos(doc, pos) {
  2466. if (pos.line < doc.first) { return Pos(doc.first, 0) }
  2467. var last = doc.first + doc.size - 1;
  2468. if (pos.line > last) { return Pos(last, getLine(doc, last).text.length) }
  2469. return clipToLen(pos, getLine(doc, pos.line).text.length)
  2470. }
  2471. function clipToLen(pos, linelen) {
  2472. var ch = pos.ch;
  2473. if (ch == null || ch > linelen) { return Pos(pos.line, linelen) }
  2474. else if (ch < 0) { return Pos(pos.line, 0) }
  2475. else { return pos }
  2476. }
  2477. function clipPosArray(doc, array) {
  2478. var out = [];
  2479. for (var i = 0; i < array.length; i++) { out[i] = clipPos(doc, array[i]); }
  2480. return out
  2481. }
  2482. // Optimize some code when these features are not used.
  2483. var sawReadOnlySpans = false;
  2484. var sawCollapsedSpans = false;
  2485. function seeReadOnlySpans() {
  2486. sawReadOnlySpans = true;
  2487. }
  2488. function seeCollapsedSpans() {
  2489. sawCollapsedSpans = true;
  2490. }
  2491. // TEXTMARKER SPANS
  2492. function MarkedSpan(marker, from, to) {
  2493. this.marker = marker;
  2494. this.from = from; this.to = to;
  2495. }
  2496. // Search an array of spans for a span matching the given marker.
  2497. function getMarkedSpanFor(spans, marker) {
  2498. if (spans) { for (var i = 0; i < spans.length; ++i) {
  2499. var span = spans[i];
  2500. if (span.marker == marker) { return span }
  2501. } }
  2502. }
  2503. // Remove a span from an array, returning undefined if no spans are
  2504. // left (we don't store arrays for lines without spans).
  2505. function removeMarkedSpan(spans, span) {
  2506. var r;
  2507. for (var i = 0; i < spans.length; ++i)
  2508. { if (spans[i] != span) { (r || (r = [])).push(spans[i]); } }
  2509. return r
  2510. }
  2511. // Add a span to a line.
  2512. function addMarkedSpan(line, span) {
  2513. line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span];
  2514. span.marker.attachLine(line);
  2515. }
  2516. // Used for the algorithm that adjusts markers for a change in the
  2517. // document. These functions cut an array of spans at a given
  2518. // character position, returning an array of remaining chunks (or
  2519. // undefined if nothing remains).
  2520. function markedSpansBefore(old, startCh, isInsert) {
  2521. var nw;
  2522. if (old) { for (var i = 0; i < old.length; ++i) {
  2523. var span = old[i], marker = span.marker;
  2524. var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh);
  2525. if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) {
  2526. 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));
  2527. }
  2528. } }
  2529. return nw
  2530. }
  2531. function markedSpansAfter(old, endCh, isInsert) {
  2532. var nw;
  2533. if (old) { for (var i = 0; i < old.length; ++i) {
  2534. var span = old[i], marker = span.marker;
  2535. var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh);
  2536. if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) {
  2537. var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh);(nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh,
  2538. span.to == null ? null : span.to - endCh));
  2539. }
  2540. } }
  2541. return nw
  2542. }
  2543. // Given a change object, compute the new set of marker spans that
  2544. // cover the line in which the change took place. Removes spans
  2545. // entirely within the change, reconnects spans belonging to the
  2546. // same marker that appear on both sides of the change, and cuts off
  2547. // spans partially within the change. Returns an array of span
  2548. // arrays with one element for each line in (after) the change.
  2549. function stretchSpansOverChange(doc, change) {
  2550. if (change.full) { return null }
  2551. var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans;
  2552. var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans;
  2553. if (!oldFirst && !oldLast) { return null }
  2554. var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0;
  2555. // Get the spans that 'stick out' on both sides
  2556. var first = markedSpansBefore(oldFirst, startCh, isInsert);
  2557. var last = markedSpansAfter(oldLast, endCh, isInsert);
  2558. // Next, merge those two ends
  2559. var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0);
  2560. if (first) {
  2561. // Fix up .to properties of first
  2562. for (var i = 0; i < first.length; ++i) {
  2563. var span = first[i];
  2564. if (span.to == null) {
  2565. var found = getMarkedSpanFor(last, span.marker);
  2566. if (!found) { span.to = startCh; }
  2567. else if (sameLine) { span.to = found.to == null ? null : found.to + offset; }
  2568. }
  2569. }
  2570. }
  2571. if (last) {
  2572. // Fix up .from in last (or move them into first in case of sameLine)
  2573. for (var i$1 = 0; i$1 < last.length; ++i$1) {
  2574. var span$1 = last[i$1];
  2575. if (span$1.to != null) { span$1.to += offset; }
  2576. if (span$1.from == null) {
  2577. var found$1 = getMarkedSpanFor(first, span$1.marker);
  2578. if (!found$1) {
  2579. span$1.from = offset;
  2580. if (sameLine) { (first || (first = [])).push(span$1); }
  2581. }
  2582. } else {
  2583. span$1.from += offset;
  2584. if (sameLine) { (first || (first = [])).push(span$1); }
  2585. }
  2586. }
  2587. }
  2588. // Make sure we didn't create any zero-length spans
  2589. if (first) { first = clearEmptySpans(first); }
  2590. if (last && last != first) { last = clearEmptySpans(last); }
  2591. var newMarkers = [first];
  2592. if (!sameLine) {
  2593. // Fill gap with whole-line-spans
  2594. var gap = change.text.length - 2, gapMarkers;
  2595. if (gap > 0 && first)
  2596. { for (var i$2 = 0; i$2 < first.length; ++i$2)
  2597. { if (first[i$2].to == null)
  2598. { (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i$2].marker, null, null)); } } }
  2599. for (var i$3 = 0; i$3 < gap; ++i$3)
  2600. { newMarkers.push(gapMarkers); }
  2601. newMarkers.push(last);
  2602. }
  2603. return newMarkers
  2604. }
  2605. // Remove spans that are empty and don't have a clearWhenEmpty
  2606. // option of false.
  2607. function clearEmptySpans(spans) {
  2608. for (var i = 0; i < spans.length; ++i) {
  2609. var span = spans[i];
  2610. if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false)
  2611. { spans.splice(i--, 1); }
  2612. }
  2613. if (!spans.length) { return null }
  2614. return spans
  2615. }
  2616. // Used to 'clip' out readOnly ranges when making a change.
  2617. function removeReadOnlyRanges(doc, from, to) {
  2618. var markers = null;
  2619. doc.iter(from.line, to.line + 1, function (line) {
  2620. if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) {
  2621. var mark = line.markedSpans[i].marker;
  2622. if (mark.readOnly && (!markers || indexOf(markers, mark) == -1))
  2623. { (markers || (markers = [])).push(mark); }
  2624. } }
  2625. });
  2626. if (!markers) { return null }
  2627. var parts = [{from: from, to: to}];
  2628. for (var i = 0; i < markers.length; ++i) {
  2629. var mk = markers[i], m = mk.find(0);
  2630. for (var j = 0; j < parts.length; ++j) {
  2631. var p = parts[j];
  2632. if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) { continue }
  2633. var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to);
  2634. if (dfrom < 0 || !mk.inclusiveLeft && !dfrom)
  2635. { newParts.push({from: p.from, to: m.from}); }
  2636. if (dto > 0 || !mk.inclusiveRight && !dto)
  2637. { newParts.push({from: m.to, to: p.to}); }
  2638. parts.splice.apply(parts, newParts);
  2639. j += newParts.length - 3;
  2640. }
  2641. }
  2642. return parts
  2643. }
  2644. // Connect or disconnect spans from a line.
  2645. function detachMarkedSpans(line) {
  2646. var spans = line.markedSpans;
  2647. if (!spans) { return }
  2648. for (var i = 0; i < spans.length; ++i)
  2649. { spans[i].marker.detachLine(line); }
  2650. line.markedSpans = null;
  2651. }
  2652. function attachMarkedSpans(line, spans) {
  2653. if (!spans) { return }
  2654. for (var i = 0; i < spans.length; ++i)
  2655. { spans[i].marker.attachLine(line); }
  2656. line.markedSpans = spans;
  2657. }
  2658. // Helpers used when computing which overlapping collapsed span
  2659. // counts as the larger one.
  2660. function extraLeft(marker) { return marker.inclusiveLeft ? -1 : 0 }
  2661. function extraRight(marker) { return marker.inclusiveRight ? 1 : 0 }
  2662. // Returns a number indicating which of two overlapping collapsed
  2663. // spans is larger (and thus includes the other). Falls back to
  2664. // comparing ids when the spans cover exactly the same range.
  2665. function compareCollapsedMarkers(a, b) {
  2666. var lenDiff = a.lines.length - b.lines.length;
  2667. if (lenDiff != 0) { return lenDiff }
  2668. var aPos = a.find(), bPos = b.find();
  2669. var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b);
  2670. if (fromCmp) { return -fromCmp }
  2671. var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b);
  2672. if (toCmp) { return toCmp }
  2673. return b.id - a.id
  2674. }
  2675. // Find out whether a line ends or starts in a collapsed span. If
  2676. // so, return the marker for that span.
  2677. function collapsedSpanAtSide(line, start) {
  2678. var sps = sawCollapsedSpans && line.markedSpans, found;
  2679. if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) {
  2680. sp = sps[i];
  2681. if (sp.marker.collapsed && (start ? sp.from : sp.to) == null &&
  2682. (!found || compareCollapsedMarkers(found, sp.marker) < 0))
  2683. { found = sp.marker; }
  2684. } }
  2685. return found
  2686. }
  2687. function collapsedSpanAtStart(line) { return collapsedSpanAtSide(line, true) }
  2688. function collapsedSpanAtEnd(line) { return collapsedSpanAtSide(line, false) }
  2689. // Test whether there exists a collapsed span that partially
  2690. // overlaps (covers the start or end, but not both) of a new span.
  2691. // Such overlap is not allowed.
  2692. function conflictingCollapsedRange(doc, lineNo$$1, from, to, marker) {
  2693. var line = getLine(doc, lineNo$$1);
  2694. var sps = sawCollapsedSpans && line.markedSpans;
  2695. if (sps) { for (var i = 0; i < sps.length; ++i) {
  2696. var sp = sps[i];
  2697. if (!sp.marker.collapsed) { continue }
  2698. var found = sp.marker.find(0);
  2699. var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker);
  2700. var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker);
  2701. if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) { continue }
  2702. if (fromCmp <= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.to, from) >= 0 : cmp(found.to, from) > 0) ||
  2703. fromCmp >= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.from, to) <= 0 : cmp(found.from, to) < 0))
  2704. { return true }
  2705. } }
  2706. }
  2707. // A visual line is a line as drawn on the screen. Folding, for
  2708. // example, can cause multiple logical lines to appear on the same
  2709. // visual line. This finds the start of the visual line that the
  2710. // given line is part of (usually that is the line itself).
  2711. function visualLine(line) {
  2712. var merged;
  2713. while (merged = collapsedSpanAtStart(line))
  2714. { line = merged.find(-1, true).line; }
  2715. return line
  2716. }
  2717. function visualLineEnd(line) {
  2718. var merged;
  2719. while (merged = collapsedSpanAtEnd(line))
  2720. { line = merged.find(1, true).line; }
  2721. return line
  2722. }
  2723. // Returns an array of logical lines that continue the visual line
  2724. // started by the argument, or undefined if there are no such lines.
  2725. function visualLineContinued(line) {
  2726. var merged, lines;
  2727. while (merged = collapsedSpanAtEnd(line)) {
  2728. line = merged.find(1, true).line
  2729. ;(lines || (lines = [])).push(line);
  2730. }
  2731. return lines
  2732. }
  2733. // Get the line number of the start of the visual line that the
  2734. // given line number is part of.
  2735. function visualLineNo(doc, lineN) {
  2736. var line = getLine(doc, lineN), vis = visualLine(line);
  2737. if (line == vis) { return lineN }
  2738. return lineNo(vis)
  2739. }
  2740. // Get the line number of the start of the next visual line after
  2741. // the given line.
  2742. function visualLineEndNo(doc, lineN) {
  2743. if (lineN > doc.lastLine()) { return lineN }
  2744. var line = getLine(doc, lineN), merged;
  2745. if (!lineIsHidden(doc, line)) { return lineN }
  2746. while (merged = collapsedSpanAtEnd(line))
  2747. { line = merged.find(1, true).line; }
  2748. return lineNo(line) + 1
  2749. }
  2750. // Compute whether a line is hidden. Lines count as hidden when they
  2751. // are part of a visual line that starts with another line, or when
  2752. // they are entirely covered by collapsed, non-widget span.
  2753. function lineIsHidden(doc, line) {
  2754. var sps = sawCollapsedSpans && line.markedSpans;
  2755. if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) {
  2756. sp = sps[i];
  2757. if (!sp.marker.collapsed) { continue }
  2758. if (sp.from == null) { return true }
  2759. if (sp.marker.widgetNode) { continue }
  2760. if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp))
  2761. { return true }
  2762. } }
  2763. }
  2764. function lineIsHiddenInner(doc, line, span) {
  2765. if (span.to == null) {
  2766. var end = span.marker.find(1, true);
  2767. return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker))
  2768. }
  2769. if (span.marker.inclusiveRight && span.to == line.text.length)
  2770. { return true }
  2771. for (var sp = (void 0), i = 0; i < line.markedSpans.length; ++i) {
  2772. sp = line.markedSpans[i];
  2773. if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to &&
  2774. (sp.to == null || sp.to != span.from) &&
  2775. (sp.marker.inclusiveLeft || span.marker.inclusiveRight) &&
  2776. lineIsHiddenInner(doc, line, sp)) { return true }
  2777. }
  2778. }
  2779. // Find the height above the given line.
  2780. function heightAtLine(lineObj) {
  2781. lineObj = visualLine(lineObj);
  2782. var h = 0, chunk = lineObj.parent;
  2783. for (var i = 0; i < chunk.lines.length; ++i) {
  2784. var line = chunk.lines[i];
  2785. if (line == lineObj) { break }
  2786. else { h += line.height; }
  2787. }
  2788. for (var p = chunk.parent; p; chunk = p, p = chunk.parent) {
  2789. for (var i$1 = 0; i$1 < p.children.length; ++i$1) {
  2790. var cur = p.children[i$1];
  2791. if (cur == chunk) { break }
  2792. else { h += cur.height; }
  2793. }
  2794. }
  2795. return h
  2796. }
  2797. // Compute the character length of a line, taking into account
  2798. // collapsed ranges (see markText) that might hide parts, and join
  2799. // other lines onto it.
  2800. function lineLength(line) {
  2801. if (line.height == 0) { return 0 }
  2802. var len = line.text.length, merged, cur = line;
  2803. while (merged = collapsedSpanAtStart(cur)) {
  2804. var found = merged.find(0, true);
  2805. cur = found.from.line;
  2806. len += found.from.ch - found.to.ch;
  2807. }
  2808. cur = line;
  2809. while (merged = collapsedSpanAtEnd(cur)) {
  2810. var found$1 = merged.find(0, true);
  2811. len -= cur.text.length - found$1.from.ch;
  2812. cur = found$1.to.line;
  2813. len += cur.text.length - found$1.to.ch;
  2814. }
  2815. return len
  2816. }
  2817. // Find the longest line in the document.
  2818. function findMaxLine(cm) {
  2819. var d = cm.display, doc = cm.doc;
  2820. d.maxLine = getLine(doc, doc.first);
  2821. d.maxLineLength = lineLength(d.maxLine);
  2822. d.maxLineChanged = true;
  2823. doc.iter(function (line) {
  2824. var len = lineLength(line);
  2825. if (len > d.maxLineLength) {
  2826. d.maxLineLength = len;
  2827. d.maxLine = line;
  2828. }
  2829. });
  2830. }
  2831. // BIDI HELPERS
  2832. function iterateBidiSections(order, from, to, f) {
  2833. if (!order) { return f(from, to, "ltr", 0) }
  2834. var found = false;
  2835. for (var i = 0; i < order.length; ++i) {
  2836. var part = order[i];
  2837. if (part.from < to && part.to > from || from == to && part.to == from) {
  2838. f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr", i);
  2839. found = true;
  2840. }
  2841. }
  2842. if (!found) { f(from, to, "ltr"); }
  2843. }
  2844. var bidiOther = null;
  2845. function getBidiPartAt(order, ch, sticky) {
  2846. var found;
  2847. bidiOther = null;
  2848. for (var i = 0; i < order.length; ++i) {
  2849. var cur = order[i];
  2850. if (cur.from < ch && cur.to > ch) { return i }
  2851. if (cur.to == ch) {
  2852. if (cur.from != cur.to && sticky == "before") { found = i; }
  2853. else { bidiOther = i; }
  2854. }
  2855. if (cur.from == ch) {
  2856. if (cur.from != cur.to && sticky != "before") { found = i; }
  2857. else { bidiOther = i; }
  2858. }
  2859. }
  2860. return found != null ? found : bidiOther
  2861. }
  2862. // Bidirectional ordering algorithm
  2863. // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm
  2864. // that this (partially) implements.
  2865. // One-char codes used for character types:
  2866. // L (L): Left-to-Right
  2867. // R (R): Right-to-Left
  2868. // r (AL): Right-to-Left Arabic
  2869. // 1 (EN): European Number
  2870. // + (ES): European Number Separator
  2871. // % (ET): European Number Terminator
  2872. // n (AN): Arabic Number
  2873. // , (CS): Common Number Separator
  2874. // m (NSM): Non-Spacing Mark
  2875. // b (BN): Boundary Neutral
  2876. // s (B): Paragraph Separator
  2877. // t (S): Segment Separator
  2878. // w (WS): Whitespace
  2879. // N (ON): Other Neutrals
  2880. // Returns null if characters are ordered as they appear
  2881. // (left-to-right), or an array of sections ({from, to, level}
  2882. // objects) in the order in which they occur visually.
  2883. var bidiOrdering = (function() {
  2884. // Character types for codepoints 0 to 0xff
  2885. var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN";
  2886. // Character types for codepoints 0x600 to 0x6f9
  2887. var arabicTypes = "nnnnnnNNr%%r,rNNmmmmmmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmmmnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmnNmmmmmmrrmmNmmmmrr1111111111";
  2888. function charType(code) {
  2889. if (code <= 0xf7) { return lowTypes.charAt(code) }
  2890. else if (0x590 <= code && code <= 0x5f4) { return "R" }
  2891. else if (0x600 <= code && code <= 0x6f9) { return arabicTypes.charAt(code - 0x600) }
  2892. else if (0x6ee <= code && code <= 0x8ac) { return "r" }
  2893. else if (0x2000 <= code && code <= 0x200b) { return "w" }
  2894. else if (code == 0x200c) { return "b" }
  2895. else { return "L" }
  2896. }
  2897. var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/;
  2898. var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/;
  2899. function BidiSpan(level, from, to) {
  2900. this.level = level;
  2901. this.from = from; this.to = to;
  2902. }
  2903. return function(str, direction) {
  2904. var outerType = direction == "ltr" ? "L" : "R";
  2905. if (str.length == 0 || direction == "ltr" && !bidiRE.test(str)) { return false }
  2906. var len = str.length, types = [];
  2907. for (var i = 0; i < len; ++i)
  2908. { types.push(charType(str.charCodeAt(i))); }
  2909. // W1. Examine each non-spacing mark (NSM) in the level run, and
  2910. // change the type of the NSM to the type of the previous
  2911. // character. If the NSM is at the start of the level run, it will
  2912. // get the type of sor.
  2913. for (var i$1 = 0, prev = outerType; i$1 < len; ++i$1) {
  2914. var type = types[i$1];
  2915. if (type == "m") { types[i$1] = prev; }
  2916. else { prev = type; }
  2917. }
  2918. // W2. Search backwards from each instance of a European number
  2919. // until the first strong type (R, L, AL, or sor) is found. If an
  2920. // AL is found, change the type of the European number to Arabic
  2921. // number.
  2922. // W3. Change all ALs to R.
  2923. for (var i$2 = 0, cur = outerType; i$2 < len; ++i$2) {
  2924. var type$1 = types[i$2];
  2925. if (type$1 == "1" && cur == "r") { types[i$2] = "n"; }
  2926. else if (isStrong.test(type$1)) { cur = type$1; if (type$1 == "r") { types[i$2] = "R"; } }
  2927. }
  2928. // W4. A single European separator between two European numbers
  2929. // changes to a European number. A single common separator between
  2930. // two numbers of the same type changes to that type.
  2931. for (var i$3 = 1, prev$1 = types[0]; i$3 < len - 1; ++i$3) {
  2932. var type$2 = types[i$3];
  2933. if (type$2 == "+" && prev$1 == "1" && types[i$3+1] == "1") { types[i$3] = "1"; }
  2934. else if (type$2 == "," && prev$1 == types[i$3+1] &&
  2935. (prev$1 == "1" || prev$1 == "n")) { types[i$3] = prev$1; }
  2936. prev$1 = type$2;
  2937. }
  2938. // W5. A sequence of European terminators adjacent to European
  2939. // numbers changes to all European numbers.
  2940. // W6. Otherwise, separators and terminators change to Other
  2941. // Neutral.
  2942. for (var i$4 = 0; i$4 < len; ++i$4) {
  2943. var type$3 = types[i$4];
  2944. if (type$3 == ",") { types[i$4] = "N"; }
  2945. else if (type$3 == "%") {
  2946. var end = (void 0);
  2947. for (end = i$4 + 1; end < len && types[end] == "%"; ++end) {}
  2948. var replace = (i$4 && types[i$4-1] == "!") || (end < len && types[end] == "1") ? "1" : "N";
  2949. for (var j = i$4; j < end; ++j) { types[j] = replace; }
  2950. i$4 = end - 1;
  2951. }
  2952. }
  2953. // W7. Search backwards from each instance of a European number
  2954. // until the first strong type (R, L, or sor) is found. If an L is
  2955. // found, then change the type of the European number to L.
  2956. for (var i$5 = 0, cur$1 = outerType; i$5 < len; ++i$5) {
  2957. var type$4 = types[i$5];
  2958. if (cur$1 == "L" && type$4 == "1") { types[i$5] = "L"; }
  2959. else if (isStrong.test(type$4)) { cur$1 = type$4; }
  2960. }
  2961. // N1. A sequence of neutrals takes the direction of the
  2962. // surrounding strong text if the text on both sides has the same
  2963. // direction. European and Arabic numbers act as if they were R in
  2964. // terms of their influence on neutrals. Start-of-level-run (sor)
  2965. // and end-of-level-run (eor) are used at level run boundaries.
  2966. // N2. Any remaining neutrals take the embedding direction.
  2967. for (var i$6 = 0; i$6 < len; ++i$6) {
  2968. if (isNeutral.test(types[i$6])) {
  2969. var end$1 = (void 0);
  2970. for (end$1 = i$6 + 1; end$1 < len && isNeutral.test(types[end$1]); ++end$1) {}
  2971. var before = (i$6 ? types[i$6-1] : outerType) == "L";
  2972. var after = (end$1 < len ? types[end$1] : outerType) == "L";
  2973. var replace$1 = before == after ? (before ? "L" : "R") : outerType;
  2974. for (var j$1 = i$6; j$1 < end$1; ++j$1) { types[j$1] = replace$1; }
  2975. i$6 = end$1 - 1;
  2976. }
  2977. }
  2978. // Here we depart from the documented algorithm, in order to avoid
  2979. // building up an actual levels array. Since there are only three
  2980. // levels (0, 1, 2) in an implementation that doesn't take
  2981. // explicit embedding into account, we can build up the order on
  2982. // the fly, without following the level-based algorithm.
  2983. var order = [], m;
  2984. for (var i$7 = 0; i$7 < len;) {
  2985. if (countsAsLeft.test(types[i$7])) {
  2986. var start = i$7;
  2987. for (++i$7; i$7 < len && countsAsLeft.test(types[i$7]); ++i$7) {}
  2988. order.push(new BidiSpan(0, start, i$7));
  2989. } else {
  2990. var pos = i$7, at = order.length;
  2991. for (++i$7; i$7 < len && types[i$7] != "L"; ++i$7) {}
  2992. for (var j$2 = pos; j$2 < i$7;) {
  2993. if (countsAsNum.test(types[j$2])) {
  2994. if (pos < j$2) { order.splice(at, 0, new BidiSpan(1, pos, j$2)); }
  2995. var nstart = j$2;
  2996. for (++j$2; j$2 < i$7 && countsAsNum.test(types[j$2]); ++j$2) {}
  2997. order.splice(at, 0, new BidiSpan(2, nstart, j$2));
  2998. pos = j$2;
  2999. } else { ++j$2; }
  3000. }
  3001. if (pos < i$7) { order.splice(at, 0, new BidiSpan(1, pos, i$7)); }
  3002. }
  3003. }
  3004. if (direction == "ltr") {
  3005. if (order[0].level == 1 && (m = str.match(/^\s+/))) {
  3006. order[0].from = m[0].length;
  3007. order.unshift(new BidiSpan(0, 0, m[0].length));
  3008. }
  3009. if (lst(order).level == 1 && (m = str.match(/\s+$/))) {
  3010. lst(order).to -= m[0].length;
  3011. order.push(new BidiSpan(0, len - m[0].length, len));
  3012. }
  3013. }
  3014. return direction == "rtl" ? order.reverse() : order
  3015. }
  3016. })();
  3017. // Get the bidi ordering for the given line (and cache it). Returns
  3018. // false for lines that are fully left-to-right, and an array of
  3019. // BidiSpan objects otherwise.
  3020. function getOrder(line, direction) {
  3021. var order = line.order;
  3022. if (order == null) { order = line.order = bidiOrdering(line.text, direction); }
  3023. return order
  3024. }
  3025. // EVENT HANDLING
  3026. // Lightweight event framework. on/off also work on DOM nodes,
  3027. // registering native DOM handlers.
  3028. var noHandlers = [];
  3029. var on = function(emitter, type, f) {
  3030. if (emitter.addEventListener) {
  3031. emitter.addEventListener(type, f, false);
  3032. } else if (emitter.attachEvent) {
  3033. emitter.attachEvent("on" + type, f);
  3034. } else {
  3035. var map$$1 = emitter._handlers || (emitter._handlers = {});
  3036. map$$1[type] = (map$$1[type] || noHandlers).concat(f);
  3037. }
  3038. };
  3039. function getHandlers(emitter, type) {
  3040. return emitter._handlers && emitter._handlers[type] || noHandlers
  3041. }
  3042. function off(emitter, type, f) {
  3043. if (emitter.removeEventListener) {
  3044. emitter.removeEventListener(type, f, false);
  3045. } else if (emitter.detachEvent) {
  3046. emitter.detachEvent("on" + type, f);
  3047. } else {
  3048. var map$$1 = emitter._handlers, arr = map$$1 && map$$1[type];
  3049. if (arr) {
  3050. var index = indexOf(arr, f);
  3051. if (index > -1)
  3052. { map$$1[type] = arr.slice(0, index).concat(arr.slice(index + 1)); }
  3053. }
  3054. }
  3055. }
  3056. function signal(emitter, type /*, values...*/) {
  3057. var handlers = getHandlers(emitter, type);
  3058. if (!handlers.length) { return }
  3059. var args = Array.prototype.slice.call(arguments, 2);
  3060. for (var i = 0; i < handlers.length; ++i) { handlers[i].apply(null, args); }
  3061. }
  3062. // The DOM events that CodeMirror handles can be overridden by
  3063. // registering a (non-DOM) handler on the editor for the event name,
  3064. // and preventDefault-ing the event in that handler.
  3065. function signalDOMEvent(cm, e, override) {
  3066. if (typeof e == "string")
  3067. { e = {type: e, preventDefault: function() { this.defaultPrevented = true; }}; }
  3068. signal(cm, override || e.type, cm, e);
  3069. return e_defaultPrevented(e) || e.codemirrorIgnore
  3070. }
  3071. function signalCursorActivity(cm) {
  3072. var arr = cm._handlers && cm._handlers.cursorActivity;
  3073. if (!arr) { return }
  3074. var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = []);
  3075. for (var i = 0; i < arr.length; ++i) { if (indexOf(set, arr[i]) == -1)
  3076. { set.push(arr[i]); } }
  3077. }
  3078. function hasHandler(emitter, type) {
  3079. return getHandlers(emitter, type).length > 0
  3080. }
  3081. // Add on and off methods to a constructor's prototype, to make
  3082. // registering events on such objects more convenient.
  3083. function eventMixin(ctor) {
  3084. ctor.prototype.on = function(type, f) {on(this, type, f);};
  3085. ctor.prototype.off = function(type, f) {off(this, type, f);};
  3086. }
  3087. // Due to the fact that we still support jurassic IE versions, some
  3088. // compatibility wrappers are needed.
  3089. function e_preventDefault(e) {
  3090. if (e.preventDefault) { e.preventDefault(); }
  3091. else { e.returnValue = false; }
  3092. }
  3093. function e_stopPropagation(e) {
  3094. if (e.stopPropagation) { e.stopPropagation(); }
  3095. else { e.cancelBubble = true; }
  3096. }
  3097. function e_defaultPrevented(e) {
  3098. return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false
  3099. }
  3100. function e_stop(e) {e_preventDefault(e); e_stopPropagation(e);}
  3101. function e_target(e) {return e.target || e.srcElement}
  3102. function e_button(e) {
  3103. var b = e.which;
  3104. if (b == null) {
  3105. if (e.button & 1) { b = 1; }
  3106. else if (e.button & 2) { b = 3; }
  3107. else if (e.button & 4) { b = 2; }
  3108. }
  3109. if (mac && e.ctrlKey && b == 1) { b = 3; }
  3110. return b
  3111. }
  3112. // Detect drag-and-drop
  3113. var dragAndDrop = function() {
  3114. // There is *some* kind of drag-and-drop support in IE6-8, but I
  3115. // couldn't get it to work yet.
  3116. if (ie && ie_version < 9) { return false }
  3117. var div = elt('div');
  3118. return "draggable" in div || "dragDrop" in div
  3119. }();
  3120. var zwspSupported;
  3121. function zeroWidthElement(measure) {
  3122. if (zwspSupported == null) {
  3123. var test = elt("span", "\u200b");
  3124. removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")]));
  3125. if (measure.firstChild.offsetHeight != 0)
  3126. { zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8); }
  3127. }
  3128. var node = zwspSupported ? elt("span", "\u200b") :
  3129. elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px");
  3130. node.setAttribute("cm-text", "");
  3131. return node
  3132. }
  3133. // Feature-detect IE's crummy client rect reporting for bidi text
  3134. var badBidiRects;
  3135. function hasBadBidiRects(measure) {
  3136. if (badBidiRects != null) { return badBidiRects }
  3137. var txt = removeChildrenAndAdd(measure, document.createTextNode("A\u062eA"));
  3138. var r0 = range(txt, 0, 1).getBoundingClientRect();
  3139. var r1 = range(txt, 1, 2).getBoundingClientRect();
  3140. removeChildren(measure);
  3141. if (!r0 || r0.left == r0.right) { return false } // Safari returns null in some cases (#2780)
  3142. return badBidiRects = (r1.right - r0.right < 3)
  3143. }
  3144. // See if "".split is the broken IE version, if so, provide an
  3145. // alternative way to split lines.
  3146. var splitLinesAuto = "\n\nb".split(/\n/).length != 3 ? function (string) {
  3147. var pos = 0, result = [], l = string.length;
  3148. while (pos <= l) {
  3149. var nl = string.indexOf("\n", pos);
  3150. if (nl == -1) { nl = string.length; }
  3151. var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl);
  3152. var rt = line.indexOf("\r");
  3153. if (rt != -1) {
  3154. result.push(line.slice(0, rt));
  3155. pos += rt + 1;
  3156. } else {
  3157. result.push(line);
  3158. pos = nl + 1;
  3159. }
  3160. }
  3161. return result
  3162. } : function (string) { return string.split(/\r\n?|\n/); };
  3163. var hasSelection = window.getSelection ? function (te) {
  3164. try { return te.selectionStart != te.selectionEnd }
  3165. catch(e) { return false }
  3166. } : function (te) {
  3167. var range$$1;
  3168. try {range$$1 = te.ownerDocument.selection.createRange();}
  3169. catch(e) {}
  3170. if (!range$$1 || range$$1.parentElement() != te) { return false }
  3171. return range$$1.compareEndPoints("StartToEnd", range$$1) != 0
  3172. };
  3173. var hasCopyEvent = (function () {
  3174. var e = elt("div");
  3175. if ("oncopy" in e) { return true }
  3176. e.setAttribute("oncopy", "return;");
  3177. return typeof e.oncopy == "function"
  3178. })();
  3179. var badZoomedRects = null;
  3180. function hasBadZoomedRects(measure) {
  3181. if (badZoomedRects != null) { return badZoomedRects }
  3182. var node = removeChildrenAndAdd(measure, elt("span", "x"));
  3183. var normal = node.getBoundingClientRect();
  3184. var fromRange = range(node, 0, 1).getBoundingClientRect();
  3185. return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1
  3186. }
  3187. // Known modes, by name and by MIME
  3188. var modes = {};
  3189. var mimeModes = {};
  3190. // Extra arguments are stored as the mode's dependencies, which is
  3191. // used by (legacy) mechanisms like loadmode.js to automatically
  3192. // load a mode. (Preferred mechanism is the require/define calls.)
  3193. function defineMode(name, mode) {
  3194. if (arguments.length > 2)
  3195. { mode.dependencies = Array.prototype.slice.call(arguments, 2); }
  3196. modes[name] = mode;
  3197. }
  3198. function defineMIME(mime, spec) {
  3199. mimeModes[mime] = spec;
  3200. }
  3201. // Given a MIME type, a {name, ...options} config object, or a name
  3202. // string, return a mode config object.
  3203. function resolveMode(spec) {
  3204. if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) {
  3205. spec = mimeModes[spec];
  3206. } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) {
  3207. var found = mimeModes[spec.name];
  3208. if (typeof found == "string") { found = {name: found}; }
  3209. spec = createObj(found, spec);
  3210. spec.name = found.name;
  3211. } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) {
  3212. return resolveMode("application/xml")
  3213. } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+json$/.test(spec)) {
  3214. return resolveMode("application/json")
  3215. }
  3216. if (typeof spec == "string") { return {name: spec} }
  3217. else { return spec || {name: "null"} }
  3218. }
  3219. // Given a mode spec (anything that resolveMode accepts), find and
  3220. // initialize an actual mode object.
  3221. function getMode(options, spec) {
  3222. spec = resolveMode(spec);
  3223. var mfactory = modes[spec.name];
  3224. if (!mfactory) { return getMode(options, "text/plain") }
  3225. var modeObj = mfactory(options, spec);
  3226. if (modeExtensions.hasOwnProperty(spec.name)) {
  3227. var exts = modeExtensions[spec.name];
  3228. for (var prop in exts) {
  3229. if (!exts.hasOwnProperty(prop)) { continue }
  3230. if (modeObj.hasOwnProperty(prop)) { modeObj["_" + prop] = modeObj[prop]; }
  3231. modeObj[prop] = exts[prop];
  3232. }
  3233. }
  3234. modeObj.name = spec.name;
  3235. if (spec.helperType) { modeObj.helperType = spec.helperType; }
  3236. if (spec.modeProps) { for (var prop$1 in spec.modeProps)
  3237. { modeObj[prop$1] = spec.modeProps[prop$1]; } }
  3238. return modeObj
  3239. }
  3240. // This can be used to attach properties to mode objects from
  3241. // outside the actual mode definition.
  3242. var modeExtensions = {};
  3243. function extendMode(mode, properties) {
  3244. var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {});
  3245. copyObj(properties, exts);
  3246. }
  3247. function copyState(mode, state) {
  3248. if (state === true) { return state }
  3249. if (mode.copyState) { return mode.copyState(state) }
  3250. var nstate = {};
  3251. for (var n in state) {
  3252. var val = state[n];
  3253. if (val instanceof Array) { val = val.concat([]); }
  3254. nstate[n] = val;
  3255. }
  3256. return nstate
  3257. }
  3258. // Given a mode and a state (for that mode), find the inner mode and
  3259. // state at the position that the state refers to.
  3260. function innerMode(mode, state) {
  3261. var info;
  3262. while (mode.innerMode) {
  3263. info = mode.innerMode(state);
  3264. if (!info || info.mode == mode) { break }
  3265. state = info.state;
  3266. mode = info.mode;
  3267. }
  3268. return info || {mode: mode, state: state}
  3269. }
  3270. function startState(mode, a1, a2) {
  3271. return mode.startState ? mode.startState(a1, a2) : true
  3272. }
  3273. // STRING STREAM
  3274. // Fed to the mode parsers, provides helper functions to make
  3275. // parsers more succinct.
  3276. var StringStream = function(string, tabSize, lineOracle) {
  3277. this.pos = this.start = 0;
  3278. this.string = string;
  3279. this.tabSize = tabSize || 8;
  3280. this.lastColumnPos = this.lastColumnValue = 0;
  3281. this.lineStart = 0;
  3282. this.lineOracle = lineOracle;
  3283. };
  3284. StringStream.prototype.eol = function () {return this.pos >= this.string.length};
  3285. StringStream.prototype.sol = function () {return this.pos == this.lineStart};
  3286. StringStream.prototype.peek = function () {return this.string.charAt(this.pos) || undefined};
  3287. StringStream.prototype.next = function () {
  3288. if (this.pos < this.string.length)
  3289. { return this.string.charAt(this.pos++) }
  3290. };
  3291. StringStream.prototype.eat = function (match) {
  3292. var ch = this.string.charAt(this.pos);
  3293. var ok;
  3294. if (typeof match == "string") { ok = ch == match; }
  3295. else { ok = ch && (match.test ? match.test(ch) : match(ch)); }
  3296. if (ok) {++this.pos; return ch}
  3297. };
  3298. StringStream.prototype.eatWhile = function (match) {
  3299. var start = this.pos;
  3300. while (this.eat(match)){}
  3301. return this.pos > start
  3302. };
  3303. StringStream.prototype.eatSpace = function () {
  3304. var this$1 = this;
  3305. var start = this.pos;
  3306. while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) { ++this$1.pos; }
  3307. return this.pos > start
  3308. };
  3309. StringStream.prototype.skipToEnd = function () {this.pos = this.string.length;};
  3310. StringStream.prototype.skipTo = function (ch) {
  3311. var found = this.string.indexOf(ch, this.pos);
  3312. if (found > -1) {this.pos = found; return true}
  3313. };
  3314. StringStream.prototype.backUp = function (n) {this.pos -= n;};
  3315. StringStream.prototype.column = function () {
  3316. if (this.lastColumnPos < this.start) {
  3317. this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue);
  3318. this.lastColumnPos = this.start;
  3319. }
  3320. return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0)
  3321. };
  3322. StringStream.prototype.indentation = function () {
  3323. return countColumn(this.string, null, this.tabSize) -
  3324. (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0)
  3325. };
  3326. StringStream.prototype.match = function (pattern, consume, caseInsensitive) {
  3327. if (typeof pattern == "string") {
  3328. var cased = function (str) { return caseInsensitive ? str.toLowerCase() : str; };
  3329. var substr = this.string.substr(this.pos, pattern.length);
  3330. if (cased(substr) == cased(pattern)) {
  3331. if (consume !== false) { this.pos += pattern.length; }
  3332. return true
  3333. }
  3334. } else {
  3335. var match = this.string.slice(this.pos).match(pattern);
  3336. if (match && match.index > 0) { return null }
  3337. if (match && consume !== false) { this.pos += match[0].length; }
  3338. return match
  3339. }
  3340. };
  3341. StringStream.prototype.current = function (){return this.string.slice(this.start, this.pos)};
  3342. StringStream.prototype.hideFirstChars = function (n, inner) {
  3343. this.lineStart += n;
  3344. try { return inner() }
  3345. finally { this.lineStart -= n; }
  3346. };
  3347. StringStream.prototype.lookAhead = function (n) {
  3348. var oracle = this.lineOracle;
  3349. return oracle && oracle.lookAhead(n)
  3350. };
  3351. StringStream.prototype.baseToken = function () {
  3352. var oracle = this.lineOracle;
  3353. return oracle && oracle.baseToken(this.pos)
  3354. };
  3355. var SavedContext = function(state, lookAhead) {
  3356. this.state = state;
  3357. this.lookAhead = lookAhead;
  3358. };
  3359. var Context = function(doc, state, line, lookAhead) {
  3360. this.state = state;
  3361. this.doc = doc;
  3362. this.line = line;
  3363. this.maxLookAhead = lookAhead || 0;
  3364. this.baseTokens = null;
  3365. this.baseTokenPos = 1;
  3366. };
  3367. Context.prototype.lookAhead = function (n) {
  3368. var line = this.doc.getLine(this.line + n);
  3369. if (line != null && n > this.maxLookAhead) { this.maxLookAhead = n; }
  3370. return line
  3371. };
  3372. Context.prototype.baseToken = function (n) {
  3373. var this$1 = this;
  3374. if (!this.baseTokens) { return null }
  3375. while (this.baseTokens[this.baseTokenPos] <= n)
  3376. { this$1.baseTokenPos += 2; }
  3377. var type = this.baseTokens[this.baseTokenPos + 1];
  3378. return {type: type && type.replace(/( |^)overlay .*/, ""),
  3379. size: this.baseTokens[this.baseTokenPos] - n}
  3380. };
  3381. Context.prototype.nextLine = function () {
  3382. this.line++;
  3383. if (this.maxLookAhead > 0) { this.maxLookAhead--; }
  3384. };
  3385. Context.fromSaved = function (doc, saved, line) {
  3386. if (saved instanceof SavedContext)
  3387. { return new Context(doc, copyState(doc.mode, saved.state), line, saved.lookAhead) }
  3388. else
  3389. { return new Context(doc, copyState(doc.mode, saved), line) }
  3390. };
  3391. Context.prototype.save = function (copy) {
  3392. var state = copy !== false ? copyState(this.doc.mode, this.state) : this.state;
  3393. return this.maxLookAhead > 0 ? new SavedContext(state, this.maxLookAhead) : state
  3394. };
  3395. // Compute a style array (an array starting with a mode generation
  3396. // -- for invalidation -- followed by pairs of end positions and
  3397. // style strings), which is used to highlight the tokens on the
  3398. // line.
  3399. function highlightLine(cm, line, context, forceToEnd) {
  3400. // A styles array always starts with a number identifying the
  3401. // mode/overlays that it is based on (for easy invalidation).
  3402. var st = [cm.state.modeGen], lineClasses = {};
  3403. // Compute the base array of styles
  3404. runMode(cm, line.text, cm.doc.mode, context, function (end, style) { return st.push(end, style); },
  3405. lineClasses, forceToEnd);
  3406. var state = context.state;
  3407. // Run overlays, adjust style array.
  3408. var loop = function ( o ) {
  3409. context.baseTokens = st;
  3410. var overlay = cm.state.overlays[o], i = 1, at = 0;
  3411. context.state = true;
  3412. runMode(cm, line.text, overlay.mode, context, function (end, style) {
  3413. var start = i;
  3414. // Ensure there's a token end at the current position, and that i points at it
  3415. while (at < end) {
  3416. var i_end = st[i];
  3417. if (i_end > end)
  3418. { st.splice(i, 1, end, st[i+1], i_end); }
  3419. i += 2;
  3420. at = Math.min(end, i_end);
  3421. }
  3422. if (!style) { return }
  3423. if (overlay.opaque) {
  3424. st.splice(start, i - start, end, "overlay " + style);
  3425. i = start + 2;
  3426. } else {
  3427. for (; start < i; start += 2) {
  3428. var cur = st[start+1];
  3429. st[start+1] = (cur ? cur + " " : "") + "overlay " + style;
  3430. }
  3431. }
  3432. }, lineClasses);
  3433. context.state = state;
  3434. context.baseTokens = null;
  3435. context.baseTokenPos = 1;
  3436. };
  3437. for (var o = 0; o < cm.state.overlays.length; ++o) loop( o );
  3438. return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null}
  3439. }
  3440. function getLineStyles(cm, line, updateFrontier) {
  3441. if (!line.styles || line.styles[0] != cm.state.modeGen) {
  3442. var context = getContextBefore(cm, lineNo(line));
  3443. var resetState = line.text.length > cm.options.maxHighlightLength && copyState(cm.doc.mode, context.state);
  3444. var result = highlightLine(cm, line, context);
  3445. if (resetState) { context.state = resetState; }
  3446. line.stateAfter = context.save(!resetState);
  3447. line.styles = result.styles;
  3448. if (result.classes) { line.styleClasses = result.classes; }
  3449. else if (line.styleClasses) { line.styleClasses = null; }
  3450. if (updateFrontier === cm.doc.highlightFrontier)
  3451. { cm.doc.modeFrontier = Math.max(cm.doc.modeFrontier, ++cm.doc.highlightFrontier); }
  3452. }
  3453. return line.styles
  3454. }
  3455. function getContextBefore(cm, n, precise) {
  3456. var doc = cm.doc, display = cm.display;
  3457. if (!doc.mode.startState) { return new Context(doc, true, n) }
  3458. var start = findStartLine(cm, n, precise);
  3459. var saved = start > doc.first && getLine(doc, start - 1).stateAfter;
  3460. var context = saved ? Context.fromSaved(doc, saved, start) : new Context(doc, startState(doc.mode), start);
  3461. doc.iter(start, n, function (line) {
  3462. processLine(cm, line.text, context);
  3463. var pos = context.line;
  3464. line.stateAfter = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo ? context.save() : null;
  3465. context.nextLine();
  3466. });
  3467. if (precise) { doc.modeFrontier = context.line; }
  3468. return context
  3469. }
  3470. // Lightweight form of highlight -- proceed over this line and
  3471. // update state, but don't save a style array. Used for lines that
  3472. // aren't currently visible.
  3473. function processLine(cm, text, context, startAt) {
  3474. var mode = cm.doc.mode;
  3475. var stream = new StringStream(text, cm.options.tabSize, context);
  3476. stream.start = stream.pos = startAt || 0;
  3477. if (text == "") { callBlankLine(mode, context.state); }
  3478. while (!stream.eol()) {
  3479. readToken(mode, stream, context.state);
  3480. stream.start = stream.pos;
  3481. }
  3482. }
  3483. function callBlankLine(mode, state) {
  3484. if (mode.blankLine) { return mode.blankLine(state) }
  3485. if (!mode.innerMode) { return }
  3486. var inner = innerMode(mode, state);
  3487. if (inner.mode.blankLine) { return inner.mode.blankLine(inner.state) }
  3488. }
  3489. function readToken(mode, stream, state, inner) {
  3490. for (var i = 0; i < 10; i++) {
  3491. if (inner) { inner[0] = innerMode(mode, state).mode; }
  3492. var style = mode.token(stream, state);
  3493. if (stream.pos > stream.start) { return style }
  3494. }
  3495. throw new Error("Mode " + mode.name + " failed to advance stream.")
  3496. }
  3497. var Token = function(stream, type, state) {
  3498. this.start = stream.start; this.end = stream.pos;
  3499. this.string = stream.current();
  3500. this.type = type || null;
  3501. this.state = state;
  3502. };
  3503. // Utility for getTokenAt and getLineTokens
  3504. function takeToken(cm, pos, precise, asArray) {
  3505. var doc = cm.doc, mode = doc.mode, style;
  3506. pos = clipPos(doc, pos);
  3507. var line = getLine(doc, pos.line), context = getContextBefore(cm, pos.line, precise);
  3508. var stream = new StringStream(line.text, cm.options.tabSize, context), tokens;
  3509. if (asArray) { tokens = []; }
  3510. while ((asArray || stream.pos < pos.ch) && !stream.eol()) {
  3511. stream.start = stream.pos;
  3512. style = readToken(mode, stream, context.state);
  3513. if (asArray) { tokens.push(new Token(stream, style, copyState(doc.mode, context.state))); }
  3514. }
  3515. return asArray ? tokens : new Token(stream, style, context.state)
  3516. }
  3517. function extractLineClasses(type, output) {
  3518. if (type) { for (;;) {
  3519. var lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/);
  3520. if (!lineClass) { break }
  3521. type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length);
  3522. var prop = lineClass[1] ? "bgClass" : "textClass";
  3523. if (output[prop] == null)
  3524. { output[prop] = lineClass[2]; }
  3525. else if (!(new RegExp("(?:^|\s)" + lineClass[2] + "(?:$|\s)")).test(output[prop]))
  3526. { output[prop] += " " + lineClass[2]; }
  3527. } }
  3528. return type
  3529. }
  3530. // Run the given mode's parser over a line, calling f for each token.
  3531. function runMode(cm, text, mode, context, f, lineClasses, forceToEnd) {
  3532. var flattenSpans = mode.flattenSpans;
  3533. if (flattenSpans == null) { flattenSpans = cm.options.flattenSpans; }
  3534. var curStart = 0, curStyle = null;
  3535. var stream = new StringStream(text, cm.options.tabSize, context), style;
  3536. var inner = cm.options.addModeClass && [null];
  3537. if (text == "") { extractLineClasses(callBlankLine(mode, context.state), lineClasses); }
  3538. while (!stream.eol()) {
  3539. if (stream.pos > cm.options.maxHighlightLength) {
  3540. flattenSpans = false;
  3541. if (forceToEnd) { processLine(cm, text, context, stream.pos); }
  3542. stream.pos = text.length;
  3543. style = null;
  3544. } else {
  3545. style = extractLineClasses(readToken(mode, stream, context.state, inner), lineClasses);
  3546. }
  3547. if (inner) {
  3548. var mName = inner[0].name;
  3549. if (mName) { style = "m-" + (style ? mName + " " + style : mName); }
  3550. }
  3551. if (!flattenSpans || curStyle != style) {
  3552. while (curStart < stream.start) {
  3553. curStart = Math.min(stream.start, curStart + 5000);
  3554. f(curStart, curStyle);
  3555. }
  3556. curStyle = style;
  3557. }
  3558. stream.start = stream.pos;
  3559. }
  3560. while (curStart < stream.pos) {
  3561. // Webkit seems to refuse to render text nodes longer than 57444
  3562. // characters, and returns inaccurate measurements in nodes
  3563. // starting around 5000 chars.
  3564. var pos = Math.min(stream.pos, curStart + 5000);
  3565. f(pos, curStyle);
  3566. curStart = pos;
  3567. }
  3568. }
  3569. // Finds the line to start with when starting a parse. Tries to
  3570. // find a line with a stateAfter, so that it can start with a
  3571. // valid state. If that fails, it returns the line with the
  3572. // smallest indentation, which tends to need the least context to
  3573. // parse correctly.
  3574. function findStartLine(cm, n, precise) {
  3575. var minindent, minline, doc = cm.doc;
  3576. var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100);
  3577. for (var search = n; search > lim; --search) {
  3578. if (search <= doc.first) { return doc.first }
  3579. var line = getLine(doc, search - 1), after = line.stateAfter;
  3580. if (after && (!precise || search + (after instanceof SavedContext ? after.lookAhead : 0) <= doc.modeFrontier))
  3581. { return search }
  3582. var indented = countColumn(line.text, null, cm.options.tabSize);
  3583. if (minline == null || minindent > indented) {
  3584. minline = search - 1;
  3585. minindent = indented;
  3586. }
  3587. }
  3588. return minline
  3589. }
  3590. function retreatFrontier(doc, n) {
  3591. doc.modeFrontier = Math.min(doc.modeFrontier, n);
  3592. if (doc.highlightFrontier < n - 10) { return }
  3593. var start = doc.first;
  3594. for (var line = n - 1; line > start; line--) {
  3595. var saved = getLine(doc, line).stateAfter;
  3596. // change is on 3
  3597. // state on line 1 looked ahead 2 -- so saw 3
  3598. // test 1 + 2 < 3 should cover this
  3599. if (saved && (!(saved instanceof SavedContext) || line + saved.lookAhead < n)) {
  3600. start = line + 1;
  3601. break
  3602. }
  3603. }
  3604. doc.highlightFrontier = Math.min(doc.highlightFrontier, start);
  3605. }
  3606. // LINE DATA STRUCTURE
  3607. // Line objects. These hold state related to a line, including
  3608. // highlighting info (the styles array).
  3609. var Line = function(text, markedSpans, estimateHeight) {
  3610. this.text = text;
  3611. attachMarkedSpans(this, markedSpans);
  3612. this.height = estimateHeight ? estimateHeight(this) : 1;
  3613. };
  3614. Line.prototype.lineNo = function () { return lineNo(this) };
  3615. eventMixin(Line);
  3616. // Change the content (text, markers) of a line. Automatically
  3617. // invalidates cached information and tries to re-estimate the
  3618. // line's height.
  3619. function updateLine(line, text, markedSpans, estimateHeight) {
  3620. line.text = text;
  3621. if (line.stateAfter) { line.stateAfter = null; }
  3622. if (line.styles) { line.styles = null; }
  3623. if (line.order != null) { line.order = null; }
  3624. detachMarkedSpans(line);
  3625. attachMarkedSpans(line, markedSpans);
  3626. var estHeight = estimateHeight ? estimateHeight(line) : 1;
  3627. if (estHeight != line.height) { updateLineHeight(line, estHeight); }
  3628. }
  3629. // Detach a line from the document tree and its markers.
  3630. function cleanUpLine(line) {
  3631. line.parent = null;
  3632. detachMarkedSpans(line);
  3633. }
  3634. // Convert a style as returned by a mode (either null, or a string
  3635. // containing one or more styles) to a CSS style. This is cached,
  3636. // and also looks for line-wide styles.
  3637. var styleToClassCache = {};
  3638. var styleToClassCacheWithMode = {};
  3639. function interpretTokenStyle(style, options) {
  3640. if (!style || /^\s*$/.test(style)) { return null }
  3641. var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache;
  3642. return cache[style] ||
  3643. (cache[style] = style.replace(/\S+/g, "cm-$&"))
  3644. }
  3645. // Render the DOM representation of the text of a line. Also builds
  3646. // up a 'line map', which points at the DOM nodes that represent
  3647. // specific stretches of text, and is used by the measuring code.
  3648. // The returned object contains the DOM node, this map, and
  3649. // information about line-wide styles that were set by the mode.
  3650. function buildLineContent(cm, lineView) {
  3651. // The padding-right forces the element to have a 'border', which
  3652. // is needed on Webkit to be able to get line-level bounding
  3653. // rectangles for it (in measureChar).
  3654. var content = eltP("span", null, null, webkit ? "padding-right: .1px" : null);
  3655. var builder = {pre: eltP("pre", [content], "CodeMirror-line"), content: content,
  3656. col: 0, pos: 0, cm: cm,
  3657. trailingSpace: false,
  3658. splitSpaces: (ie || webkit) && cm.getOption("lineWrapping")};
  3659. lineView.measure = {};
  3660. // Iterate over the logical lines that make up this visual line.
  3661. for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) {
  3662. var line = i ? lineView.rest[i - 1] : lineView.line, order = (void 0);
  3663. builder.pos = 0;
  3664. builder.addToken = buildToken;
  3665. // Optionally wire in some hacks into the token-rendering
  3666. // algorithm, to deal with browser quirks.
  3667. if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line, cm.doc.direction)))
  3668. { builder.addToken = buildTokenBadBidi(builder.addToken, order); }
  3669. builder.map = [];
  3670. var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line);
  3671. insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate));
  3672. if (line.styleClasses) {
  3673. if (line.styleClasses.bgClass)
  3674. { builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || ""); }
  3675. if (line.styleClasses.textClass)
  3676. { builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || ""); }
  3677. }
  3678. // Ensure at least a single node is present, for measuring.
  3679. if (builder.map.length == 0)
  3680. { builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure))); }
  3681. // Store the map and a cache object for the current logical line
  3682. if (i == 0) {
  3683. lineView.measure.map = builder.map;
  3684. lineView.measure.cache = {};
  3685. } else {
  3686. (lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map)
  3687. ;(lineView.measure.caches || (lineView.measure.caches = [])).push({});
  3688. }
  3689. }
  3690. // See issue #2901
  3691. if (webkit) {
  3692. var last = builder.content.lastChild;
  3693. if (/\bcm-tab\b/.test(last.className) || (last.querySelector && last.querySelector(".cm-tab")))
  3694. { builder.content.className = "cm-tab-wrap-hack"; }
  3695. }
  3696. signal(cm, "renderLine", cm, lineView.line, builder.pre);
  3697. if (builder.pre.className)
  3698. { builder.textClass = joinClasses(builder.pre.className, builder.textClass || ""); }
  3699. return builder
  3700. }
  3701. function defaultSpecialCharPlaceholder(ch) {
  3702. var token = elt("span", "\u2022", "cm-invalidchar");
  3703. token.title = "\\u" + ch.charCodeAt(0).toString(16);
  3704. token.setAttribute("aria-label", token.title);
  3705. return token
  3706. }
  3707. // Build up the DOM representation for a single token, and add it to
  3708. // the line map. Takes care to render special characters separately.
  3709. function buildToken(builder, text, style, startStyle, endStyle, title, css) {
  3710. if (!text) { return }
  3711. var displayText = builder.splitSpaces ? splitSpaces(text, builder.trailingSpace) : text;
  3712. var special = builder.cm.state.specialChars, mustWrap = false;
  3713. var content;
  3714. if (!special.test(text)) {
  3715. builder.col += text.length;
  3716. content = document.createTextNode(displayText);
  3717. builder.map.push(builder.pos, builder.pos + text.length, content);
  3718. if (ie && ie_version < 9) { mustWrap = true; }
  3719. builder.pos += text.length;
  3720. } else {
  3721. content = document.createDocumentFragment();
  3722. var pos = 0;
  3723. while (true) {
  3724. special.lastIndex = pos;
  3725. var m = special.exec(text);
  3726. var skipped = m ? m.index - pos : text.length - pos;
  3727. if (skipped) {
  3728. var txt = document.createTextNode(displayText.slice(pos, pos + skipped));
  3729. if (ie && ie_version < 9) { content.appendChild(elt("span", [txt])); }
  3730. else { content.appendChild(txt); }
  3731. builder.map.push(builder.pos, builder.pos + skipped, txt);
  3732. builder.col += skipped;
  3733. builder.pos += skipped;
  3734. }
  3735. if (!m) { break }
  3736. pos += skipped + 1;
  3737. var txt$1 = (void 0);
  3738. if (m[0] == "\t") {
  3739. var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize;
  3740. txt$1 = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab"));
  3741. txt$1.setAttribute("role", "presentation");
  3742. txt$1.setAttribute("cm-text", "\t");
  3743. builder.col += tabWidth;
  3744. } else if (m[0] == "\r" || m[0] == "\n") {
  3745. txt$1 = content.appendChild(elt("span", m[0] == "\r" ? "\u240d" : "\u2424", "cm-invalidchar"));
  3746. txt$1.setAttribute("cm-text", m[0]);
  3747. builder.col += 1;
  3748. } else {
  3749. txt$1 = builder.cm.options.specialCharPlaceholder(m[0]);
  3750. txt$1.setAttribute("cm-text", m[0]);
  3751. if (ie && ie_version < 9) { content.appendChild(elt("span", [txt$1])); }
  3752. else { content.appendChild(txt$1); }
  3753. builder.col += 1;
  3754. }
  3755. builder.map.push(builder.pos, builder.pos + 1, txt$1);
  3756. builder.pos++;
  3757. }
  3758. }
  3759. builder.trailingSpace = displayText.charCodeAt(text.length - 1) == 32;
  3760. if (style || startStyle || endStyle || mustWrap || css) {
  3761. var fullStyle = style || "";
  3762. if (startStyle) { fullStyle += startStyle; }
  3763. if (endStyle) { fullStyle += endStyle; }
  3764. var token = elt("span", [content], fullStyle, css);
  3765. if (title) { token.title = title; }
  3766. return builder.content.appendChild(token)
  3767. }
  3768. builder.content.appendChild(content);
  3769. }
  3770. function splitSpaces(text, trailingBefore) {
  3771. if (text.length > 1 && !/ /.test(text)) { return text }
  3772. var spaceBefore = trailingBefore, result = "";
  3773. for (var i = 0; i < text.length; i++) {
  3774. var ch = text.charAt(i);
  3775. if (ch == " " && spaceBefore && (i == text.length - 1 || text.charCodeAt(i + 1) == 32))
  3776. { ch = "\u00a0"; }
  3777. result += ch;
  3778. spaceBefore = ch == " ";
  3779. }
  3780. return result
  3781. }
  3782. // Work around nonsense dimensions being reported for stretches of
  3783. // right-to-left text.
  3784. function buildTokenBadBidi(inner, order) {
  3785. return function (builder, text, style, startStyle, endStyle, title, css) {
  3786. style = style ? style + " cm-force-border" : "cm-force-border";
  3787. var start = builder.pos, end = start + text.length;
  3788. for (;;) {
  3789. // Find the part that overlaps with the start of this text
  3790. var part = (void 0);
  3791. for (var i = 0; i < order.length; i++) {
  3792. part = order[i];
  3793. if (part.to > start && part.from <= start) { break }
  3794. }
  3795. if (part.to >= end) { return inner(builder, text, style, startStyle, endStyle, title, css) }
  3796. inner(builder, text.slice(0, part.to - start), style, startStyle, null, title, css);
  3797. startStyle = null;
  3798. text = text.slice(part.to - start);
  3799. start = part.to;
  3800. }
  3801. }
  3802. }
  3803. function buildCollapsedSpan(builder, size, marker, ignoreWidget) {
  3804. var widget = !ignoreWidget && marker.widgetNode;
  3805. if (widget) { builder.map.push(builder.pos, builder.pos + size, widget); }
  3806. if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) {
  3807. if (!widget)
  3808. { widget = builder.content.appendChild(document.createElement("span")); }
  3809. widget.setAttribute("cm-marker", marker.id);
  3810. }
  3811. if (widget) {
  3812. builder.cm.display.input.setUneditable(widget);
  3813. builder.content.appendChild(widget);
  3814. }
  3815. builder.pos += size;
  3816. builder.trailingSpace = false;
  3817. }
  3818. // Outputs a number of spans to make up a line, taking highlighting
  3819. // and marked text into account.
  3820. function insertLineContent(line, builder, styles) {
  3821. var spans = line.markedSpans, allText = line.text, at = 0;
  3822. if (!spans) {
  3823. for (var i$1 = 1; i$1 < styles.length; i$1+=2)
  3824. { builder.addToken(builder, allText.slice(at, at = styles[i$1]), interpretTokenStyle(styles[i$1+1], builder.cm.options)); }
  3825. return
  3826. }
  3827. var len = allText.length, pos = 0, i = 1, text = "", style, css;
  3828. var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, title, collapsed;
  3829. for (;;) {
  3830. if (nextChange == pos) { // Update current marker set
  3831. spanStyle = spanEndStyle = spanStartStyle = title = css = "";
  3832. collapsed = null; nextChange = Infinity;
  3833. var foundBookmarks = [], endStyles = (void 0);
  3834. for (var j = 0; j < spans.length; ++j) {
  3835. var sp = spans[j], m = sp.marker;
  3836. if (m.type == "bookmark" && sp.from == pos && m.widgetNode) {
  3837. foundBookmarks.push(m);
  3838. } else if (sp.from <= pos && (sp.to == null || sp.to > pos || m.collapsed && sp.to == pos && sp.from == pos)) {
  3839. if (sp.to != null && sp.to != pos && nextChange > sp.to) {
  3840. nextChange = sp.to;
  3841. spanEndStyle = "";
  3842. }
  3843. if (m.className) { spanStyle += " " + m.className; }
  3844. if (m.css) { css = (css ? css + ";" : "") + m.css; }
  3845. if (m.startStyle && sp.from == pos) { spanStartStyle += " " + m.startStyle; }
  3846. if (m.endStyle && sp.to == nextChange) { (endStyles || (endStyles = [])).push(m.endStyle, sp.to); }
  3847. if (m.title && !title) { title = m.title; }
  3848. if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0))
  3849. { collapsed = sp; }
  3850. } else if (sp.from > pos && nextChange > sp.from) {
  3851. nextChange = sp.from;
  3852. }
  3853. }
  3854. if (endStyles) { for (var j$1 = 0; j$1 < endStyles.length; j$1 += 2)
  3855. { if (endStyles[j$1 + 1] == nextChange) { spanEndStyle += " " + endStyles[j$1]; } } }
  3856. if (!collapsed || collapsed.from == pos) { for (var j$2 = 0; j$2 < foundBookmarks.length; ++j$2)
  3857. { buildCollapsedSpan(builder, 0, foundBookmarks[j$2]); } }
  3858. if (collapsed && (collapsed.from || 0) == pos) {
  3859. buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos,
  3860. collapsed.marker, collapsed.from == null);
  3861. if (collapsed.to == null) { return }
  3862. if (collapsed.to == pos) { collapsed = false; }
  3863. }
  3864. }
  3865. if (pos >= len) { break }
  3866. var upto = Math.min(len, nextChange);
  3867. while (true) {
  3868. if (text) {
  3869. var end = pos + text.length;
  3870. if (!collapsed) {
  3871. var tokenText = end > upto ? text.slice(0, upto - pos) : text;
  3872. builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle,
  3873. spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", title, css);
  3874. }
  3875. if (end >= upto) {text = text.slice(upto - pos); pos = upto; break}
  3876. pos = end;
  3877. spanStartStyle = "";
  3878. }
  3879. text = allText.slice(at, at = styles[i++]);
  3880. style = interpretTokenStyle(styles[i++], builder.cm.options);
  3881. }
  3882. }
  3883. }
  3884. // These objects are used to represent the visible (currently drawn)
  3885. // part of the document. A LineView may correspond to multiple
  3886. // logical lines, if those are connected by collapsed ranges.
  3887. function LineView(doc, line, lineN) {
  3888. // The starting line
  3889. this.line = line;
  3890. // Continuing lines, if any
  3891. this.rest = visualLineContinued(line);
  3892. // Number of logical lines in this visual line
  3893. this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1;
  3894. this.node = this.text = null;
  3895. this.hidden = lineIsHidden(doc, line);
  3896. }
  3897. // Create a range of LineView objects for the given lines.
  3898. function buildViewArray(cm, from, to) {
  3899. var array = [], nextPos;
  3900. for (var pos = from; pos < to; pos = nextPos) {
  3901. var view = new LineView(cm.doc, getLine(cm.doc, pos), pos);
  3902. nextPos = pos + view.size;
  3903. array.push(view);
  3904. }
  3905. return array
  3906. }
  3907. var operationGroup = null;
  3908. function pushOperation(op) {
  3909. if (operationGroup) {
  3910. operationGroup.ops.push(op);
  3911. } else {
  3912. op.ownsGroup = operationGroup = {
  3913. ops: [op],
  3914. delayedCallbacks: []
  3915. };
  3916. }
  3917. }
  3918. function fireCallbacksForOps(group) {
  3919. // Calls delayed callbacks and cursorActivity handlers until no
  3920. // new ones appear
  3921. var callbacks = group.delayedCallbacks, i = 0;
  3922. do {
  3923. for (; i < callbacks.length; i++)
  3924. { callbacks[i].call(null); }
  3925. for (var j = 0; j < group.ops.length; j++) {
  3926. var op = group.ops[j];
  3927. if (op.cursorActivityHandlers)
  3928. { while (op.cursorActivityCalled < op.cursorActivityHandlers.length)
  3929. { op.cursorActivityHandlers[op.cursorActivityCalled++].call(null, op.cm); } }
  3930. }
  3931. } while (i < callbacks.length)
  3932. }
  3933. function finishOperation(op, endCb) {
  3934. var group = op.ownsGroup;
  3935. if (!group) { return }
  3936. try { fireCallbacksForOps(group); }
  3937. finally {
  3938. operationGroup = null;
  3939. endCb(group);
  3940. }
  3941. }
  3942. var orphanDelayedCallbacks = null;
  3943. // Often, we want to signal events at a point where we are in the
  3944. // middle of some work, but don't want the handler to start calling
  3945. // other methods on the editor, which might be in an inconsistent
  3946. // state or simply not expect any other events to happen.
  3947. // signalLater looks whether there are any handlers, and schedules
  3948. // them to be executed when the last operation ends, or, if no
  3949. // operation is active, when a timeout fires.
  3950. function signalLater(emitter, type /*, values...*/) {
  3951. var arr = getHandlers(emitter, type);
  3952. if (!arr.length) { return }
  3953. var args = Array.prototype.slice.call(arguments, 2), list;
  3954. if (operationGroup) {
  3955. list = operationGroup.delayedCallbacks;
  3956. } else if (orphanDelayedCallbacks) {
  3957. list = orphanDelayedCallbacks;
  3958. } else {
  3959. list = orphanDelayedCallbacks = [];
  3960. setTimeout(fireOrphanDelayed, 0);
  3961. }
  3962. var loop = function ( i ) {
  3963. list.push(function () { return arr[i].apply(null, args); });
  3964. };
  3965. for (var i = 0; i < arr.length; ++i)
  3966. loop( i );
  3967. }
  3968. function fireOrphanDelayed() {
  3969. var delayed = orphanDelayedCallbacks;
  3970. orphanDelayedCallbacks = null;
  3971. for (var i = 0; i < delayed.length; ++i) { delayed[i](); }
  3972. }
  3973. // When an aspect of a line changes, a string is added to
  3974. // lineView.changes. This updates the relevant part of the line's
  3975. // DOM structure.
  3976. function updateLineForChanges(cm, lineView, lineN, dims) {
  3977. for (var j = 0; j < lineView.changes.length; j++) {
  3978. var type = lineView.changes[j];
  3979. if (type == "text") { updateLineText(cm, lineView); }
  3980. else if (type == "gutter") { updateLineGutter(cm, lineView, lineN, dims); }
  3981. else if (type == "class") { updateLineClasses(cm, lineView); }
  3982. else if (type == "widget") { updateLineWidgets(cm, lineView, dims); }
  3983. }
  3984. lineView.changes = null;
  3985. }
  3986. // Lines with gutter elements, widgets or a background class need to
  3987. // be wrapped, and have the extra elements added to the wrapper div
  3988. function ensureLineWrapped(lineView) {
  3989. if (lineView.node == lineView.text) {
  3990. lineView.node = elt("div", null, null, "position: relative");
  3991. if (lineView.text.parentNode)
  3992. { lineView.text.parentNode.replaceChild(lineView.node, lineView.text); }
  3993. lineView.node.appendChild(lineView.text);
  3994. if (ie && ie_version < 8) { lineView.node.style.zIndex = 2; }
  3995. }
  3996. return lineView.node
  3997. }
  3998. function updateLineBackground(cm, lineView) {
  3999. var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass;
  4000. if (cls) { cls += " CodeMirror-linebackground"; }
  4001. if (lineView.background) {
  4002. if (cls) { lineView.background.className = cls; }
  4003. else { lineView.background.parentNode.removeChild(lineView.background); lineView.background = null; }
  4004. } else if (cls) {
  4005. var wrap = ensureLineWrapped(lineView);
  4006. lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild);
  4007. cm.display.input.setUneditable(lineView.background);
  4008. }
  4009. }
  4010. // Wrapper around buildLineContent which will reuse the structure
  4011. // in display.externalMeasured when possible.
  4012. function getLineContent(cm, lineView) {
  4013. var ext = cm.display.externalMeasured;
  4014. if (ext && ext.line == lineView.line) {
  4015. cm.display.externalMeasured = null;
  4016. lineView.measure = ext.measure;
  4017. return ext.built
  4018. }
  4019. return buildLineContent(cm, lineView)
  4020. }
  4021. // Redraw the line's text. Interacts with the background and text
  4022. // classes because the mode may output tokens that influence these
  4023. // classes.
  4024. function updateLineText(cm, lineView) {
  4025. var cls = lineView.text.className;
  4026. var built = getLineContent(cm, lineView);
  4027. if (lineView.text == lineView.node) { lineView.node = built.pre; }
  4028. lineView.text.parentNode.replaceChild(built.pre, lineView.text);
  4029. lineView.text = built.pre;
  4030. if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) {
  4031. lineView.bgClass = built.bgClass;
  4032. lineView.textClass = built.textClass;
  4033. updateLineClasses(cm, lineView);
  4034. } else if (cls) {
  4035. lineView.text.className = cls;
  4036. }
  4037. }
  4038. function updateLineClasses(cm, lineView) {
  4039. updateLineBackground(cm, lineView);
  4040. if (lineView.line.wrapClass)
  4041. { ensureLineWrapped(lineView).className = lineView.line.wrapClass; }
  4042. else if (lineView.node != lineView.text)
  4043. { lineView.node.className = ""; }
  4044. var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass;
  4045. lineView.text.className = textClass || "";
  4046. }
  4047. function updateLineGutter(cm, lineView, lineN, dims) {
  4048. if (lineView.gutter) {
  4049. lineView.node.removeChild(lineView.gutter);
  4050. lineView.gutter = null;
  4051. }
  4052. if (lineView.gutterBackground) {
  4053. lineView.node.removeChild(lineView.gutterBackground);
  4054. lineView.gutterBackground = null;
  4055. }
  4056. if (lineView.line.gutterClass) {
  4057. var wrap = ensureLineWrapped(lineView);
  4058. lineView.gutterBackground = elt("div", null, "CodeMirror-gutter-background " + lineView.line.gutterClass,
  4059. ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px; width: " + (dims.gutterTotalWidth) + "px"));
  4060. cm.display.input.setUneditable(lineView.gutterBackground);
  4061. wrap.insertBefore(lineView.gutterBackground, lineView.text);
  4062. }
  4063. var markers = lineView.line.gutterMarkers;
  4064. if (cm.options.lineNumbers || markers) {
  4065. var wrap$1 = ensureLineWrapped(lineView);
  4066. var gutterWrap = lineView.gutter = elt("div", null, "CodeMirror-gutter-wrapper", ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px"));
  4067. cm.display.input.setUneditable(gutterWrap);
  4068. wrap$1.insertBefore(gutterWrap, lineView.text);
  4069. if (lineView.line.gutterClass)
  4070. { gutterWrap.className += " " + lineView.line.gutterClass; }
  4071. if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"]))
  4072. { lineView.lineNumber = gutterWrap.appendChild(
  4073. elt("div", lineNumberFor(cm.options, lineN),
  4074. "CodeMirror-linenumber CodeMirror-gutter-elt",
  4075. ("left: " + (dims.gutterLeft["CodeMirror-linenumbers"]) + "px; width: " + (cm.display.lineNumInnerWidth) + "px"))); }
  4076. if (markers) { for (var k = 0; k < cm.options.gutters.length; ++k) {
  4077. var id = cm.options.gutters[k], found = markers.hasOwnProperty(id) && markers[id];
  4078. if (found)
  4079. { gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt",
  4080. ("left: " + (dims.gutterLeft[id]) + "px; width: " + (dims.gutterWidth[id]) + "px"))); }
  4081. } }
  4082. }
  4083. }
  4084. function updateLineWidgets(cm, lineView, dims) {
  4085. if (lineView.alignable) { lineView.alignable = null; }
  4086. for (var node = lineView.node.firstChild, next = (void 0); node; node = next) {
  4087. next = node.nextSibling;
  4088. if (node.className == "CodeMirror-linewidget")
  4089. { lineView.node.removeChild(node); }
  4090. }
  4091. insertLineWidgets(cm, lineView, dims);
  4092. }
  4093. // Build a line's DOM representation from scratch
  4094. function buildLineElement(cm, lineView, lineN, dims) {
  4095. var built = getLineContent(cm, lineView);
  4096. lineView.text = lineView.node = built.pre;
  4097. if (built.bgClass) { lineView.bgClass = built.bgClass; }
  4098. if (built.textClass) { lineView.textClass = built.textClass; }
  4099. updateLineClasses(cm, lineView);
  4100. updateLineGutter(cm, lineView, lineN, dims);
  4101. insertLineWidgets(cm, lineView, dims);
  4102. return lineView.node
  4103. }
  4104. // A lineView may contain multiple logical lines (when merged by
  4105. // collapsed spans). The widgets for all of them need to be drawn.
  4106. function insertLineWidgets(cm, lineView, dims) {
  4107. insertLineWidgetsFor(cm, lineView.line, lineView, dims, true);
  4108. if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++)
  4109. { insertLineWidgetsFor(cm, lineView.rest[i], lineView, dims, false); } }
  4110. }
  4111. function insertLineWidgetsFor(cm, line, lineView, dims, allowAbove) {
  4112. if (!line.widgets) { return }
  4113. var wrap = ensureLineWrapped(lineView);
  4114. for (var i = 0, ws = line.widgets; i < ws.length; ++i) {
  4115. var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget");
  4116. if (!widget.handleMouseEvents) { node.setAttribute("cm-ignore-events", "true"); }
  4117. positionLineWidget(widget, node, lineView, dims);
  4118. cm.display.input.setUneditable(node);
  4119. if (allowAbove && widget.above)
  4120. { wrap.insertBefore(node, lineView.gutter || lineView.text); }
  4121. else
  4122. { wrap.appendChild(node); }
  4123. signalLater(widget, "redraw");
  4124. }
  4125. }
  4126. function positionLineWidget(widget, node, lineView, dims) {
  4127. if (widget.noHScroll) {
  4128. (lineView.alignable || (lineView.alignable = [])).push(node);
  4129. var width = dims.wrapperWidth;
  4130. node.style.left = dims.fixedPos + "px";
  4131. if (!widget.coverGutter) {
  4132. width -= dims.gutterTotalWidth;
  4133. node.style.paddingLeft = dims.gutterTotalWidth + "px";
  4134. }
  4135. node.style.width = width + "px";
  4136. }
  4137. if (widget.coverGutter) {
  4138. node.style.zIndex = 5;
  4139. node.style.position = "relative";
  4140. if (!widget.noHScroll) { node.style.marginLeft = -dims.gutterTotalWidth + "px"; }
  4141. }
  4142. }
  4143. function widgetHeight(widget) {
  4144. if (widget.height != null) { return widget.height }
  4145. var cm = widget.doc.cm;
  4146. if (!cm) { return 0 }
  4147. if (!contains(document.body, widget.node)) {
  4148. var parentStyle = "position: relative;";
  4149. if (widget.coverGutter)
  4150. { parentStyle += "margin-left: -" + cm.display.gutters.offsetWidth + "px;"; }
  4151. if (widget.noHScroll)
  4152. { parentStyle += "width: " + cm.display.wrapper.clientWidth + "px;"; }
  4153. removeChildrenAndAdd(cm.display.measure, elt("div", [widget.node], null, parentStyle));
  4154. }
  4155. return widget.height = widget.node.parentNode.offsetHeight
  4156. }
  4157. // Return true when the given mouse event happened in a widget
  4158. function eventInWidget(display, e) {
  4159. for (var n = e_target(e); n != display.wrapper; n = n.parentNode) {
  4160. if (!n || (n.nodeType == 1 && n.getAttribute("cm-ignore-events") == "true") ||
  4161. (n.parentNode == display.sizer && n != display.mover))
  4162. { return true }
  4163. }
  4164. }
  4165. // POSITION MEASUREMENT
  4166. function paddingTop(display) {return display.lineSpace.offsetTop}
  4167. function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight}
  4168. function paddingH(display) {
  4169. if (display.cachedPaddingH) { return display.cachedPaddingH }
  4170. var e = removeChildrenAndAdd(display.measure, elt("pre", "x"));
  4171. var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle;
  4172. var data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)};
  4173. if (!isNaN(data.left) && !isNaN(data.right)) { display.cachedPaddingH = data; }
  4174. return data
  4175. }
  4176. function scrollGap(cm) { return scrollerGap - cm.display.nativeBarWidth }
  4177. function displayWidth(cm) {
  4178. return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth
  4179. }
  4180. function displayHeight(cm) {
  4181. return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight
  4182. }
  4183. // Ensure the lineView.wrapping.heights array is populated. This is
  4184. // an array of bottom offsets for the lines that make up a drawn
  4185. // line. When lineWrapping is on, there might be more than one
  4186. // height.
  4187. function ensureLineHeights(cm, lineView, rect) {
  4188. var wrapping = cm.options.lineWrapping;
  4189. var curWidth = wrapping && displayWidth(cm);
  4190. if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) {
  4191. var heights = lineView.measure.heights = [];
  4192. if (wrapping) {
  4193. lineView.measure.width = curWidth;
  4194. var rects = lineView.text.firstChild.getClientRects();
  4195. for (var i = 0; i < rects.length - 1; i++) {
  4196. var cur = rects[i], next = rects[i + 1];
  4197. if (Math.abs(cur.bottom - next.bottom) > 2)
  4198. { heights.push((cur.bottom + next.top) / 2 - rect.top); }
  4199. }
  4200. }
  4201. heights.push(rect.bottom - rect.top);
  4202. }
  4203. }
  4204. // Find a line map (mapping character offsets to text nodes) and a
  4205. // measurement cache for the given line number. (A line view might
  4206. // contain multiple lines when collapsed ranges are present.)
  4207. function mapFromLineView(lineView, line, lineN) {
  4208. if (lineView.line == line)
  4209. { return {map: lineView.measure.map, cache: lineView.measure.cache} }
  4210. for (var i = 0; i < lineView.rest.length; i++)
  4211. { if (lineView.rest[i] == line)
  4212. { return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i]} } }
  4213. for (var i$1 = 0; i$1 < lineView.rest.length; i$1++)
  4214. { if (lineNo(lineView.rest[i$1]) > lineN)
  4215. { return {map: lineView.measure.maps[i$1], cache: lineView.measure.caches[i$1], before: true} } }
  4216. }
  4217. // Render a line into the hidden node display.externalMeasured. Used
  4218. // when measurement is needed for a line that's not in the viewport.
  4219. function updateExternalMeasurement(cm, line) {
  4220. line = visualLine(line);
  4221. var lineN = lineNo(line);
  4222. var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN);
  4223. view.lineN = lineN;
  4224. var built = view.built = buildLineContent(cm, view);
  4225. view.text = built.pre;
  4226. removeChildrenAndAdd(cm.display.lineMeasure, built.pre);
  4227. return view
  4228. }
  4229. // Get a {top, bottom, left, right} box (in line-local coordinates)
  4230. // for a given character.
  4231. function measureChar(cm, line, ch, bias) {
  4232. return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias)
  4233. }
  4234. // Find a line view that corresponds to the given line number.
  4235. function findViewForLine(cm, lineN) {
  4236. if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo)
  4237. { return cm.display.view[findViewIndex(cm, lineN)] }
  4238. var ext = cm.display.externalMeasured;
  4239. if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size)
  4240. { return ext }
  4241. }
  4242. // Measurement can be split in two steps, the set-up work that
  4243. // applies to the whole line, and the measurement of the actual
  4244. // character. Functions like coordsChar, that need to do a lot of
  4245. // measurements in a row, can thus ensure that the set-up work is
  4246. // only done once.
  4247. function prepareMeasureForLine(cm, line) {
  4248. var lineN = lineNo(line);
  4249. var view = findViewForLine(cm, lineN);
  4250. if (view && !view.text) {
  4251. view = null;
  4252. } else if (view && view.changes) {
  4253. updateLineForChanges(cm, view, lineN, getDimensions(cm));
  4254. cm.curOp.forceUpdate = true;
  4255. }
  4256. if (!view)
  4257. { view = updateExternalMeasurement(cm, line); }
  4258. var info = mapFromLineView(view, line, lineN);
  4259. return {
  4260. line: line, view: view, rect: null,
  4261. map: info.map, cache: info.cache, before: info.before,
  4262. hasHeights: false
  4263. }
  4264. }
  4265. // Given a prepared measurement object, measures the position of an
  4266. // actual character (or fetches it from the cache).
  4267. function measureCharPrepared(cm, prepared, ch, bias, varHeight) {
  4268. if (prepared.before) { ch = -1; }
  4269. var key = ch + (bias || ""), found;
  4270. if (prepared.cache.hasOwnProperty(key)) {
  4271. found = prepared.cache[key];
  4272. } else {
  4273. if (!prepared.rect)
  4274. { prepared.rect = prepared.view.text.getBoundingClientRect(); }
  4275. if (!prepared.hasHeights) {
  4276. ensureLineHeights(cm, prepared.view, prepared.rect);
  4277. prepared.hasHeights = true;
  4278. }
  4279. found = measureCharInner(cm, prepared, ch, bias);
  4280. if (!found.bogus) { prepared.cache[key] = found; }
  4281. }
  4282. return {left: found.left, right: found.right,
  4283. top: varHeight ? found.rtop : found.top,
  4284. bottom: varHeight ? found.rbottom : found.bottom}
  4285. }
  4286. var nullRect = {left: 0, right: 0, top: 0, bottom: 0};
  4287. function nodeAndOffsetInLineMap(map$$1, ch, bias) {
  4288. var node, start, end, collapse, mStart, mEnd;
  4289. // First, search the line map for the text node corresponding to,
  4290. // or closest to, the target character.
  4291. for (var i = 0; i < map$$1.length; i += 3) {
  4292. mStart = map$$1[i];
  4293. mEnd = map$$1[i + 1];
  4294. if (ch < mStart) {
  4295. start = 0; end = 1;
  4296. collapse = "left";
  4297. } else if (ch < mEnd) {
  4298. start = ch - mStart;
  4299. end = start + 1;
  4300. } else if (i == map$$1.length - 3 || ch == mEnd && map$$1[i + 3] > ch) {
  4301. end = mEnd - mStart;
  4302. start = end - 1;
  4303. if (ch >= mEnd) { collapse = "right"; }
  4304. }
  4305. if (start != null) {
  4306. node = map$$1[i + 2];
  4307. if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right"))
  4308. { collapse = bias; }
  4309. if (bias == "left" && start == 0)
  4310. { while (i && map$$1[i - 2] == map$$1[i - 3] && map$$1[i - 1].insertLeft) {
  4311. node = map$$1[(i -= 3) + 2];
  4312. collapse = "left";
  4313. } }
  4314. if (bias == "right" && start == mEnd - mStart)
  4315. { while (i < map$$1.length - 3 && map$$1[i + 3] == map$$1[i + 4] && !map$$1[i + 5].insertLeft) {
  4316. node = map$$1[(i += 3) + 2];
  4317. collapse = "right";
  4318. } }
  4319. break
  4320. }
  4321. }
  4322. return {node: node, start: start, end: end, collapse: collapse, coverStart: mStart, coverEnd: mEnd}
  4323. }
  4324. function getUsefulRect(rects, bias) {
  4325. var rect = nullRect;
  4326. if (bias == "left") { for (var i = 0; i < rects.length; i++) {
  4327. if ((rect = rects[i]).left != rect.right) { break }
  4328. } } else { for (var i$1 = rects.length - 1; i$1 >= 0; i$1--) {
  4329. if ((rect = rects[i$1]).left != rect.right) { break }
  4330. } }
  4331. return rect
  4332. }
  4333. function measureCharInner(cm, prepared, ch, bias) {
  4334. var place = nodeAndOffsetInLineMap(prepared.map, ch, bias);
  4335. var node = place.node, start = place.start, end = place.end, collapse = place.collapse;
  4336. var rect;
  4337. if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates.
  4338. for (var i$1 = 0; i$1 < 4; i$1++) { // Retry a maximum of 4 times when nonsense rectangles are returned
  4339. while (start && isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) { --start; }
  4340. while (place.coverStart + end < place.coverEnd && isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) { ++end; }
  4341. if (ie && ie_version < 9 && start == 0 && end == place.coverEnd - place.coverStart)
  4342. { rect = node.parentNode.getBoundingClientRect(); }
  4343. else
  4344. { rect = getUsefulRect(range(node, start, end).getClientRects(), bias); }
  4345. if (rect.left || rect.right || start == 0) { break }
  4346. end = start;
  4347. start = start - 1;
  4348. collapse = "right";
  4349. }
  4350. if (ie && ie_version < 11) { rect = maybeUpdateRectForZooming(cm.display.measure, rect); }
  4351. } else { // If it is a widget, simply get the box for the whole widget.
  4352. if (start > 0) { collapse = bias = "right"; }
  4353. var rects;
  4354. if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1)
  4355. { rect = rects[bias == "right" ? rects.length - 1 : 0]; }
  4356. else
  4357. { rect = node.getBoundingClientRect(); }
  4358. }
  4359. if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) {
  4360. var rSpan = node.parentNode.getClientRects()[0];
  4361. if (rSpan)
  4362. { rect = {left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom}; }
  4363. else
  4364. { rect = nullRect; }
  4365. }
  4366. var rtop = rect.top - prepared.rect.top, rbot = rect.bottom - prepared.rect.top;
  4367. var mid = (rtop + rbot) / 2;
  4368. var heights = prepared.view.measure.heights;
  4369. var i = 0;
  4370. for (; i < heights.length - 1; i++)
  4371. { if (mid < heights[i]) { break } }
  4372. var top = i ? heights[i - 1] : 0, bot = heights[i];
  4373. var result = {left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left,
  4374. right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left,
  4375. top: top, bottom: bot};
  4376. if (!rect.left && !rect.right) { result.bogus = true; }
  4377. if (!cm.options.singleCursorHeightPerLine) { result.rtop = rtop; result.rbottom = rbot; }
  4378. return result
  4379. }
  4380. // Work around problem with bounding client rects on ranges being
  4381. // returned incorrectly when zoomed on IE10 and below.
  4382. function maybeUpdateRectForZooming(measure, rect) {
  4383. if (!window.screen || screen.logicalXDPI == null ||
  4384. screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure))
  4385. { return rect }
  4386. var scaleX = screen.logicalXDPI / screen.deviceXDPI;
  4387. var scaleY = screen.logicalYDPI / screen.deviceYDPI;
  4388. return {left: rect.left * scaleX, right: rect.right * scaleX,
  4389. top: rect.top * scaleY, bottom: rect.bottom * scaleY}
  4390. }
  4391. function clearLineMeasurementCacheFor(lineView) {
  4392. if (lineView.measure) {
  4393. lineView.measure.cache = {};
  4394. lineView.measure.heights = null;
  4395. if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++)
  4396. { lineView.measure.caches[i] = {}; } }
  4397. }
  4398. }
  4399. function clearLineMeasurementCache(cm) {
  4400. cm.display.externalMeasure = null;
  4401. removeChildren(cm.display.lineMeasure);
  4402. for (var i = 0; i < cm.display.view.length; i++)
  4403. { clearLineMeasurementCacheFor(cm.display.view[i]); }
  4404. }
  4405. function clearCaches(cm) {
  4406. clearLineMeasurementCache(cm);
  4407. cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null;
  4408. if (!cm.options.lineWrapping) { cm.display.maxLineChanged = true; }
  4409. cm.display.lineNumChars = null;
  4410. }
  4411. function pageScrollX() {
  4412. // Work around https://bugs.chromium.org/p/chromium/issues/detail?id=489206
  4413. // which causes page_Offset and bounding client rects to use
  4414. // different reference viewports and invalidate our calculations.
  4415. if (chrome && android) { return -(document.body.getBoundingClientRect().left - parseInt(getComputedStyle(document.body).marginLeft)) }
  4416. return window.pageXOffset || (document.documentElement || document.body).scrollLeft
  4417. }
  4418. function pageScrollY() {
  4419. if (chrome && android) { return -(document.body.getBoundingClientRect().top - parseInt(getComputedStyle(document.body).marginTop)) }
  4420. return window.pageYOffset || (document.documentElement || document.body).scrollTop
  4421. }
  4422. function widgetTopHeight(lineObj) {
  4423. var height = 0;
  4424. if (lineObj.widgets) { for (var i = 0; i < lineObj.widgets.length; ++i) { if (lineObj.widgets[i].above)
  4425. { height += widgetHeight(lineObj.widgets[i]); } } }
  4426. return height
  4427. }
  4428. // Converts a {top, bottom, left, right} box from line-local
  4429. // coordinates into another coordinate system. Context may be one of
  4430. // "line", "div" (display.lineDiv), "local"./null (editor), "window",
  4431. // or "page".
  4432. function intoCoordSystem(cm, lineObj, rect, context, includeWidgets) {
  4433. if (!includeWidgets) {
  4434. var height = widgetTopHeight(lineObj);
  4435. rect.top += height; rect.bottom += height;
  4436. }
  4437. if (context == "line") { return rect }
  4438. if (!context) { context = "local"; }
  4439. var yOff = heightAtLine(lineObj);
  4440. if (context == "local") { yOff += paddingTop(cm.display); }
  4441. else { yOff -= cm.display.viewOffset; }
  4442. if (context == "page" || context == "window") {
  4443. var lOff = cm.display.lineSpace.getBoundingClientRect();
  4444. yOff += lOff.top + (context == "window" ? 0 : pageScrollY());
  4445. var xOff = lOff.left + (context == "window" ? 0 : pageScrollX());
  4446. rect.left += xOff; rect.right += xOff;
  4447. }
  4448. rect.top += yOff; rect.bottom += yOff;
  4449. return rect
  4450. }
  4451. // Coverts a box from "div" coords to another coordinate system.
  4452. // Context may be "window", "page", "div", or "local"./null.
  4453. function fromCoordSystem(cm, coords, context) {
  4454. if (context == "div") { return coords }
  4455. var left = coords.left, top = coords.top;
  4456. // First move into "page" coordinate system
  4457. if (context == "page") {
  4458. left -= pageScrollX();
  4459. top -= pageScrollY();
  4460. } else if (context == "local" || !context) {
  4461. var localBox = cm.display.sizer.getBoundingClientRect();
  4462. left += localBox.left;
  4463. top += localBox.top;
  4464. }
  4465. var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect();
  4466. return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top}
  4467. }
  4468. function charCoords(cm, pos, context, lineObj, bias) {
  4469. if (!lineObj) { lineObj = getLine(cm.doc, pos.line); }
  4470. return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context)
  4471. }
  4472. // Returns a box for a given cursor position, which may have an
  4473. // 'other' property containing the position of the secondary cursor
  4474. // on a bidi boundary.
  4475. // A cursor Pos(line, char, "before") is on the same visual line as `char - 1`
  4476. // and after `char - 1` in writing order of `char - 1`
  4477. // A cursor Pos(line, char, "after") is on the same visual line as `char`
  4478. // and before `char` in writing order of `char`
  4479. // Examples (upper-case letters are RTL, lower-case are LTR):
  4480. // Pos(0, 1, ...)
  4481. // before after
  4482. // ab a|b a|b
  4483. // aB a|B aB|
  4484. // Ab |Ab A|b
  4485. // AB B|A B|A
  4486. // Every position after the last character on a line is considered to stick
  4487. // to the last character on the line.
  4488. function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) {
  4489. lineObj = lineObj || getLine(cm.doc, pos.line);
  4490. if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj); }
  4491. function get(ch, right) {
  4492. var m = measureCharPrepared(cm, preparedMeasure, ch, right ? "right" : "left", varHeight);
  4493. if (right) { m.left = m.right; } else { m.right = m.left; }
  4494. return intoCoordSystem(cm, lineObj, m, context)
  4495. }
  4496. var order = getOrder(lineObj, cm.doc.direction), ch = pos.ch, sticky = pos.sticky;
  4497. if (ch >= lineObj.text.length) {
  4498. ch = lineObj.text.length;
  4499. sticky = "before";
  4500. } else if (ch <= 0) {
  4501. ch = 0;
  4502. sticky = "after";
  4503. }
  4504. if (!order) { return get(sticky == "before" ? ch - 1 : ch, sticky == "before") }
  4505. function getBidi(ch, partPos, invert) {
  4506. var part = order[partPos], right = part.level == 1;
  4507. return get(invert ? ch - 1 : ch, right != invert)
  4508. }
  4509. var partPos = getBidiPartAt(order, ch, sticky);
  4510. var other = bidiOther;
  4511. var val = getBidi(ch, partPos, sticky == "before");
  4512. if (other != null) { val.other = getBidi(ch, other, sticky != "before"); }
  4513. return val
  4514. }
  4515. // Used to cheaply estimate the coordinates for a position. Used for
  4516. // intermediate scroll updates.
  4517. function estimateCoords(cm, pos) {
  4518. var left = 0;
  4519. pos = clipPos(cm.doc, pos);
  4520. if (!cm.options.lineWrapping) { left = charWidth(cm.display) * pos.ch; }
  4521. var lineObj = getLine(cm.doc, pos.line);
  4522. var top = heightAtLine(lineObj) + paddingTop(cm.display);
  4523. return {left: left, right: left, top: top, bottom: top + lineObj.height}
  4524. }
  4525. // Positions returned by coordsChar contain some extra information.
  4526. // xRel is the relative x position of the input coordinates compared
  4527. // to the found position (so xRel > 0 means the coordinates are to
  4528. // the right of the character position, for example). When outside
  4529. // is true, that means the coordinates lie outside the line's
  4530. // vertical range.
  4531. function PosWithInfo(line, ch, sticky, outside, xRel) {
  4532. var pos = Pos(line, ch, sticky);
  4533. pos.xRel = xRel;
  4534. if (outside) { pos.outside = true; }
  4535. return pos
  4536. }
  4537. // Compute the character position closest to the given coordinates.
  4538. // Input must be lineSpace-local ("div" coordinate system).
  4539. function coordsChar(cm, x, y) {
  4540. var doc = cm.doc;
  4541. y += cm.display.viewOffset;
  4542. if (y < 0) { return PosWithInfo(doc.first, 0, null, true, -1) }
  4543. var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1;
  4544. if (lineN > last)
  4545. { return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, null, true, 1) }
  4546. if (x < 0) { x = 0; }
  4547. var lineObj = getLine(doc, lineN);
  4548. for (;;) {
  4549. var found = coordsCharInner(cm, lineObj, lineN, x, y);
  4550. var merged = collapsedSpanAtEnd(lineObj);
  4551. var mergedPos = merged && merged.find(0, true);
  4552. if (merged && (found.ch > mergedPos.from.ch || found.ch == mergedPos.from.ch && found.xRel > 0))
  4553. { lineN = lineNo(lineObj = mergedPos.to.line); }
  4554. else
  4555. { return found }
  4556. }
  4557. }
  4558. function wrappedLineExtent(cm, lineObj, preparedMeasure, y) {
  4559. y -= widgetTopHeight(lineObj);
  4560. var end = lineObj.text.length;
  4561. var begin = findFirst(function (ch) { return measureCharPrepared(cm, preparedMeasure, ch - 1).bottom <= y; }, end, 0);
  4562. end = findFirst(function (ch) { return measureCharPrepared(cm, preparedMeasure, ch).top > y; }, begin, end);
  4563. return {begin: begin, end: end}
  4564. }
  4565. function wrappedLineExtentChar(cm, lineObj, preparedMeasure, target) {
  4566. if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj); }
  4567. var targetTop = intoCoordSystem(cm, lineObj, measureCharPrepared(cm, preparedMeasure, target), "line").top;
  4568. return wrappedLineExtent(cm, lineObj, preparedMeasure, targetTop)
  4569. }
  4570. // Returns true if the given side of a box is after the given
  4571. // coordinates, in top-to-bottom, left-to-right order.
  4572. function boxIsAfter(box, x, y, left) {
  4573. return box.bottom <= y ? false : box.top > y ? true : (left ? box.left : box.right) > x
  4574. }
  4575. function coordsCharInner(cm, lineObj, lineNo$$1, x, y) {
  4576. // Move y into line-local coordinate space
  4577. y -= heightAtLine(lineObj);
  4578. var preparedMeasure = prepareMeasureForLine(cm, lineObj);
  4579. // When directly calling `measureCharPrepared`, we have to adjust
  4580. // for the widgets at this line.
  4581. var widgetHeight$$1 = widgetTopHeight(lineObj);
  4582. var begin = 0, end = lineObj.text.length, ltr = true;
  4583. var order = getOrder(lineObj, cm.doc.direction);
  4584. // If the line isn't plain left-to-right text, first figure out
  4585. // which bidi section the coordinates fall into.
  4586. if (order) {
  4587. var part = (cm.options.lineWrapping ? coordsBidiPartWrapped : coordsBidiPart)
  4588. (cm, lineObj, lineNo$$1, preparedMeasure, order, x, y);
  4589. ltr = part.level != 1;
  4590. // The awkward -1 offsets are needed because findFirst (called
  4591. // on these below) will treat its first bound as inclusive,
  4592. // second as exclusive, but we want to actually address the
  4593. // characters in the part's range
  4594. begin = ltr ? part.from : part.to - 1;
  4595. end = ltr ? part.to : part.from - 1;
  4596. }
  4597. // A binary search to find the first character whose bounding box
  4598. // starts after the coordinates. If we run across any whose box wrap
  4599. // the coordinates, store that.
  4600. var chAround = null, boxAround = null;
  4601. var ch = findFirst(function (ch) {
  4602. var box = measureCharPrepared(cm, preparedMeasure, ch);
  4603. box.top += widgetHeight$$1; box.bottom += widgetHeight$$1;
  4604. if (!boxIsAfter(box, x, y, false)) { return false }
  4605. if (box.top <= y && box.left <= x) {
  4606. chAround = ch;
  4607. boxAround = box;
  4608. }
  4609. return true
  4610. }, begin, end);
  4611. var baseX, sticky, outside = false;
  4612. // If a box around the coordinates was found, use that
  4613. if (boxAround) {
  4614. // Distinguish coordinates nearer to the left or right side of the box
  4615. var atLeft = x - boxAround.left < boxAround.right - x, atStart = atLeft == ltr;
  4616. ch = chAround + (atStart ? 0 : 1);
  4617. sticky = atStart ? "after" : "before";
  4618. baseX = atLeft ? boxAround.left : boxAround.right;
  4619. } else {
  4620. // (Adjust for extended bound, if necessary.)
  4621. if (!ltr && (ch == end || ch == begin)) { ch++; }
  4622. // To determine which side to associate with, get the box to the
  4623. // left of the character and compare it's vertical position to the
  4624. // coordinates
  4625. sticky = ch == 0 ? "after" : ch == lineObj.text.length ? "before" :
  4626. (measureCharPrepared(cm, preparedMeasure, ch - (ltr ? 1 : 0)).bottom + widgetHeight$$1 <= y) == ltr ?
  4627. "after" : "before";
  4628. // Now get accurate coordinates for this place, in order to get a
  4629. // base X position
  4630. var coords = cursorCoords(cm, Pos(lineNo$$1, ch, sticky), "line", lineObj, preparedMeasure);
  4631. baseX = coords.left;
  4632. outside = y < coords.top || y >= coords.bottom;
  4633. }
  4634. ch = skipExtendingChars(lineObj.text, ch, 1);
  4635. return PosWithInfo(lineNo$$1, ch, sticky, outside, x - baseX)
  4636. }
  4637. function coordsBidiPart(cm, lineObj, lineNo$$1, preparedMeasure, order, x, y) {
  4638. // Bidi parts are sorted left-to-right, and in a non-line-wrapping
  4639. // situation, we can take this ordering to correspond to the visual
  4640. // ordering. This finds the first part whose end is after the given
  4641. // coordinates.
  4642. var index = findFirst(function (i) {
  4643. var part = order[i], ltr = part.level != 1;
  4644. return boxIsAfter(cursorCoords(cm, Pos(lineNo$$1, ltr ? part.to : part.from, ltr ? "before" : "after"),
  4645. "line", lineObj, preparedMeasure), x, y, true)
  4646. }, 0, order.length - 1);
  4647. var part = order[index];
  4648. // If this isn't the first part, the part's start is also after
  4649. // the coordinates, and the coordinates aren't on the same line as
  4650. // that start, move one part back.
  4651. if (index > 0) {
  4652. var ltr = part.level != 1;
  4653. var start = cursorCoords(cm, Pos(lineNo$$1, ltr ? part.from : part.to, ltr ? "after" : "before"),
  4654. "line", lineObj, preparedMeasure);
  4655. if (boxIsAfter(start, x, y, true) && start.top > y)
  4656. { part = order[index - 1]; }
  4657. }
  4658. return part
  4659. }
  4660. function coordsBidiPartWrapped(cm, lineObj, _lineNo, preparedMeasure, order, x, y) {
  4661. // In a wrapped line, rtl text on wrapping boundaries can do things
  4662. // that don't correspond to the ordering in our `order` array at
  4663. // all, so a binary search doesn't work, and we want to return a
  4664. // part that only spans one line so that the binary search in
  4665. // coordsCharInner is safe. As such, we first find the extent of the
  4666. // wrapped line, and then do a flat search in which we discard any
  4667. // spans that aren't on the line.
  4668. var ref = wrappedLineExtent(cm, lineObj, preparedMeasure, y);
  4669. var begin = ref.begin;
  4670. var end = ref.end;
  4671. if (/\s/.test(lineObj.text.charAt(end - 1))) { end--; }
  4672. var part = null, closestDist = null;
  4673. for (var i = 0; i < order.length; i++) {
  4674. var p = order[i];
  4675. if (p.from >= end || p.to <= begin) { continue }
  4676. var ltr = p.level != 1;
  4677. var endX = measureCharPrepared(cm, preparedMeasure, ltr ? Math.min(end, p.to) - 1 : Math.max(begin, p.from)).right;
  4678. // Weigh against spans ending before this, so that they are only
  4679. // picked if nothing ends after
  4680. var dist = endX < x ? x - endX + 1e9 : endX - x;
  4681. if (!part || closestDist > dist) {
  4682. part = p;
  4683. closestDist = dist;
  4684. }
  4685. }
  4686. if (!part) { part = order[order.length - 1]; }
  4687. // Clip the part to the wrapped line.
  4688. if (part.from < begin) { part = {from: begin, to: part.to, level: part.level}; }
  4689. if (part.to > end) { part = {from: part.from, to: end, level: part.level}; }
  4690. return part
  4691. }
  4692. var measureText;
  4693. // Compute the default text height.
  4694. function textHeight(display) {
  4695. if (display.cachedTextHeight != null) { return display.cachedTextHeight }
  4696. if (measureText == null) {
  4697. measureText = elt("pre");
  4698. // Measure a bunch of lines, for browsers that compute
  4699. // fractional heights.
  4700. for (var i = 0; i < 49; ++i) {
  4701. measureText.appendChild(document.createTextNode("x"));
  4702. measureText.appendChild(elt("br"));
  4703. }
  4704. measureText.appendChild(document.createTextNode("x"));
  4705. }
  4706. removeChildrenAndAdd(display.measure, measureText);
  4707. var height = measureText.offsetHeight / 50;
  4708. if (height > 3) { display.cachedTextHeight = height; }
  4709. removeChildren(display.measure);
  4710. return height || 1
  4711. }
  4712. // Compute the default character width.
  4713. function charWidth(display) {
  4714. if (display.cachedCharWidth != null) { return display.cachedCharWidth }
  4715. var anchor = elt("span", "xxxxxxxxxx");
  4716. var pre = elt("pre", [anchor]);
  4717. removeChildrenAndAdd(display.measure, pre);
  4718. var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10;
  4719. if (width > 2) { display.cachedCharWidth = width; }
  4720. return width || 10
  4721. }
  4722. // Do a bulk-read of the DOM positions and sizes needed to draw the
  4723. // view, so that we don't interleave reading and writing to the DOM.
  4724. function getDimensions(cm) {
  4725. var d = cm.display, left = {}, width = {};
  4726. var gutterLeft = d.gutters.clientLeft;
  4727. for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) {
  4728. left[cm.options.gutters[i]] = n.offsetLeft + n.clientLeft + gutterLeft;
  4729. width[cm.options.gutters[i]] = n.clientWidth;
  4730. }
  4731. return {fixedPos: compensateForHScroll(d),
  4732. gutterTotalWidth: d.gutters.offsetWidth,
  4733. gutterLeft: left,
  4734. gutterWidth: width,
  4735. wrapperWidth: d.wrapper.clientWidth}
  4736. }
  4737. // Computes display.scroller.scrollLeft + display.gutters.offsetWidth,
  4738. // but using getBoundingClientRect to get a sub-pixel-accurate
  4739. // result.
  4740. function compensateForHScroll(display) {
  4741. return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left
  4742. }
  4743. // Returns a function that estimates the height of a line, to use as
  4744. // first approximation until the line becomes visible (and is thus
  4745. // properly measurable).
  4746. function estimateHeight(cm) {
  4747. var th = textHeight(cm.display), wrapping = cm.options.lineWrapping;
  4748. var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3);
  4749. return function (line) {
  4750. if (lineIsHidden(cm.doc, line)) { return 0 }
  4751. var widgetsHeight = 0;
  4752. if (line.widgets) { for (var i = 0; i < line.widgets.length; i++) {
  4753. if (line.widgets[i].height) { widgetsHeight += line.widgets[i].height; }
  4754. } }
  4755. if (wrapping)
  4756. { return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th }
  4757. else
  4758. { return widgetsHeight + th }
  4759. }
  4760. }
  4761. function estimateLineHeights(cm) {
  4762. var doc = cm.doc, est = estimateHeight(cm);
  4763. doc.iter(function (line) {
  4764. var estHeight = est(line);
  4765. if (estHeight != line.height) { updateLineHeight(line, estHeight); }
  4766. });
  4767. }
  4768. // Given a mouse event, find the corresponding position. If liberal
  4769. // is false, it checks whether a gutter or scrollbar was clicked,
  4770. // and returns null if it was. forRect is used by rectangular
  4771. // selections, and tries to estimate a character position even for
  4772. // coordinates beyond the right of the text.
  4773. function posFromMouse(cm, e, liberal, forRect) {
  4774. var display = cm.display;
  4775. if (!liberal && e_target(e).getAttribute("cm-not-content") == "true") { return null }
  4776. var x, y, space = display.lineSpace.getBoundingClientRect();
  4777. // Fails unpredictably on IE[67] when mouse is dragged around quickly.
  4778. try { x = e.clientX - space.left; y = e.clientY - space.top; }
  4779. catch (e) { return null }
  4780. var coords = coordsChar(cm, x, y), line;
  4781. if (forRect && coords.xRel == 1 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) {
  4782. var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length;
  4783. coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff));
  4784. }
  4785. return coords
  4786. }
  4787. // Find the view element corresponding to a given line. Return null
  4788. // when the line isn't visible.
  4789. function findViewIndex(cm, n) {
  4790. if (n >= cm.display.viewTo) { return null }
  4791. n -= cm.display.viewFrom;
  4792. if (n < 0) { return null }
  4793. var view = cm.display.view;
  4794. for (var i = 0; i < view.length; i++) {
  4795. n -= view[i].size;
  4796. if (n < 0) { return i }
  4797. }
  4798. }
  4799. function updateSelection(cm) {
  4800. cm.display.input.showSelection(cm.display.input.prepareSelection());
  4801. }
  4802. function prepareSelection(cm, primary) {
  4803. if ( primary === void 0 ) primary = true;
  4804. var doc = cm.doc, result = {};
  4805. var curFragment = result.cursors = document.createDocumentFragment();
  4806. var selFragment = result.selection = document.createDocumentFragment();
  4807. for (var i = 0; i < doc.sel.ranges.length; i++) {
  4808. if (!primary && i == doc.sel.primIndex) { continue }
  4809. var range$$1 = doc.sel.ranges[i];
  4810. if (range$$1.from().line >= cm.display.viewTo || range$$1.to().line < cm.display.viewFrom) { continue }
  4811. var collapsed = range$$1.empty();
  4812. if (collapsed || cm.options.showCursorWhenSelecting)
  4813. { drawSelectionCursor(cm, range$$1.head, curFragment); }
  4814. if (!collapsed)
  4815. { drawSelectionRange(cm, range$$1, selFragment); }
  4816. }
  4817. return result
  4818. }
  4819. // Draws a cursor for the given range
  4820. function drawSelectionCursor(cm, head, output) {
  4821. var pos = cursorCoords(cm, head, "div", null, null, !cm.options.singleCursorHeightPerLine);
  4822. var cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor"));
  4823. cursor.style.left = pos.left + "px";
  4824. cursor.style.top = pos.top + "px";
  4825. cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px";
  4826. if (pos.other) {
  4827. // Secondary cursor, shown when on a 'jump' in bi-directional text
  4828. var otherCursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor"));
  4829. otherCursor.style.display = "";
  4830. otherCursor.style.left = pos.other.left + "px";
  4831. otherCursor.style.top = pos.other.top + "px";
  4832. otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px";
  4833. }
  4834. }
  4835. function cmpCoords(a, b) { return a.top - b.top || a.left - b.left }
  4836. // Draws the given range as a highlighted selection
  4837. function drawSelectionRange(cm, range$$1, output) {
  4838. var display = cm.display, doc = cm.doc;
  4839. var fragment = document.createDocumentFragment();
  4840. var padding = paddingH(cm.display), leftSide = padding.left;
  4841. var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right;
  4842. var docLTR = doc.direction == "ltr";
  4843. function add(left, top, width, bottom) {
  4844. if (top < 0) { top = 0; }
  4845. top = Math.round(top);
  4846. bottom = Math.round(bottom);
  4847. 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")));
  4848. }
  4849. function drawForLine(line, fromArg, toArg) {
  4850. var lineObj = getLine(doc, line);
  4851. var lineLen = lineObj.text.length;
  4852. var start, end;
  4853. function coords(ch, bias) {
  4854. return charCoords(cm, Pos(line, ch), "div", lineObj, bias)
  4855. }
  4856. function wrapX(pos, dir, side) {
  4857. var extent = wrappedLineExtentChar(cm, lineObj, null, pos);
  4858. var prop = (dir == "ltr") == (side == "after") ? "left" : "right";
  4859. var ch = side == "after" ? extent.begin : extent.end - (/\s/.test(lineObj.text.charAt(extent.end - 1)) ? 2 : 1);
  4860. return coords(ch, prop)[prop]
  4861. }
  4862. var order = getOrder(lineObj, doc.direction);
  4863. iterateBidiSections(order, fromArg || 0, toArg == null ? lineLen : toArg, function (from, to, dir, i) {
  4864. var ltr = dir == "ltr";
  4865. var fromPos = coords(from, ltr ? "left" : "right");
  4866. var toPos = coords(to - 1, ltr ? "right" : "left");
  4867. var openStart = fromArg == null && from == 0, openEnd = toArg == null && to == lineLen;
  4868. var first = i == 0, last = !order || i == order.length - 1;
  4869. if (toPos.top - fromPos.top <= 3) { // Single line
  4870. var openLeft = (docLTR ? openStart : openEnd) && first;
  4871. var openRight = (docLTR ? openEnd : openStart) && last;
  4872. var left = openLeft ? leftSide : (ltr ? fromPos : toPos).left;
  4873. var right = openRight ? rightSide : (ltr ? toPos : fromPos).right;
  4874. add(left, fromPos.top, right - left, fromPos.bottom);
  4875. } else { // Multiple lines
  4876. var topLeft, topRight, botLeft, botRight;
  4877. if (ltr) {
  4878. topLeft = docLTR && openStart && first ? leftSide : fromPos.left;
  4879. topRight = docLTR ? rightSide : wrapX(from, dir, "before");
  4880. botLeft = docLTR ? leftSide : wrapX(to, dir, "after");
  4881. botRight = docLTR && openEnd && last ? rightSide : toPos.right;
  4882. } else {
  4883. topLeft = !docLTR ? leftSide : wrapX(from, dir, "before");
  4884. topRight = !docLTR && openStart && first ? rightSide : fromPos.right;
  4885. botLeft = !docLTR && openEnd && last ? leftSide : toPos.left;
  4886. botRight = !docLTR ? rightSide : wrapX(to, dir, "after");
  4887. }
  4888. add(topLeft, fromPos.top, topRight - topLeft, fromPos.bottom);
  4889. if (fromPos.bottom < toPos.top) { add(leftSide, fromPos.bottom, null, toPos.top); }
  4890. add(botLeft, toPos.top, botRight - botLeft, toPos.bottom);
  4891. }
  4892. if (!start || cmpCoords(fromPos, start) < 0) { start = fromPos; }
  4893. if (cmpCoords(toPos, start) < 0) { start = toPos; }
  4894. if (!end || cmpCoords(fromPos, end) < 0) { end = fromPos; }
  4895. if (cmpCoords(toPos, end) < 0) { end = toPos; }
  4896. });
  4897. return {start: start, end: end}
  4898. }
  4899. var sFrom = range$$1.from(), sTo = range$$1.to();
  4900. if (sFrom.line == sTo.line) {
  4901. drawForLine(sFrom.line, sFrom.ch, sTo.ch);
  4902. } else {
  4903. var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line);
  4904. var singleVLine = visualLine(fromLine) == visualLine(toLine);
  4905. var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end;
  4906. var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start;
  4907. if (singleVLine) {
  4908. if (leftEnd.top < rightStart.top - 2) {
  4909. add(leftEnd.right, leftEnd.top, null, leftEnd.bottom);
  4910. add(leftSide, rightStart.top, rightStart.left, rightStart.bottom);
  4911. } else {
  4912. add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom);
  4913. }
  4914. }
  4915. if (leftEnd.bottom < rightStart.top)
  4916. { add(leftSide, leftEnd.bottom, null, rightStart.top); }
  4917. }
  4918. output.appendChild(fragment);
  4919. }
  4920. // Cursor-blinking
  4921. function restartBlink(cm) {
  4922. if (!cm.state.focused) { return }
  4923. var display = cm.display;
  4924. clearInterval(display.blinker);
  4925. var on = true;
  4926. display.cursorDiv.style.visibility = "";
  4927. if (cm.options.cursorBlinkRate > 0)
  4928. { display.blinker = setInterval(function () { return display.cursorDiv.style.visibility = (on = !on) ? "" : "hidden"; },
  4929. cm.options.cursorBlinkRate); }
  4930. else if (cm.options.cursorBlinkRate < 0)
  4931. { display.cursorDiv.style.visibility = "hidden"; }
  4932. }
  4933. function ensureFocus(cm) {
  4934. if (!cm.state.focused) { cm.display.input.focus(); onFocus(cm); }
  4935. }
  4936. function delayBlurEvent(cm) {
  4937. cm.state.delayingBlurEvent = true;
  4938. setTimeout(function () { if (cm.state.delayingBlurEvent) {
  4939. cm.state.delayingBlurEvent = false;
  4940. onBlur(cm);
  4941. } }, 100);
  4942. }
  4943. function onFocus(cm, e) {
  4944. if (cm.state.delayingBlurEvent) { cm.state.delayingBlurEvent = false; }
  4945. if (cm.options.readOnly == "nocursor") { return }
  4946. if (!cm.state.focused) {
  4947. signal(cm, "focus", cm, e);
  4948. cm.state.focused = true;
  4949. addClass(cm.display.wrapper, "CodeMirror-focused");
  4950. // This test prevents this from firing when a context
  4951. // menu is closed (since the input reset would kill the
  4952. // select-all detection hack)
  4953. if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) {
  4954. cm.display.input.reset();
  4955. if (webkit) { setTimeout(function () { return cm.display.input.reset(true); }, 20); } // Issue #1730
  4956. }
  4957. cm.display.input.receivedFocus();
  4958. }
  4959. restartBlink(cm);
  4960. }
  4961. function onBlur(cm, e) {
  4962. if (cm.state.delayingBlurEvent) { return }
  4963. if (cm.state.focused) {
  4964. signal(cm, "blur", cm, e);
  4965. cm.state.focused = false;
  4966. rmClass(cm.display.wrapper, "CodeMirror-focused");
  4967. }
  4968. clearInterval(cm.display.blinker);
  4969. setTimeout(function () { if (!cm.state.focused) { cm.display.shift = false; } }, 150);
  4970. }
  4971. // Read the actual heights of the rendered lines, and update their
  4972. // stored heights to match.
  4973. function updateHeightsInViewport(cm) {
  4974. var display = cm.display;
  4975. var prevBottom = display.lineDiv.offsetTop;
  4976. for (var i = 0; i < display.view.length; i++) {
  4977. var cur = display.view[i], height = (void 0);
  4978. if (cur.hidden) { continue }
  4979. if (ie && ie_version < 8) {
  4980. var bot = cur.node.offsetTop + cur.node.offsetHeight;
  4981. height = bot - prevBottom;
  4982. prevBottom = bot;
  4983. } else {
  4984. var box = cur.node.getBoundingClientRect();
  4985. height = box.bottom - box.top;
  4986. }
  4987. var diff = cur.line.height - height;
  4988. if (height < 2) { height = textHeight(display); }
  4989. if (diff > .005 || diff < -.005) {
  4990. updateLineHeight(cur.line, height);
  4991. updateWidgetHeight(cur.line);
  4992. if (cur.rest) { for (var j = 0; j < cur.rest.length; j++)
  4993. { updateWidgetHeight(cur.rest[j]); } }
  4994. }
  4995. }
  4996. }
  4997. // Read and store the height of line widgets associated with the
  4998. // given line.
  4999. function updateWidgetHeight(line) {
  5000. if (line.widgets) { for (var i = 0; i < line.widgets.length; ++i) {
  5001. var w = line.widgets[i], parent = w.node.parentNode;
  5002. if (parent) { w.height = parent.offsetHeight; }
  5003. } }
  5004. }
  5005. // Compute the lines that are visible in a given viewport (defaults
  5006. // the the current scroll position). viewport may contain top,
  5007. // height, and ensure (see op.scrollToPos) properties.
  5008. function visibleLines(display, doc, viewport) {
  5009. var top = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop;
  5010. top = Math.floor(top - paddingTop(display));
  5011. var bottom = viewport && viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight;
  5012. var from = lineAtHeight(doc, top), to = lineAtHeight(doc, bottom);
  5013. // Ensure is a {from: {line, ch}, to: {line, ch}} object, and
  5014. // forces those lines into the viewport (if possible).
  5015. if (viewport && viewport.ensure) {
  5016. var ensureFrom = viewport.ensure.from.line, ensureTo = viewport.ensure.to.line;
  5017. if (ensureFrom < from) {
  5018. from = ensureFrom;
  5019. to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight);
  5020. } else if (Math.min(ensureTo, doc.lastLine()) >= to) {
  5021. from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight);
  5022. to = ensureTo;
  5023. }
  5024. }
  5025. return {from: from, to: Math.max(to, from + 1)}
  5026. }
  5027. // Re-align line numbers and gutter marks to compensate for
  5028. // horizontal scrolling.
  5029. function alignHorizontally(cm) {
  5030. var display = cm.display, view = display.view;
  5031. if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) { return }
  5032. var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft;
  5033. var gutterW = display.gutters.offsetWidth, left = comp + "px";
  5034. for (var i = 0; i < view.length; i++) { if (!view[i].hidden) {
  5035. if (cm.options.fixedGutter) {
  5036. if (view[i].gutter)
  5037. { view[i].gutter.style.left = left; }
  5038. if (view[i].gutterBackground)
  5039. { view[i].gutterBackground.style.left = left; }
  5040. }
  5041. var align = view[i].alignable;
  5042. if (align) { for (var j = 0; j < align.length; j++)
  5043. { align[j].style.left = left; } }
  5044. } }
  5045. if (cm.options.fixedGutter)
  5046. { display.gutters.style.left = (comp + gutterW) + "px"; }
  5047. }
  5048. // Used to ensure that the line number gutter is still the right
  5049. // size for the current document size. Returns true when an update
  5050. // is needed.
  5051. function maybeUpdateLineNumberWidth(cm) {
  5052. if (!cm.options.lineNumbers) { return false }
  5053. var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display;
  5054. if (last.length != display.lineNumChars) {
  5055. var test = display.measure.appendChild(elt("div", [elt("div", last)],
  5056. "CodeMirror-linenumber CodeMirror-gutter-elt"));
  5057. var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW;
  5058. display.lineGutter.style.width = "";
  5059. display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding) + 1;
  5060. display.lineNumWidth = display.lineNumInnerWidth + padding;
  5061. display.lineNumChars = display.lineNumInnerWidth ? last.length : -1;
  5062. display.lineGutter.style.width = display.lineNumWidth + "px";
  5063. updateGutterSpace(cm);
  5064. return true
  5065. }
  5066. return false
  5067. }
  5068. // SCROLLING THINGS INTO VIEW
  5069. // If an editor sits on the top or bottom of the window, partially
  5070. // scrolled out of view, this ensures that the cursor is visible.
  5071. function maybeScrollWindow(cm, rect) {
  5072. if (signalDOMEvent(cm, "scrollCursorIntoView")) { return }
  5073. var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null;
  5074. if (rect.top + box.top < 0) { doScroll = true; }
  5075. else if (rect.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) { doScroll = false; }
  5076. if (doScroll != null && !phantom) {
  5077. 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;"));
  5078. cm.display.lineSpace.appendChild(scrollNode);
  5079. scrollNode.scrollIntoView(doScroll);
  5080. cm.display.lineSpace.removeChild(scrollNode);
  5081. }
  5082. }
  5083. // Scroll a given position into view (immediately), verifying that
  5084. // it actually became visible (as line heights are accurately
  5085. // measured, the position of something may 'drift' during drawing).
  5086. function scrollPosIntoView(cm, pos, end, margin) {
  5087. if (margin == null) { margin = 0; }
  5088. var rect;
  5089. if (!cm.options.lineWrapping && pos == end) {
  5090. // Set pos and end to the cursor positions around the character pos sticks to
  5091. // If pos.sticky == "before", that is around pos.ch - 1, otherwise around pos.ch
  5092. // If pos == Pos(_, 0, "before"), pos and end are unchanged
  5093. pos = pos.ch ? Pos(pos.line, pos.sticky == "before" ? pos.ch - 1 : pos.ch, "after") : pos;
  5094. end = pos.sticky == "before" ? Pos(pos.line, pos.ch + 1, "before") : pos;
  5095. }
  5096. for (var limit = 0; limit < 5; limit++) {
  5097. var changed = false;
  5098. var coords = cursorCoords(cm, pos);
  5099. var endCoords = !end || end == pos ? coords : cursorCoords(cm, end);
  5100. rect = {left: Math.min(coords.left, endCoords.left),
  5101. top: Math.min(coords.top, endCoords.top) - margin,
  5102. right: Math.max(coords.left, endCoords.left),
  5103. bottom: Math.max(coords.bottom, endCoords.bottom) + margin};
  5104. var scrollPos = calculateScrollPos(cm, rect);
  5105. var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft;
  5106. if (scrollPos.scrollTop != null) {
  5107. updateScrollTop(cm, scrollPos.scrollTop);
  5108. if (Math.abs(cm.doc.scrollTop - startTop) > 1) { changed = true; }
  5109. }
  5110. if (scrollPos.scrollLeft != null) {
  5111. setScrollLeft(cm, scrollPos.scrollLeft);
  5112. if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) { changed = true; }
  5113. }
  5114. if (!changed) { break }
  5115. }
  5116. return rect
  5117. }
  5118. // Scroll a given set of coordinates into view (immediately).
  5119. function scrollIntoView(cm, rect) {
  5120. var scrollPos = calculateScrollPos(cm, rect);
  5121. if (scrollPos.scrollTop != null) { updateScrollTop(cm, scrollPos.scrollTop); }
  5122. if (scrollPos.scrollLeft != null) { setScrollLeft(cm, scrollPos.scrollLeft); }
  5123. }
  5124. // Calculate a new scroll position needed to scroll the given
  5125. // rectangle into view. Returns an object with scrollTop and
  5126. // scrollLeft properties. When these are undefined, the
  5127. // vertical/horizontal position does not need to be adjusted.
  5128. function calculateScrollPos(cm, rect) {
  5129. var display = cm.display, snapMargin = textHeight(cm.display);
  5130. if (rect.top < 0) { rect.top = 0; }
  5131. var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop;
  5132. var screen = displayHeight(cm), result = {};
  5133. if (rect.bottom - rect.top > screen) { rect.bottom = rect.top + screen; }
  5134. var docBottom = cm.doc.height + paddingVert(display);
  5135. var atTop = rect.top < snapMargin, atBottom = rect.bottom > docBottom - snapMargin;
  5136. if (rect.top < screentop) {
  5137. result.scrollTop = atTop ? 0 : rect.top;
  5138. } else if (rect.bottom > screentop + screen) {
  5139. var newTop = Math.min(rect.top, (atBottom ? docBottom : rect.bottom) - screen);
  5140. if (newTop != screentop) { result.scrollTop = newTop; }
  5141. }
  5142. var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft;
  5143. var screenw = displayWidth(cm) - (cm.options.fixedGutter ? display.gutters.offsetWidth : 0);
  5144. var tooWide = rect.right - rect.left > screenw;
  5145. if (tooWide) { rect.right = rect.left + screenw; }
  5146. if (rect.left < 10)
  5147. { result.scrollLeft = 0; }
  5148. else if (rect.left < screenleft)
  5149. { result.scrollLeft = Math.max(0, rect.left - (tooWide ? 0 : 10)); }
  5150. else if (rect.right > screenw + screenleft - 3)
  5151. { result.scrollLeft = rect.right + (tooWide ? 0 : 10) - screenw; }
  5152. return result
  5153. }
  5154. // Store a relative adjustment to the scroll position in the current
  5155. // operation (to be applied when the operation finishes).
  5156. function addToScrollTop(cm, top) {
  5157. if (top == null) { return }
  5158. resolveScrollToPos(cm);
  5159. cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top;
  5160. }
  5161. // Make sure that at the end of the operation the current cursor is
  5162. // shown.
  5163. function ensureCursorVisible(cm) {
  5164. resolveScrollToPos(cm);
  5165. var cur = cm.getCursor();
  5166. cm.curOp.scrollToPos = {from: cur, to: cur, margin: cm.options.cursorScrollMargin};
  5167. }
  5168. function scrollToCoords(cm, x, y) {
  5169. if (x != null || y != null) { resolveScrollToPos(cm); }
  5170. if (x != null) { cm.curOp.scrollLeft = x; }
  5171. if (y != null) { cm.curOp.scrollTop = y; }
  5172. }
  5173. function scrollToRange(cm, range$$1) {
  5174. resolveScrollToPos(cm);
  5175. cm.curOp.scrollToPos = range$$1;
  5176. }
  5177. // When an operation has its scrollToPos property set, and another
  5178. // scroll action is applied before the end of the operation, this
  5179. // 'simulates' scrolling that position into view in a cheap way, so
  5180. // that the effect of intermediate scroll commands is not ignored.
  5181. function resolveScrollToPos(cm) {
  5182. var range$$1 = cm.curOp.scrollToPos;
  5183. if (range$$1) {
  5184. cm.curOp.scrollToPos = null;
  5185. var from = estimateCoords(cm, range$$1.from), to = estimateCoords(cm, range$$1.to);
  5186. scrollToCoordsRange(cm, from, to, range$$1.margin);
  5187. }
  5188. }
  5189. function scrollToCoordsRange(cm, from, to, margin) {
  5190. var sPos = calculateScrollPos(cm, {
  5191. left: Math.min(from.left, to.left),
  5192. top: Math.min(from.top, to.top) - margin,
  5193. right: Math.max(from.right, to.right),
  5194. bottom: Math.max(from.bottom, to.bottom) + margin
  5195. });
  5196. scrollToCoords(cm, sPos.scrollLeft, sPos.scrollTop);
  5197. }
  5198. // Sync the scrollable area and scrollbars, ensure the viewport
  5199. // covers the visible area.
  5200. function updateScrollTop(cm, val) {
  5201. if (Math.abs(cm.doc.scrollTop - val) < 2) { return }
  5202. if (!gecko) { updateDisplaySimple(cm, {top: val}); }
  5203. setScrollTop(cm, val, true);
  5204. if (gecko) { updateDisplaySimple(cm); }
  5205. startWorker(cm, 100);
  5206. }
  5207. function setScrollTop(cm, val, forceScroll) {
  5208. val = Math.min(cm.display.scroller.scrollHeight - cm.display.scroller.clientHeight, val);
  5209. if (cm.display.scroller.scrollTop == val && !forceScroll) { return }
  5210. cm.doc.scrollTop = val;
  5211. cm.display.scrollbars.setScrollTop(val);
  5212. if (cm.display.scroller.scrollTop != val) { cm.display.scroller.scrollTop = val; }
  5213. }
  5214. // Sync scroller and scrollbar, ensure the gutter elements are
  5215. // aligned.
  5216. function setScrollLeft(cm, val, isScroller, forceScroll) {
  5217. val = Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth);
  5218. if ((isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) && !forceScroll) { return }
  5219. cm.doc.scrollLeft = val;
  5220. alignHorizontally(cm);
  5221. if (cm.display.scroller.scrollLeft != val) { cm.display.scroller.scrollLeft = val; }
  5222. cm.display.scrollbars.setScrollLeft(val);
  5223. }
  5224. // SCROLLBARS
  5225. // Prepare DOM reads needed to update the scrollbars. Done in one
  5226. // shot to minimize update/measure roundtrips.
  5227. function measureForScrollbars(cm) {
  5228. var d = cm.display, gutterW = d.gutters.offsetWidth;
  5229. var docH = Math.round(cm.doc.height + paddingVert(cm.display));
  5230. return {
  5231. clientHeight: d.scroller.clientHeight,
  5232. viewHeight: d.wrapper.clientHeight,
  5233. scrollWidth: d.scroller.scrollWidth, clientWidth: d.scroller.clientWidth,
  5234. viewWidth: d.wrapper.clientWidth,
  5235. barLeft: cm.options.fixedGutter ? gutterW : 0,
  5236. docHeight: docH,
  5237. scrollHeight: docH + scrollGap(cm) + d.barHeight,
  5238. nativeBarWidth: d.nativeBarWidth,
  5239. gutterWidth: gutterW
  5240. }
  5241. }
  5242. var NativeScrollbars = function(place, scroll, cm) {
  5243. this.cm = cm;
  5244. var vert = this.vert = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar");
  5245. var horiz = this.horiz = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar");
  5246. place(vert); place(horiz);
  5247. on(vert, "scroll", function () {
  5248. if (vert.clientHeight) { scroll(vert.scrollTop, "vertical"); }
  5249. });
  5250. on(horiz, "scroll", function () {
  5251. if (horiz.clientWidth) { scroll(horiz.scrollLeft, "horizontal"); }
  5252. });
  5253. this.checkedZeroWidth = false;
  5254. // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8).
  5255. if (ie && ie_version < 8) { this.horiz.style.minHeight = this.vert.style.minWidth = "18px"; }
  5256. };
  5257. NativeScrollbars.prototype.update = function (measure) {
  5258. var needsH = measure.scrollWidth > measure.clientWidth + 1;
  5259. var needsV = measure.scrollHeight > measure.clientHeight + 1;
  5260. var sWidth = measure.nativeBarWidth;
  5261. if (needsV) {
  5262. this.vert.style.display = "block";
  5263. this.vert.style.bottom = needsH ? sWidth + "px" : "0";
  5264. var totalHeight = measure.viewHeight - (needsH ? sWidth : 0);
  5265. // A bug in IE8 can cause this value to be negative, so guard it.
  5266. this.vert.firstChild.style.height =
  5267. Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + "px";
  5268. } else {
  5269. this.vert.style.display = "";
  5270. this.vert.firstChild.style.height = "0";
  5271. }
  5272. if (needsH) {
  5273. this.horiz.style.display = "block";
  5274. this.horiz.style.right = needsV ? sWidth + "px" : "0";
  5275. this.horiz.style.left = measure.barLeft + "px";
  5276. var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0);
  5277. this.horiz.firstChild.style.width =
  5278. Math.max(0, measure.scrollWidth - measure.clientWidth + totalWidth) + "px";
  5279. } else {
  5280. this.horiz.style.display = "";
  5281. this.horiz.firstChild.style.width = "0";
  5282. }
  5283. if (!this.checkedZeroWidth && measure.clientHeight > 0) {
  5284. if (sWidth == 0) { this.zeroWidthHack(); }
  5285. this.checkedZeroWidth = true;
  5286. }
  5287. return {right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0}
  5288. };
  5289. NativeScrollbars.prototype.setScrollLeft = function (pos) {
  5290. if (this.horiz.scrollLeft != pos) { this.horiz.scrollLeft = pos; }
  5291. if (this.disableHoriz) { this.enableZeroWidthBar(this.horiz, this.disableHoriz, "horiz"); }
  5292. };
  5293. NativeScrollbars.prototype.setScrollTop = function (pos) {
  5294. if (this.vert.scrollTop != pos) { this.vert.scrollTop = pos; }
  5295. if (this.disableVert) { this.enableZeroWidthBar(this.vert, this.disableVert, "vert"); }
  5296. };
  5297. NativeScrollbars.prototype.zeroWidthHack = function () {
  5298. var w = mac && !mac_geMountainLion ? "12px" : "18px";
  5299. this.horiz.style.height = this.vert.style.width = w;
  5300. this.horiz.style.pointerEvents = this.vert.style.pointerEvents = "none";
  5301. this.disableHoriz = new Delayed;
  5302. this.disableVert = new Delayed;
  5303. };
  5304. NativeScrollbars.prototype.enableZeroWidthBar = function (bar, delay, type) {
  5305. bar.style.pointerEvents = "auto";
  5306. function maybeDisable() {
  5307. // To find out whether the scrollbar is still visible, we
  5308. // check whether the element under the pixel in the bottom
  5309. // right corner of the scrollbar box is the scrollbar box
  5310. // itself (when the bar is still visible) or its filler child
  5311. // (when the bar is hidden). If it is still visible, we keep
  5312. // it enabled, if it's hidden, we disable pointer events.
  5313. var box = bar.getBoundingClientRect();
  5314. var elt$$1 = type == "vert" ? document.elementFromPoint(box.right - 1, (box.top + box.bottom) / 2)
  5315. : document.elementFromPoint((box.right + box.left) / 2, box.bottom - 1);
  5316. if (elt$$1 != bar) { bar.style.pointerEvents = "none"; }
  5317. else { delay.set(1000, maybeDisable); }
  5318. }
  5319. delay.set(1000, maybeDisable);
  5320. };
  5321. NativeScrollbars.prototype.clear = function () {
  5322. var parent = this.horiz.parentNode;
  5323. parent.removeChild(this.horiz);
  5324. parent.removeChild(this.vert);
  5325. };
  5326. var NullScrollbars = function () {};
  5327. NullScrollbars.prototype.update = function () { return {bottom: 0, right: 0} };
  5328. NullScrollbars.prototype.setScrollLeft = function () {};
  5329. NullScrollbars.prototype.setScrollTop = function () {};
  5330. NullScrollbars.prototype.clear = function () {};
  5331. function updateScrollbars(cm, measure) {
  5332. if (!measure) { measure = measureForScrollbars(cm); }
  5333. var startWidth = cm.display.barWidth, startHeight = cm.display.barHeight;
  5334. updateScrollbarsInner(cm, measure);
  5335. for (var i = 0; i < 4 && startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i++) {
  5336. if (startWidth != cm.display.barWidth && cm.options.lineWrapping)
  5337. { updateHeightsInViewport(cm); }
  5338. updateScrollbarsInner(cm, measureForScrollbars(cm));
  5339. startWidth = cm.display.barWidth; startHeight = cm.display.barHeight;
  5340. }
  5341. }
  5342. // Re-synchronize the fake scrollbars with the actual size of the
  5343. // content.
  5344. function updateScrollbarsInner(cm, measure) {
  5345. var d = cm.display;
  5346. var sizes = d.scrollbars.update(measure);
  5347. d.sizer.style.paddingRight = (d.barWidth = sizes.right) + "px";
  5348. d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + "px";
  5349. d.heightForcer.style.borderBottom = sizes.bottom + "px solid transparent";
  5350. if (sizes.right && sizes.bottom) {
  5351. d.scrollbarFiller.style.display = "block";
  5352. d.scrollbarFiller.style.height = sizes.bottom + "px";
  5353. d.scrollbarFiller.style.width = sizes.right + "px";
  5354. } else { d.scrollbarFiller.style.display = ""; }
  5355. if (sizes.bottom && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) {
  5356. d.gutterFiller.style.display = "block";
  5357. d.gutterFiller.style.height = sizes.bottom + "px";
  5358. d.gutterFiller.style.width = measure.gutterWidth + "px";
  5359. } else { d.gutterFiller.style.display = ""; }
  5360. }
  5361. var scrollbarModel = {"native": NativeScrollbars, "null": NullScrollbars};
  5362. function initScrollbars(cm) {
  5363. if (cm.display.scrollbars) {
  5364. cm.display.scrollbars.clear();
  5365. if (cm.display.scrollbars.addClass)
  5366. { rmClass(cm.display.wrapper, cm.display.scrollbars.addClass); }
  5367. }
  5368. cm.display.scrollbars = new scrollbarModel[cm.options.scrollbarStyle](function (node) {
  5369. cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller);
  5370. // Prevent clicks in the scrollbars from killing focus
  5371. on(node, "mousedown", function () {
  5372. if (cm.state.focused) { setTimeout(function () { return cm.display.input.focus(); }, 0); }
  5373. });
  5374. node.setAttribute("cm-not-content", "true");
  5375. }, function (pos, axis) {
  5376. if (axis == "horizontal") { setScrollLeft(cm, pos); }
  5377. else { updateScrollTop(cm, pos); }
  5378. }, cm);
  5379. if (cm.display.scrollbars.addClass)
  5380. { addClass(cm.display.wrapper, cm.display.scrollbars.addClass); }
  5381. }
  5382. // Operations are used to wrap a series of changes to the editor
  5383. // state in such a way that each change won't have to update the
  5384. // cursor and display (which would be awkward, slow, and
  5385. // error-prone). Instead, display updates are batched and then all
  5386. // combined and executed at once.
  5387. var nextOpId = 0;
  5388. // Start a new operation.
  5389. function startOperation(cm) {
  5390. cm.curOp = {
  5391. cm: cm,
  5392. viewChanged: false, // Flag that indicates that lines might need to be redrawn
  5393. startHeight: cm.doc.height, // Used to detect need to update scrollbar
  5394. forceUpdate: false, // Used to force a redraw
  5395. updateInput: null, // Whether to reset the input textarea
  5396. typing: false, // Whether this reset should be careful to leave existing text (for compositing)
  5397. changeObjs: null, // Accumulated changes, for firing change events
  5398. cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on
  5399. cursorActivityCalled: 0, // Tracks which cursorActivity handlers have been called already
  5400. selectionChanged: false, // Whether the selection needs to be redrawn
  5401. updateMaxLine: false, // Set when the widest line needs to be determined anew
  5402. scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet
  5403. scrollToPos: null, // Used to scroll to a specific position
  5404. focus: false,
  5405. id: ++nextOpId // Unique ID
  5406. };
  5407. pushOperation(cm.curOp);
  5408. }
  5409. // Finish an operation, updating the display and signalling delayed events
  5410. function endOperation(cm) {
  5411. var op = cm.curOp;
  5412. finishOperation(op, function (group) {
  5413. for (var i = 0; i < group.ops.length; i++)
  5414. { group.ops[i].cm.curOp = null; }
  5415. endOperations(group);
  5416. });
  5417. }
  5418. // The DOM updates done when an operation finishes are batched so
  5419. // that the minimum number of relayouts are required.
  5420. function endOperations(group) {
  5421. var ops = group.ops;
  5422. for (var i = 0; i < ops.length; i++) // Read DOM
  5423. { endOperation_R1(ops[i]); }
  5424. for (var i$1 = 0; i$1 < ops.length; i$1++) // Write DOM (maybe)
  5425. { endOperation_W1(ops[i$1]); }
  5426. for (var i$2 = 0; i$2 < ops.length; i$2++) // Read DOM
  5427. { endOperation_R2(ops[i$2]); }
  5428. for (var i$3 = 0; i$3 < ops.length; i$3++) // Write DOM (maybe)
  5429. { endOperation_W2(ops[i$3]); }
  5430. for (var i$4 = 0; i$4 < ops.length; i$4++) // Read DOM
  5431. { endOperation_finish(ops[i$4]); }
  5432. }
  5433. function endOperation_R1(op) {
  5434. var cm = op.cm, display = cm.display;
  5435. maybeClipScrollbars(cm);
  5436. if (op.updateMaxLine) { findMaxLine(cm); }
  5437. op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null ||
  5438. op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom ||
  5439. op.scrollToPos.to.line >= display.viewTo) ||
  5440. display.maxLineChanged && cm.options.lineWrapping;
  5441. op.update = op.mustUpdate &&
  5442. new DisplayUpdate(cm, op.mustUpdate && {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate);
  5443. }
  5444. function endOperation_W1(op) {
  5445. op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update);
  5446. }
  5447. function endOperation_R2(op) {
  5448. var cm = op.cm, display = cm.display;
  5449. if (op.updatedDisplay) { updateHeightsInViewport(cm); }
  5450. op.barMeasure = measureForScrollbars(cm);
  5451. // If the max line changed since it was last measured, measure it,
  5452. // and ensure the document's width matches it.
  5453. // updateDisplay_W2 will use these properties to do the actual resizing
  5454. if (display.maxLineChanged && !cm.options.lineWrapping) {
  5455. op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3;
  5456. cm.display.sizerWidth = op.adjustWidthTo;
  5457. op.barMeasure.scrollWidth =
  5458. Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth);
  5459. op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm));
  5460. }
  5461. if (op.updatedDisplay || op.selectionChanged)
  5462. { op.preparedSelection = display.input.prepareSelection(); }
  5463. }
  5464. function endOperation_W2(op) {
  5465. var cm = op.cm;
  5466. if (op.adjustWidthTo != null) {
  5467. cm.display.sizer.style.minWidth = op.adjustWidthTo + "px";
  5468. if (op.maxScrollLeft < cm.doc.scrollLeft)
  5469. { setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true); }
  5470. cm.display.maxLineChanged = false;
  5471. }
  5472. var takeFocus = op.focus && op.focus == activeElt();
  5473. if (op.preparedSelection)
  5474. { cm.display.input.showSelection(op.preparedSelection, takeFocus); }
  5475. if (op.updatedDisplay || op.startHeight != cm.doc.height)
  5476. { updateScrollbars(cm, op.barMeasure); }
  5477. if (op.updatedDisplay)
  5478. { setDocumentHeight(cm, op.barMeasure); }
  5479. if (op.selectionChanged) { restartBlink(cm); }
  5480. if (cm.state.focused && op.updateInput)
  5481. { cm.display.input.reset(op.typing); }
  5482. if (takeFocus) { ensureFocus(op.cm); }
  5483. }
  5484. function endOperation_finish(op) {
  5485. var cm = op.cm, display = cm.display, doc = cm.doc;
  5486. if (op.updatedDisplay) { postUpdateDisplay(cm, op.update); }
  5487. // Abort mouse wheel delta measurement, when scrolling explicitly
  5488. if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos))
  5489. { display.wheelStartX = display.wheelStartY = null; }
  5490. // Propagate the scroll position to the actual DOM scroller
  5491. if (op.scrollTop != null) { setScrollTop(cm, op.scrollTop, op.forceScroll); }
  5492. if (op.scrollLeft != null) { setScrollLeft(cm, op.scrollLeft, true, true); }
  5493. // If we need to scroll a specific position into view, do so.
  5494. if (op.scrollToPos) {
  5495. var rect = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from),
  5496. clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin);
  5497. maybeScrollWindow(cm, rect);
  5498. }
  5499. // Fire events for markers that are hidden/unidden by editing or
  5500. // undoing
  5501. var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers;
  5502. if (hidden) { for (var i = 0; i < hidden.length; ++i)
  5503. { if (!hidden[i].lines.length) { signal(hidden[i], "hide"); } } }
  5504. if (unhidden) { for (var i$1 = 0; i$1 < unhidden.length; ++i$1)
  5505. { if (unhidden[i$1].lines.length) { signal(unhidden[i$1], "unhide"); } } }
  5506. if (display.wrapper.offsetHeight)
  5507. { doc.scrollTop = cm.display.scroller.scrollTop; }
  5508. // Fire change events, and delayed event handlers
  5509. if (op.changeObjs)
  5510. { signal(cm, "changes", cm, op.changeObjs); }
  5511. if (op.update)
  5512. { op.update.finish(); }
  5513. }
  5514. // Run the given function in an operation
  5515. function runInOp(cm, f) {
  5516. if (cm.curOp) { return f() }
  5517. startOperation(cm);
  5518. try { return f() }
  5519. finally { endOperation(cm); }
  5520. }
  5521. // Wraps a function in an operation. Returns the wrapped function.
  5522. function operation(cm, f) {
  5523. return function() {
  5524. if (cm.curOp) { return f.apply(cm, arguments) }
  5525. startOperation(cm);
  5526. try { return f.apply(cm, arguments) }
  5527. finally { endOperation(cm); }
  5528. }
  5529. }
  5530. // Used to add methods to editor and doc instances, wrapping them in
  5531. // operations.
  5532. function methodOp(f) {
  5533. return function() {
  5534. if (this.curOp) { return f.apply(this, arguments) }
  5535. startOperation(this);
  5536. try { return f.apply(this, arguments) }
  5537. finally { endOperation(this); }
  5538. }
  5539. }
  5540. function docMethodOp(f) {
  5541. return function() {
  5542. var cm = this.cm;
  5543. if (!cm || cm.curOp) { return f.apply(this, arguments) }
  5544. startOperation(cm);
  5545. try { return f.apply(this, arguments) }
  5546. finally { endOperation(cm); }
  5547. }
  5548. }
  5549. // Updates the display.view data structure for a given change to the
  5550. // document. From and to are in pre-change coordinates. Lendiff is
  5551. // the amount of lines added or subtracted by the change. This is
  5552. // used for changes that span multiple lines, or change the way
  5553. // lines are divided into visual lines. regLineChange (below)
  5554. // registers single-line changes.
  5555. function regChange(cm, from, to, lendiff) {
  5556. if (from == null) { from = cm.doc.first; }
  5557. if (to == null) { to = cm.doc.first + cm.doc.size; }
  5558. if (!lendiff) { lendiff = 0; }
  5559. var display = cm.display;
  5560. if (lendiff && to < display.viewTo &&
  5561. (display.updateLineNumbers == null || display.updateLineNumbers > from))
  5562. { display.updateLineNumbers = from; }
  5563. cm.curOp.viewChanged = true;
  5564. if (from >= display.viewTo) { // Change after
  5565. if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo)
  5566. { resetView(cm); }
  5567. } else if (to <= display.viewFrom) { // Change before
  5568. if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) {
  5569. resetView(cm);
  5570. } else {
  5571. display.viewFrom += lendiff;
  5572. display.viewTo += lendiff;
  5573. }
  5574. } else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap
  5575. resetView(cm);
  5576. } else if (from <= display.viewFrom) { // Top overlap
  5577. var cut = viewCuttingPoint(cm, to, to + lendiff, 1);
  5578. if (cut) {
  5579. display.view = display.view.slice(cut.index);
  5580. display.viewFrom = cut.lineN;
  5581. display.viewTo += lendiff;
  5582. } else {
  5583. resetView(cm);
  5584. }
  5585. } else if (to >= display.viewTo) { // Bottom overlap
  5586. var cut$1 = viewCuttingPoint(cm, from, from, -1);
  5587. if (cut$1) {
  5588. display.view = display.view.slice(0, cut$1.index);
  5589. display.viewTo = cut$1.lineN;
  5590. } else {
  5591. resetView(cm);
  5592. }
  5593. } else { // Gap in the middle
  5594. var cutTop = viewCuttingPoint(cm, from, from, -1);
  5595. var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1);
  5596. if (cutTop && cutBot) {
  5597. display.view = display.view.slice(0, cutTop.index)
  5598. .concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN))
  5599. .concat(display.view.slice(cutBot.index));
  5600. display.viewTo += lendiff;
  5601. } else {
  5602. resetView(cm);
  5603. }
  5604. }
  5605. var ext = display.externalMeasured;
  5606. if (ext) {
  5607. if (to < ext.lineN)
  5608. { ext.lineN += lendiff; }
  5609. else if (from < ext.lineN + ext.size)
  5610. { display.externalMeasured = null; }
  5611. }
  5612. }
  5613. // Register a change to a single line. Type must be one of "text",
  5614. // "gutter", "class", "widget"
  5615. function regLineChange(cm, line, type) {
  5616. cm.curOp.viewChanged = true;
  5617. var display = cm.display, ext = cm.display.externalMeasured;
  5618. if (ext && line >= ext.lineN && line < ext.lineN + ext.size)
  5619. { display.externalMeasured = null; }
  5620. if (line < display.viewFrom || line >= display.viewTo) { return }
  5621. var lineView = display.view[findViewIndex(cm, line)];
  5622. if (lineView.node == null) { return }
  5623. var arr = lineView.changes || (lineView.changes = []);
  5624. if (indexOf(arr, type) == -1) { arr.push(type); }
  5625. }
  5626. // Clear the view.
  5627. function resetView(cm) {
  5628. cm.display.viewFrom = cm.display.viewTo = cm.doc.first;
  5629. cm.display.view = [];
  5630. cm.display.viewOffset = 0;
  5631. }
  5632. function viewCuttingPoint(cm, oldN, newN, dir) {
  5633. var index = findViewIndex(cm, oldN), diff, view = cm.display.view;
  5634. if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size)
  5635. { return {index: index, lineN: newN} }
  5636. var n = cm.display.viewFrom;
  5637. for (var i = 0; i < index; i++)
  5638. { n += view[i].size; }
  5639. if (n != oldN) {
  5640. if (dir > 0) {
  5641. if (index == view.length - 1) { return null }
  5642. diff = (n + view[index].size) - oldN;
  5643. index++;
  5644. } else {
  5645. diff = n - oldN;
  5646. }
  5647. oldN += diff; newN += diff;
  5648. }
  5649. while (visualLineNo(cm.doc, newN) != newN) {
  5650. if (index == (dir < 0 ? 0 : view.length - 1)) { return null }
  5651. newN += dir * view[index - (dir < 0 ? 1 : 0)].size;
  5652. index += dir;
  5653. }
  5654. return {index: index, lineN: newN}
  5655. }
  5656. // Force the view to cover a given range, adding empty view element
  5657. // or clipping off existing ones as needed.
  5658. function adjustView(cm, from, to) {
  5659. var display = cm.display, view = display.view;
  5660. if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) {
  5661. display.view = buildViewArray(cm, from, to);
  5662. display.viewFrom = from;
  5663. } else {
  5664. if (display.viewFrom > from)
  5665. { display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view); }
  5666. else if (display.viewFrom < from)
  5667. { display.view = display.view.slice(findViewIndex(cm, from)); }
  5668. display.viewFrom = from;
  5669. if (display.viewTo < to)
  5670. { display.view = display.view.concat(buildViewArray(cm, display.viewTo, to)); }
  5671. else if (display.viewTo > to)
  5672. { display.view = display.view.slice(0, findViewIndex(cm, to)); }
  5673. }
  5674. display.viewTo = to;
  5675. }
  5676. // Count the number of lines in the view whose DOM representation is
  5677. // out of date (or nonexistent).
  5678. function countDirtyView(cm) {
  5679. var view = cm.display.view, dirty = 0;
  5680. for (var i = 0; i < view.length; i++) {
  5681. var lineView = view[i];
  5682. if (!lineView.hidden && (!lineView.node || lineView.changes)) { ++dirty; }
  5683. }
  5684. return dirty
  5685. }
  5686. // HIGHLIGHT WORKER
  5687. function startWorker(cm, time) {
  5688. if (cm.doc.highlightFrontier < cm.display.viewTo)
  5689. { cm.state.highlight.set(time, bind(highlightWorker, cm)); }
  5690. }
  5691. function highlightWorker(cm) {
  5692. var doc = cm.doc;
  5693. if (doc.highlightFrontier >= cm.display.viewTo) { return }
  5694. var end = +new Date + cm.options.workTime;
  5695. var context = getContextBefore(cm, doc.highlightFrontier);
  5696. var changedLines = [];
  5697. doc.iter(context.line, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function (line) {
  5698. if (context.line >= cm.display.viewFrom) { // Visible
  5699. var oldStyles = line.styles;
  5700. var resetState = line.text.length > cm.options.maxHighlightLength ? copyState(doc.mode, context.state) : null;
  5701. var highlighted = highlightLine(cm, line, context, true);
  5702. if (resetState) { context.state = resetState; }
  5703. line.styles = highlighted.styles;
  5704. var oldCls = line.styleClasses, newCls = highlighted.classes;
  5705. if (newCls) { line.styleClasses = newCls; }
  5706. else if (oldCls) { line.styleClasses = null; }
  5707. var ischange = !oldStyles || oldStyles.length != line.styles.length ||
  5708. oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass);
  5709. for (var i = 0; !ischange && i < oldStyles.length; ++i) { ischange = oldStyles[i] != line.styles[i]; }
  5710. if (ischange) { changedLines.push(context.line); }
  5711. line.stateAfter = context.save();
  5712. context.nextLine();
  5713. } else {
  5714. if (line.text.length <= cm.options.maxHighlightLength)
  5715. { processLine(cm, line.text, context); }
  5716. line.stateAfter = context.line % 5 == 0 ? context.save() : null;
  5717. context.nextLine();
  5718. }
  5719. if (+new Date > end) {
  5720. startWorker(cm, cm.options.workDelay);
  5721. return true
  5722. }
  5723. });
  5724. doc.highlightFrontier = context.line;
  5725. doc.modeFrontier = Math.max(doc.modeFrontier, context.line);
  5726. if (changedLines.length) { runInOp(cm, function () {
  5727. for (var i = 0; i < changedLines.length; i++)
  5728. { regLineChange(cm, changedLines[i], "text"); }
  5729. }); }
  5730. }
  5731. // DISPLAY DRAWING
  5732. var DisplayUpdate = function(cm, viewport, force) {
  5733. var display = cm.display;
  5734. this.viewport = viewport;
  5735. // Store some values that we'll need later (but don't want to force a relayout for)
  5736. this.visible = visibleLines(display, cm.doc, viewport);
  5737. this.editorIsHidden = !display.wrapper.offsetWidth;
  5738. this.wrapperHeight = display.wrapper.clientHeight;
  5739. this.wrapperWidth = display.wrapper.clientWidth;
  5740. this.oldDisplayWidth = displayWidth(cm);
  5741. this.force = force;
  5742. this.dims = getDimensions(cm);
  5743. this.events = [];
  5744. };
  5745. DisplayUpdate.prototype.signal = function (emitter, type) {
  5746. if (hasHandler(emitter, type))
  5747. { this.events.push(arguments); }
  5748. };
  5749. DisplayUpdate.prototype.finish = function () {
  5750. var this$1 = this;
  5751. for (var i = 0; i < this.events.length; i++)
  5752. { signal.apply(null, this$1.events[i]); }
  5753. };
  5754. function maybeClipScrollbars(cm) {
  5755. var display = cm.display;
  5756. if (!display.scrollbarsClipped && display.scroller.offsetWidth) {
  5757. display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth;
  5758. display.heightForcer.style.height = scrollGap(cm) + "px";
  5759. display.sizer.style.marginBottom = -display.nativeBarWidth + "px";
  5760. display.sizer.style.borderRightWidth = scrollGap(cm) + "px";
  5761. display.scrollbarsClipped = true;
  5762. }
  5763. }
  5764. function selectionSnapshot(cm) {
  5765. if (cm.hasFocus()) { return null }
  5766. var active = activeElt();
  5767. if (!active || !contains(cm.display.lineDiv, active)) { return null }
  5768. var result = {activeElt: active};
  5769. if (window.getSelection) {
  5770. var sel = window.getSelection();
  5771. if (sel.anchorNode && sel.extend && contains(cm.display.lineDiv, sel.anchorNode)) {
  5772. result.anchorNode = sel.anchorNode;
  5773. result.anchorOffset = sel.anchorOffset;
  5774. result.focusNode = sel.focusNode;
  5775. result.focusOffset = sel.focusOffset;
  5776. }
  5777. }
  5778. return result
  5779. }
  5780. function restoreSelection(snapshot) {
  5781. if (!snapshot || !snapshot.activeElt || snapshot.activeElt == activeElt()) { return }
  5782. snapshot.activeElt.focus();
  5783. if (snapshot.anchorNode && contains(document.body, snapshot.anchorNode) && contains(document.body, snapshot.focusNode)) {
  5784. var sel = window.getSelection(), range$$1 = document.createRange();
  5785. range$$1.setEnd(snapshot.anchorNode, snapshot.anchorOffset);
  5786. range$$1.collapse(false);
  5787. sel.removeAllRanges();
  5788. sel.addRange(range$$1);
  5789. sel.extend(snapshot.focusNode, snapshot.focusOffset);
  5790. }
  5791. }
  5792. // Does the actual updating of the line display. Bails out
  5793. // (returning false) when there is nothing to be done and forced is
  5794. // false.
  5795. function updateDisplayIfNeeded(cm, update) {
  5796. var display = cm.display, doc = cm.doc;
  5797. if (update.editorIsHidden) {
  5798. resetView(cm);
  5799. return false
  5800. }
  5801. // Bail out if the visible area is already rendered and nothing changed.
  5802. if (!update.force &&
  5803. update.visible.from >= display.viewFrom && update.visible.to <= display.viewTo &&
  5804. (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) &&
  5805. display.renderedView == display.view && countDirtyView(cm) == 0)
  5806. { return false }
  5807. if (maybeUpdateLineNumberWidth(cm)) {
  5808. resetView(cm);
  5809. update.dims = getDimensions(cm);
  5810. }
  5811. // Compute a suitable new viewport (from & to)
  5812. var end = doc.first + doc.size;
  5813. var from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first);
  5814. var to = Math.min(end, update.visible.to + cm.options.viewportMargin);
  5815. if (display.viewFrom < from && from - display.viewFrom < 20) { from = Math.max(doc.first, display.viewFrom); }
  5816. if (display.viewTo > to && display.viewTo - to < 20) { to = Math.min(end, display.viewTo); }
  5817. if (sawCollapsedSpans) {
  5818. from = visualLineNo(cm.doc, from);
  5819. to = visualLineEndNo(cm.doc, to);
  5820. }
  5821. var different = from != display.viewFrom || to != display.viewTo ||
  5822. display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth;
  5823. adjustView(cm, from, to);
  5824. display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom));
  5825. // Position the mover div to align with the current scroll position
  5826. cm.display.mover.style.top = display.viewOffset + "px";
  5827. var toUpdate = countDirtyView(cm);
  5828. if (!different && toUpdate == 0 && !update.force && display.renderedView == display.view &&
  5829. (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo))
  5830. { return false }
  5831. // For big changes, we hide the enclosing element during the
  5832. // update, since that speeds up the operations on most browsers.
  5833. var selSnapshot = selectionSnapshot(cm);
  5834. if (toUpdate > 4) { display.lineDiv.style.display = "none"; }
  5835. patchDisplay(cm, display.updateLineNumbers, update.dims);
  5836. if (toUpdate > 4) { display.lineDiv.style.display = ""; }
  5837. display.renderedView = display.view;
  5838. // There might have been a widget with a focused element that got
  5839. // hidden or updated, if so re-focus it.
  5840. restoreSelection(selSnapshot);
  5841. // Prevent selection and cursors from interfering with the scroll
  5842. // width and height.
  5843. removeChildren(display.cursorDiv);
  5844. removeChildren(display.selectionDiv);
  5845. display.gutters.style.height = display.sizer.style.minHeight = 0;
  5846. if (different) {
  5847. display.lastWrapHeight = update.wrapperHeight;
  5848. display.lastWrapWidth = update.wrapperWidth;
  5849. startWorker(cm, 400);
  5850. }
  5851. display.updateLineNumbers = null;
  5852. return true
  5853. }
  5854. function postUpdateDisplay(cm, update) {
  5855. var viewport = update.viewport;
  5856. for (var first = true;; first = false) {
  5857. if (!first || !cm.options.lineWrapping || update.oldDisplayWidth == displayWidth(cm)) {
  5858. // Clip forced viewport to actual scrollable area.
  5859. if (viewport && viewport.top != null)
  5860. { viewport = {top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top)}; }
  5861. // Updated line heights might result in the drawn area not
  5862. // actually covering the viewport. Keep looping until it does.
  5863. update.visible = visibleLines(cm.display, cm.doc, viewport);
  5864. if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo)
  5865. { break }
  5866. }
  5867. if (!updateDisplayIfNeeded(cm, update)) { break }
  5868. updateHeightsInViewport(cm);
  5869. var barMeasure = measureForScrollbars(cm);
  5870. updateSelection(cm);
  5871. updateScrollbars(cm, barMeasure);
  5872. setDocumentHeight(cm, barMeasure);
  5873. update.force = false;
  5874. }
  5875. update.signal(cm, "update", cm);
  5876. if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) {
  5877. update.signal(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo);
  5878. cm.display.reportedViewFrom = cm.display.viewFrom; cm.display.reportedViewTo = cm.display.viewTo;
  5879. }
  5880. }
  5881. function updateDisplaySimple(cm, viewport) {
  5882. var update = new DisplayUpdate(cm, viewport);
  5883. if (updateDisplayIfNeeded(cm, update)) {
  5884. updateHeightsInViewport(cm);
  5885. postUpdateDisplay(cm, update);
  5886. var barMeasure = measureForScrollbars(cm);
  5887. updateSelection(cm);
  5888. updateScrollbars(cm, barMeasure);
  5889. setDocumentHeight(cm, barMeasure);
  5890. update.finish();
  5891. }
  5892. }
  5893. // Sync the actual display DOM structure with display.view, removing
  5894. // nodes for lines that are no longer in view, and creating the ones
  5895. // that are not there yet, and updating the ones that are out of
  5896. // date.
  5897. function patchDisplay(cm, updateNumbersFrom, dims) {
  5898. var display = cm.display, lineNumbers = cm.options.lineNumbers;
  5899. var container = display.lineDiv, cur = container.firstChild;
  5900. function rm(node) {
  5901. var next = node.nextSibling;
  5902. // Works around a throw-scroll bug in OS X Webkit
  5903. if (webkit && mac && cm.display.currentWheelTarget == node)
  5904. { node.style.display = "none"; }
  5905. else
  5906. { node.parentNode.removeChild(node); }
  5907. return next
  5908. }
  5909. var view = display.view, lineN = display.viewFrom;
  5910. // Loop over the elements in the view, syncing cur (the DOM nodes
  5911. // in display.lineDiv) with the view as we go.
  5912. for (var i = 0; i < view.length; i++) {
  5913. var lineView = view[i];
  5914. if (lineView.hidden) {
  5915. } else if (!lineView.node || lineView.node.parentNode != container) { // Not drawn yet
  5916. var node = buildLineElement(cm, lineView, lineN, dims);
  5917. container.insertBefore(node, cur);
  5918. } else { // Already drawn
  5919. while (cur != lineView.node) { cur = rm(cur); }
  5920. var updateNumber = lineNumbers && updateNumbersFrom != null &&
  5921. updateNumbersFrom <= lineN && lineView.lineNumber;
  5922. if (lineView.changes) {
  5923. if (indexOf(lineView.changes, "gutter") > -1) { updateNumber = false; }
  5924. updateLineForChanges(cm, lineView, lineN, dims);
  5925. }
  5926. if (updateNumber) {
  5927. removeChildren(lineView.lineNumber);
  5928. lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN)));
  5929. }
  5930. cur = lineView.node.nextSibling;
  5931. }
  5932. lineN += lineView.size;
  5933. }
  5934. while (cur) { cur = rm(cur); }
  5935. }
  5936. function updateGutterSpace(cm) {
  5937. var width = cm.display.gutters.offsetWidth;
  5938. cm.display.sizer.style.marginLeft = width + "px";
  5939. }
  5940. function setDocumentHeight(cm, measure) {
  5941. cm.display.sizer.style.minHeight = measure.docHeight + "px";
  5942. cm.display.heightForcer.style.top = measure.docHeight + "px";
  5943. cm.display.gutters.style.height = (measure.docHeight + cm.display.barHeight + scrollGap(cm)) + "px";
  5944. }
  5945. // Rebuild the gutter elements, ensure the margin to the left of the
  5946. // code matches their width.
  5947. function updateGutters(cm) {
  5948. var gutters = cm.display.gutters, specs = cm.options.gutters;
  5949. removeChildren(gutters);
  5950. var i = 0;
  5951. for (; i < specs.length; ++i) {
  5952. var gutterClass = specs[i];
  5953. var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + gutterClass));
  5954. if (gutterClass == "CodeMirror-linenumbers") {
  5955. cm.display.lineGutter = gElt;
  5956. gElt.style.width = (cm.display.lineNumWidth || 1) + "px";
  5957. }
  5958. }
  5959. gutters.style.display = i ? "" : "none";
  5960. updateGutterSpace(cm);
  5961. }
  5962. // Make sure the gutters options contains the element
  5963. // "CodeMirror-linenumbers" when the lineNumbers option is true.
  5964. function setGuttersForLineNumbers(options) {
  5965. var found = indexOf(options.gutters, "CodeMirror-linenumbers");
  5966. if (found == -1 && options.lineNumbers) {
  5967. options.gutters = options.gutters.concat(["CodeMirror-linenumbers"]);
  5968. } else if (found > -1 && !options.lineNumbers) {
  5969. options.gutters = options.gutters.slice(0);
  5970. options.gutters.splice(found, 1);
  5971. }
  5972. }
  5973. // Since the delta values reported on mouse wheel events are
  5974. // unstandardized between browsers and even browser versions, and
  5975. // generally horribly unpredictable, this code starts by measuring
  5976. // the scroll effect that the first few mouse wheel events have,
  5977. // and, from that, detects the way it can convert deltas to pixel
  5978. // offsets afterwards.
  5979. //
  5980. // The reason we want to know the amount a wheel event will scroll
  5981. // is that it gives us a chance to update the display before the
  5982. // actual scrolling happens, reducing flickering.
  5983. var wheelSamples = 0;
  5984. var wheelPixelsPerUnit = null;
  5985. // Fill in a browser-detected starting value on browsers where we
  5986. // know one. These don't have to be accurate -- the result of them
  5987. // being wrong would just be a slight flicker on the first wheel
  5988. // scroll (if it is large enough).
  5989. if (ie) { wheelPixelsPerUnit = -.53; }
  5990. else if (gecko) { wheelPixelsPerUnit = 15; }
  5991. else if (chrome) { wheelPixelsPerUnit = -.7; }
  5992. else if (safari) { wheelPixelsPerUnit = -1/3; }
  5993. function wheelEventDelta(e) {
  5994. var dx = e.wheelDeltaX, dy = e.wheelDeltaY;
  5995. if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) { dx = e.detail; }
  5996. if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) { dy = e.detail; }
  5997. else if (dy == null) { dy = e.wheelDelta; }
  5998. return {x: dx, y: dy}
  5999. }
  6000. function wheelEventPixels(e) {
  6001. var delta = wheelEventDelta(e);
  6002. delta.x *= wheelPixelsPerUnit;
  6003. delta.y *= wheelPixelsPerUnit;
  6004. return delta
  6005. }
  6006. function onScrollWheel(cm, e) {
  6007. var delta = wheelEventDelta(e), dx = delta.x, dy = delta.y;
  6008. var display = cm.display, scroll = display.scroller;
  6009. // Quit if there's nothing to scroll here
  6010. var canScrollX = scroll.scrollWidth > scroll.clientWidth;
  6011. var canScrollY = scroll.scrollHeight > scroll.clientHeight;
  6012. if (!(dx && canScrollX || dy && canScrollY)) { return }
  6013. // Webkit browsers on OS X abort momentum scrolls when the target
  6014. // of the scroll event is removed from the scrollable element.
  6015. // This hack (see related code in patchDisplay) makes sure the
  6016. // element is kept around.
  6017. if (dy && mac && webkit) {
  6018. outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) {
  6019. for (var i = 0; i < view.length; i++) {
  6020. if (view[i].node == cur) {
  6021. cm.display.currentWheelTarget = cur;
  6022. break outer
  6023. }
  6024. }
  6025. }
  6026. }
  6027. // On some browsers, horizontal scrolling will cause redraws to
  6028. // happen before the gutter has been realigned, causing it to
  6029. // wriggle around in a most unseemly way. When we have an
  6030. // estimated pixels/delta value, we just handle horizontal
  6031. // scrolling entirely here. It'll be slightly off from native, but
  6032. // better than glitching out.
  6033. if (dx && !gecko && !presto && wheelPixelsPerUnit != null) {
  6034. if (dy && canScrollY)
  6035. { updateScrollTop(cm, Math.max(0, scroll.scrollTop + dy * wheelPixelsPerUnit)); }
  6036. setScrollLeft(cm, Math.max(0, scroll.scrollLeft + dx * wheelPixelsPerUnit));
  6037. // Only prevent default scrolling if vertical scrolling is
  6038. // actually possible. Otherwise, it causes vertical scroll
  6039. // jitter on OSX trackpads when deltaX is small and deltaY
  6040. // is large (issue #3579)
  6041. if (!dy || (dy && canScrollY))
  6042. { e_preventDefault(e); }
  6043. display.wheelStartX = null; // Abort measurement, if in progress
  6044. return
  6045. }
  6046. // 'Project' the visible viewport to cover the area that is being
  6047. // scrolled into view (if we know enough to estimate it).
  6048. if (dy && wheelPixelsPerUnit != null) {
  6049. var pixels = dy * wheelPixelsPerUnit;
  6050. var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight;
  6051. if (pixels < 0) { top = Math.max(0, top + pixels - 50); }
  6052. else { bot = Math.min(cm.doc.height, bot + pixels + 50); }
  6053. updateDisplaySimple(cm, {top: top, bottom: bot});
  6054. }
  6055. if (wheelSamples < 20) {
  6056. if (display.wheelStartX == null) {
  6057. display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop;
  6058. display.wheelDX = dx; display.wheelDY = dy;
  6059. setTimeout(function () {
  6060. if (display.wheelStartX == null) { return }
  6061. var movedX = scroll.scrollLeft - display.wheelStartX;
  6062. var movedY = scroll.scrollTop - display.wheelStartY;
  6063. var sample = (movedY && display.wheelDY && movedY / display.wheelDY) ||
  6064. (movedX && display.wheelDX && movedX / display.wheelDX);
  6065. display.wheelStartX = display.wheelStartY = null;
  6066. if (!sample) { return }
  6067. wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1);
  6068. ++wheelSamples;
  6069. }, 200);
  6070. } else {
  6071. display.wheelDX += dx; display.wheelDY += dy;
  6072. }
  6073. }
  6074. }
  6075. // Selection objects are immutable. A new one is created every time
  6076. // the selection changes. A selection is one or more non-overlapping
  6077. // (and non-touching) ranges, sorted, and an integer that indicates
  6078. // which one is the primary selection (the one that's scrolled into
  6079. // view, that getCursor returns, etc).
  6080. var Selection = function(ranges, primIndex) {
  6081. this.ranges = ranges;
  6082. this.primIndex = primIndex;
  6083. };
  6084. Selection.prototype.primary = function () { return this.ranges[this.primIndex] };
  6085. Selection.prototype.equals = function (other) {
  6086. var this$1 = this;
  6087. if (other == this) { return true }
  6088. if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) { return false }
  6089. for (var i = 0; i < this.ranges.length; i++) {
  6090. var here = this$1.ranges[i], there = other.ranges[i];
  6091. if (!equalCursorPos(here.anchor, there.anchor) || !equalCursorPos(here.head, there.head)) { return false }
  6092. }
  6093. return true
  6094. };
  6095. Selection.prototype.deepCopy = function () {
  6096. var this$1 = this;
  6097. var out = [];
  6098. for (var i = 0; i < this.ranges.length; i++)
  6099. { out[i] = new Range(copyPos(this$1.ranges[i].anchor), copyPos(this$1.ranges[i].head)); }
  6100. return new Selection(out, this.primIndex)
  6101. };
  6102. Selection.prototype.somethingSelected = function () {
  6103. var this$1 = this;
  6104. for (var i = 0; i < this.ranges.length; i++)
  6105. { if (!this$1.ranges[i].empty()) { return true } }
  6106. return false
  6107. };
  6108. Selection.prototype.contains = function (pos, end) {
  6109. var this$1 = this;
  6110. if (!end) { end = pos; }
  6111. for (var i = 0; i < this.ranges.length; i++) {
  6112. var range = this$1.ranges[i];
  6113. if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0)
  6114. { return i }
  6115. }
  6116. return -1
  6117. };
  6118. var Range = function(anchor, head) {
  6119. this.anchor = anchor; this.head = head;
  6120. };
  6121. Range.prototype.from = function () { return minPos(this.anchor, this.head) };
  6122. Range.prototype.to = function () { return maxPos(this.anchor, this.head) };
  6123. Range.prototype.empty = function () { return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch };
  6124. // Take an unsorted, potentially overlapping set of ranges, and
  6125. // build a selection out of it. 'Consumes' ranges array (modifying
  6126. // it).
  6127. function normalizeSelection(ranges, primIndex) {
  6128. var prim = ranges[primIndex];
  6129. ranges.sort(function (a, b) { return cmp(a.from(), b.from()); });
  6130. primIndex = indexOf(ranges, prim);
  6131. for (var i = 1; i < ranges.length; i++) {
  6132. var cur = ranges[i], prev = ranges[i - 1];
  6133. if (cmp(prev.to(), cur.from()) >= 0) {
  6134. var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to());
  6135. var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head;
  6136. if (i <= primIndex) { --primIndex; }
  6137. ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to));
  6138. }
  6139. }
  6140. return new Selection(ranges, primIndex)
  6141. }
  6142. function simpleSelection(anchor, head) {
  6143. return new Selection([new Range(anchor, head || anchor)], 0)
  6144. }
  6145. // Compute the position of the end of a change (its 'to' property
  6146. // refers to the pre-change end).
  6147. function changeEnd(change) {
  6148. if (!change.text) { return change.to }
  6149. return Pos(change.from.line + change.text.length - 1,
  6150. lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0))
  6151. }
  6152. // Adjust a position to refer to the post-change position of the
  6153. // same text, or the end of the change if the change covers it.
  6154. function adjustForChange(pos, change) {
  6155. if (cmp(pos, change.from) < 0) { return pos }
  6156. if (cmp(pos, change.to) <= 0) { return changeEnd(change) }
  6157. var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch;
  6158. if (pos.line == change.to.line) { ch += changeEnd(change).ch - change.to.ch; }
  6159. return Pos(line, ch)
  6160. }
  6161. function computeSelAfterChange(doc, change) {
  6162. var out = [];
  6163. for (var i = 0; i < doc.sel.ranges.length; i++) {
  6164. var range = doc.sel.ranges[i];
  6165. out.push(new Range(adjustForChange(range.anchor, change),
  6166. adjustForChange(range.head, change)));
  6167. }
  6168. return normalizeSelection(out, doc.sel.primIndex)
  6169. }
  6170. function offsetPos(pos, old, nw) {
  6171. if (pos.line == old.line)
  6172. { return Pos(nw.line, pos.ch - old.ch + nw.ch) }
  6173. else
  6174. { return Pos(nw.line + (pos.line - old.line), pos.ch) }
  6175. }
  6176. // Used by replaceSelections to allow moving the selection to the
  6177. // start or around the replaced test. Hint may be "start" or "around".
  6178. function computeReplacedSel(doc, changes, hint) {
  6179. var out = [];
  6180. var oldPrev = Pos(doc.first, 0), newPrev = oldPrev;
  6181. for (var i = 0; i < changes.length; i++) {
  6182. var change = changes[i];
  6183. var from = offsetPos(change.from, oldPrev, newPrev);
  6184. var to = offsetPos(changeEnd(change), oldPrev, newPrev);
  6185. oldPrev = change.to;
  6186. newPrev = to;
  6187. if (hint == "around") {
  6188. var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) < 0;
  6189. out[i] = new Range(inv ? to : from, inv ? from : to);
  6190. } else {
  6191. out[i] = new Range(from, from);
  6192. }
  6193. }
  6194. return new Selection(out, doc.sel.primIndex)
  6195. }
  6196. // Used to get the editor into a consistent state again when options change.
  6197. function loadMode(cm) {
  6198. cm.doc.mode = getMode(cm.options, cm.doc.modeOption);
  6199. resetModeState(cm);
  6200. }
  6201. function resetModeState(cm) {
  6202. cm.doc.iter(function (line) {
  6203. if (line.stateAfter) { line.stateAfter = null; }
  6204. if (line.styles) { line.styles = null; }
  6205. });
  6206. cm.doc.modeFrontier = cm.doc.highlightFrontier = cm.doc.first;
  6207. startWorker(cm, 100);
  6208. cm.state.modeGen++;
  6209. if (cm.curOp) { regChange(cm); }
  6210. }
  6211. // DOCUMENT DATA STRUCTURE
  6212. // By default, updates that start and end at the beginning of a line
  6213. // are treated specially, in order to make the association of line
  6214. // widgets and marker elements with the text behave more intuitive.
  6215. function isWholeLineUpdate(doc, change) {
  6216. return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" &&
  6217. (!doc.cm || doc.cm.options.wholeLineUpdateBefore)
  6218. }
  6219. // Perform a change on the document data structure.
  6220. function updateDoc(doc, change, markedSpans, estimateHeight$$1) {
  6221. function spansFor(n) {return markedSpans ? markedSpans[n] : null}
  6222. function update(line, text, spans) {
  6223. updateLine(line, text, spans, estimateHeight$$1);
  6224. signalLater(line, "change", line, change);
  6225. }
  6226. function linesFor(start, end) {
  6227. var result = [];
  6228. for (var i = start; i < end; ++i)
  6229. { result.push(new Line(text[i], spansFor(i), estimateHeight$$1)); }
  6230. return result
  6231. }
  6232. var from = change.from, to = change.to, text = change.text;
  6233. var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line);
  6234. var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line;
  6235. // Adjust the line structure
  6236. if (change.full) {
  6237. doc.insert(0, linesFor(0, text.length));
  6238. doc.remove(text.length, doc.size - text.length);
  6239. } else if (isWholeLineUpdate(doc, change)) {
  6240. // This is a whole-line replace. Treated specially to make
  6241. // sure line objects move the way they are supposed to.
  6242. var added = linesFor(0, text.length - 1);
  6243. update(lastLine, lastLine.text, lastSpans);
  6244. if (nlines) { doc.remove(from.line, nlines); }
  6245. if (added.length) { doc.insert(from.line, added); }
  6246. } else if (firstLine == lastLine) {
  6247. if (text.length == 1) {
  6248. update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans);
  6249. } else {
  6250. var added$1 = linesFor(1, text.length - 1);
  6251. added$1.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight$$1));
  6252. update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
  6253. doc.insert(from.line + 1, added$1);
  6254. }
  6255. } else if (text.length == 1) {
  6256. update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0));
  6257. doc.remove(from.line + 1, nlines);
  6258. } else {
  6259. update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
  6260. update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans);
  6261. var added$2 = linesFor(1, text.length - 1);
  6262. if (nlines > 1) { doc.remove(from.line + 1, nlines - 1); }
  6263. doc.insert(from.line + 1, added$2);
  6264. }
  6265. signalLater(doc, "change", doc, change);
  6266. }
  6267. // Call f for all linked documents.
  6268. function linkedDocs(doc, f, sharedHistOnly) {
  6269. function propagate(doc, skip, sharedHist) {
  6270. if (doc.linked) { for (var i = 0; i < doc.linked.length; ++i) {
  6271. var rel = doc.linked[i];
  6272. if (rel.doc == skip) { continue }
  6273. var shared = sharedHist && rel.sharedHist;
  6274. if (sharedHistOnly && !shared) { continue }
  6275. f(rel.doc, shared);
  6276. propagate(rel.doc, doc, shared);
  6277. } }
  6278. }
  6279. propagate(doc, null, true);
  6280. }
  6281. // Attach a document to an editor.
  6282. function attachDoc(cm, doc) {
  6283. if (doc.cm) { throw new Error("This document is already in use.") }
  6284. cm.doc = doc;
  6285. doc.cm = cm;
  6286. estimateLineHeights(cm);
  6287. loadMode(cm);
  6288. setDirectionClass(cm);
  6289. if (!cm.options.lineWrapping) { findMaxLine(cm); }
  6290. cm.options.mode = doc.modeOption;
  6291. regChange(cm);
  6292. }
  6293. function setDirectionClass(cm) {
  6294. (cm.doc.direction == "rtl" ? addClass : rmClass)(cm.display.lineDiv, "CodeMirror-rtl");
  6295. }
  6296. function directionChanged(cm) {
  6297. runInOp(cm, function () {
  6298. setDirectionClass(cm);
  6299. regChange(cm);
  6300. });
  6301. }
  6302. function History(startGen) {
  6303. // Arrays of change events and selections. Doing something adds an
  6304. // event to done and clears undo. Undoing moves events from done
  6305. // to undone, redoing moves them in the other direction.
  6306. this.done = []; this.undone = [];
  6307. this.undoDepth = Infinity;
  6308. // Used to track when changes can be merged into a single undo
  6309. // event
  6310. this.lastModTime = this.lastSelTime = 0;
  6311. this.lastOp = this.lastSelOp = null;
  6312. this.lastOrigin = this.lastSelOrigin = null;
  6313. // Used by the isClean() method
  6314. this.generation = this.maxGeneration = startGen || 1;
  6315. }
  6316. // Create a history change event from an updateDoc-style change
  6317. // object.
  6318. function historyChangeFromChange(doc, change) {
  6319. var histChange = {from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to)};
  6320. attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);
  6321. linkedDocs(doc, function (doc) { return attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1); }, true);
  6322. return histChange
  6323. }
  6324. // Pop all selection events off the end of a history array. Stop at
  6325. // a change event.
  6326. function clearSelectionEvents(array) {
  6327. while (array.length) {
  6328. var last = lst(array);
  6329. if (last.ranges) { array.pop(); }
  6330. else { break }
  6331. }
  6332. }
  6333. // Find the top change event in the history. Pop off selection
  6334. // events that are in the way.
  6335. function lastChangeEvent(hist, force) {
  6336. if (force) {
  6337. clearSelectionEvents(hist.done);
  6338. return lst(hist.done)
  6339. } else if (hist.done.length && !lst(hist.done).ranges) {
  6340. return lst(hist.done)
  6341. } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) {
  6342. hist.done.pop();
  6343. return lst(hist.done)
  6344. }
  6345. }
  6346. // Register a change in the history. Merges changes that are within
  6347. // a single operation, or are close together with an origin that
  6348. // allows merging (starting with "+") into a single event.
  6349. function addChangeToHistory(doc, change, selAfter, opId) {
  6350. var hist = doc.history;
  6351. hist.undone.length = 0;
  6352. var time = +new Date, cur;
  6353. var last;
  6354. if ((hist.lastOp == opId ||
  6355. hist.lastOrigin == change.origin && change.origin &&
  6356. ((change.origin.charAt(0) == "+" && doc.cm && hist.lastModTime > time - doc.cm.options.historyEventDelay) ||
  6357. change.origin.charAt(0) == "*")) &&
  6358. (cur = lastChangeEvent(hist, hist.lastOp == opId))) {
  6359. // Merge this change into the last event
  6360. last = lst(cur.changes);
  6361. if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) {
  6362. // Optimized case for simple insertion -- don't want to add
  6363. // new changesets for every character typed
  6364. last.to = changeEnd(change);
  6365. } else {
  6366. // Add new sub-event
  6367. cur.changes.push(historyChangeFromChange(doc, change));
  6368. }
  6369. } else {
  6370. // Can not be merged, start a new event.
  6371. var before = lst(hist.done);
  6372. if (!before || !before.ranges)
  6373. { pushSelectionToHistory(doc.sel, hist.done); }
  6374. cur = {changes: [historyChangeFromChange(doc, change)],
  6375. generation: hist.generation};
  6376. hist.done.push(cur);
  6377. while (hist.done.length > hist.undoDepth) {
  6378. hist.done.shift();
  6379. if (!hist.done[0].ranges) { hist.done.shift(); }
  6380. }
  6381. }
  6382. hist.done.push(selAfter);
  6383. hist.generation = ++hist.maxGeneration;
  6384. hist.lastModTime = hist.lastSelTime = time;
  6385. hist.lastOp = hist.lastSelOp = opId;
  6386. hist.lastOrigin = hist.lastSelOrigin = change.origin;
  6387. if (!last) { signal(doc, "historyAdded"); }
  6388. }
  6389. function selectionEventCanBeMerged(doc, origin, prev, sel) {
  6390. var ch = origin.charAt(0);
  6391. return ch == "*" ||
  6392. ch == "+" &&
  6393. prev.ranges.length == sel.ranges.length &&
  6394. prev.somethingSelected() == sel.somethingSelected() &&
  6395. new Date - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500)
  6396. }
  6397. // Called whenever the selection changes, sets the new selection as
  6398. // the pending selection in the history, and pushes the old pending
  6399. // selection into the 'done' array when it was significantly
  6400. // different (in number of selected ranges, emptiness, or time).
  6401. function addSelectionToHistory(doc, sel, opId, options) {
  6402. var hist = doc.history, origin = options && options.origin;
  6403. // A new event is started when the previous origin does not match
  6404. // the current, or the origins don't allow matching. Origins
  6405. // starting with * are always merged, those starting with + are
  6406. // merged when similar and close together in time.
  6407. if (opId == hist.lastSelOp ||
  6408. (origin && hist.lastSelOrigin == origin &&
  6409. (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin ||
  6410. selectionEventCanBeMerged(doc, origin, lst(hist.done), sel))))
  6411. { hist.done[hist.done.length - 1] = sel; }
  6412. else
  6413. { pushSelectionToHistory(sel, hist.done); }
  6414. hist.lastSelTime = +new Date;
  6415. hist.lastSelOrigin = origin;
  6416. hist.lastSelOp = opId;
  6417. if (options && options.clearRedo !== false)
  6418. { clearSelectionEvents(hist.undone); }
  6419. }
  6420. function pushSelectionToHistory(sel, dest) {
  6421. var top = lst(dest);
  6422. if (!(top && top.ranges && top.equals(sel)))
  6423. { dest.push(sel); }
  6424. }
  6425. // Used to store marked span information in the history.
  6426. function attachLocalSpans(doc, change, from, to) {
  6427. var existing = change["spans_" + doc.id], n = 0;
  6428. doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function (line) {
  6429. if (line.markedSpans)
  6430. { (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans; }
  6431. ++n;
  6432. });
  6433. }
  6434. // When un/re-doing restores text containing marked spans, those
  6435. // that have been explicitly cleared should not be restored.
  6436. function removeClearedSpans(spans) {
  6437. if (!spans) { return null }
  6438. var out;
  6439. for (var i = 0; i < spans.length; ++i) {
  6440. if (spans[i].marker.explicitlyCleared) { if (!out) { out = spans.slice(0, i); } }
  6441. else if (out) { out.push(spans[i]); }
  6442. }
  6443. return !out ? spans : out.length ? out : null
  6444. }
  6445. // Retrieve and filter the old marked spans stored in a change event.
  6446. function getOldSpans(doc, change) {
  6447. var found = change["spans_" + doc.id];
  6448. if (!found) { return null }
  6449. var nw = [];
  6450. for (var i = 0; i < change.text.length; ++i)
  6451. { nw.push(removeClearedSpans(found[i])); }
  6452. return nw
  6453. }
  6454. // Used for un/re-doing changes from the history. Combines the
  6455. // result of computing the existing spans with the set of spans that
  6456. // existed in the history (so that deleting around a span and then
  6457. // undoing brings back the span).
  6458. function mergeOldSpans(doc, change) {
  6459. var old = getOldSpans(doc, change);
  6460. var stretched = stretchSpansOverChange(doc, change);
  6461. if (!old) { return stretched }
  6462. if (!stretched) { return old }
  6463. for (var i = 0; i < old.length; ++i) {
  6464. var oldCur = old[i], stretchCur = stretched[i];
  6465. if (oldCur && stretchCur) {
  6466. spans: for (var j = 0; j < stretchCur.length; ++j) {
  6467. var span = stretchCur[j];
  6468. for (var k = 0; k < oldCur.length; ++k)
  6469. { if (oldCur[k].marker == span.marker) { continue spans } }
  6470. oldCur.push(span);
  6471. }
  6472. } else if (stretchCur) {
  6473. old[i] = stretchCur;
  6474. }
  6475. }
  6476. return old
  6477. }
  6478. // Used both to provide a JSON-safe object in .getHistory, and, when
  6479. // detaching a document, to split the history in two
  6480. function copyHistoryArray(events, newGroup, instantiateSel) {
  6481. var copy = [];
  6482. for (var i = 0; i < events.length; ++i) {
  6483. var event = events[i];
  6484. if (event.ranges) {
  6485. copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event);
  6486. continue
  6487. }
  6488. var changes = event.changes, newChanges = [];
  6489. copy.push({changes: newChanges});
  6490. for (var j = 0; j < changes.length; ++j) {
  6491. var change = changes[j], m = (void 0);
  6492. newChanges.push({from: change.from, to: change.to, text: change.text});
  6493. if (newGroup) { for (var prop in change) { if (m = prop.match(/^spans_(\d+)$/)) {
  6494. if (indexOf(newGroup, Number(m[1])) > -1) {
  6495. lst(newChanges)[prop] = change[prop];
  6496. delete change[prop];
  6497. }
  6498. } } }
  6499. }
  6500. }
  6501. return copy
  6502. }
  6503. // The 'scroll' parameter given to many of these indicated whether
  6504. // the new cursor position should be scrolled into view after
  6505. // modifying the selection.
  6506. // If shift is held or the extend flag is set, extends a range to
  6507. // include a given position (and optionally a second position).
  6508. // Otherwise, simply returns the range between the given positions.
  6509. // Used for cursor motion and such.
  6510. function extendRange(range, head, other, extend) {
  6511. if (extend) {
  6512. var anchor = range.anchor;
  6513. if (other) {
  6514. var posBefore = cmp(head, anchor) < 0;
  6515. if (posBefore != (cmp(other, anchor) < 0)) {
  6516. anchor = head;
  6517. head = other;
  6518. } else if (posBefore != (cmp(head, other) < 0)) {
  6519. head = other;
  6520. }
  6521. }
  6522. return new Range(anchor, head)
  6523. } else {
  6524. return new Range(other || head, head)
  6525. }
  6526. }
  6527. // Extend the primary selection range, discard the rest.
  6528. function extendSelection(doc, head, other, options, extend) {
  6529. if (extend == null) { extend = doc.cm && (doc.cm.display.shift || doc.extend); }
  6530. setSelection(doc, new Selection([extendRange(doc.sel.primary(), head, other, extend)], 0), options);
  6531. }
  6532. // Extend all selections (pos is an array of selections with length
  6533. // equal the number of selections)
  6534. function extendSelections(doc, heads, options) {
  6535. var out = [];
  6536. var extend = doc.cm && (doc.cm.display.shift || doc.extend);
  6537. for (var i = 0; i < doc.sel.ranges.length; i++)
  6538. { out[i] = extendRange(doc.sel.ranges[i], heads[i], null, extend); }
  6539. var newSel = normalizeSelection(out, doc.sel.primIndex);
  6540. setSelection(doc, newSel, options);
  6541. }
  6542. // Updates a single range in the selection.
  6543. function replaceOneSelection(doc, i, range, options) {
  6544. var ranges = doc.sel.ranges.slice(0);
  6545. ranges[i] = range;
  6546. setSelection(doc, normalizeSelection(ranges, doc.sel.primIndex), options);
  6547. }
  6548. // Reset the selection to a single range.
  6549. function setSimpleSelection(doc, anchor, head, options) {
  6550. setSelection(doc, simpleSelection(anchor, head), options);
  6551. }
  6552. // Give beforeSelectionChange handlers a change to influence a
  6553. // selection update.
  6554. function filterSelectionChange(doc, sel, options) {
  6555. var obj = {
  6556. ranges: sel.ranges,
  6557. update: function(ranges) {
  6558. var this$1 = this;
  6559. this.ranges = [];
  6560. for (var i = 0; i < ranges.length; i++)
  6561. { this$1.ranges[i] = new Range(clipPos(doc, ranges[i].anchor),
  6562. clipPos(doc, ranges[i].head)); }
  6563. },
  6564. origin: options && options.origin
  6565. };
  6566. signal(doc, "beforeSelectionChange", doc, obj);
  6567. if (doc.cm) { signal(doc.cm, "beforeSelectionChange", doc.cm, obj); }
  6568. if (obj.ranges != sel.ranges) { return normalizeSelection(obj.ranges, obj.ranges.length - 1) }
  6569. else { return sel }
  6570. }
  6571. function setSelectionReplaceHistory(doc, sel, options) {
  6572. var done = doc.history.done, last = lst(done);
  6573. if (last && last.ranges) {
  6574. done[done.length - 1] = sel;
  6575. setSelectionNoUndo(doc, sel, options);
  6576. } else {
  6577. setSelection(doc, sel, options);
  6578. }
  6579. }
  6580. // Set a new selection.
  6581. function setSelection(doc, sel, options) {
  6582. setSelectionNoUndo(doc, sel, options);
  6583. addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options);
  6584. }
  6585. function setSelectionNoUndo(doc, sel, options) {
  6586. if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange"))
  6587. { sel = filterSelectionChange(doc, sel, options); }
  6588. var bias = options && options.bias ||
  6589. (cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1);
  6590. setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true));
  6591. if (!(options && options.scroll === false) && doc.cm)
  6592. { ensureCursorVisible(doc.cm); }
  6593. }
  6594. function setSelectionInner(doc, sel) {
  6595. if (sel.equals(doc.sel)) { return }
  6596. doc.sel = sel;
  6597. if (doc.cm) {
  6598. doc.cm.curOp.updateInput = doc.cm.curOp.selectionChanged = true;
  6599. signalCursorActivity(doc.cm);
  6600. }
  6601. signalLater(doc, "cursorActivity", doc);
  6602. }
  6603. // Verify that the selection does not partially select any atomic
  6604. // marked ranges.
  6605. function reCheckSelection(doc) {
  6606. setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false));
  6607. }
  6608. // Return a selection that does not partially select any atomic
  6609. // ranges.
  6610. function skipAtomicInSelection(doc, sel, bias, mayClear) {
  6611. var out;
  6612. for (var i = 0; i < sel.ranges.length; i++) {
  6613. var range = sel.ranges[i];
  6614. var old = sel.ranges.length == doc.sel.ranges.length && doc.sel.ranges[i];
  6615. var newAnchor = skipAtomic(doc, range.anchor, old && old.anchor, bias, mayClear);
  6616. var newHead = skipAtomic(doc, range.head, old && old.head, bias, mayClear);
  6617. if (out || newAnchor != range.anchor || newHead != range.head) {
  6618. if (!out) { out = sel.ranges.slice(0, i); }
  6619. out[i] = new Range(newAnchor, newHead);
  6620. }
  6621. }
  6622. return out ? normalizeSelection(out, sel.primIndex) : sel
  6623. }
  6624. function skipAtomicInner(doc, pos, oldPos, dir, mayClear) {
  6625. var line = getLine(doc, pos.line);
  6626. if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) {
  6627. var sp = line.markedSpans[i], m = sp.marker;
  6628. if ((sp.from == null || (m.inclusiveLeft ? sp.from <= pos.ch : sp.from < pos.ch)) &&
  6629. (sp.to == null || (m.inclusiveRight ? sp.to >= pos.ch : sp.to > pos.ch))) {
  6630. if (mayClear) {
  6631. signal(m, "beforeCursorEnter");
  6632. if (m.explicitlyCleared) {
  6633. if (!line.markedSpans) { break }
  6634. else {--i; continue}
  6635. }
  6636. }
  6637. if (!m.atomic) { continue }
  6638. if (oldPos) {
  6639. var near = m.find(dir < 0 ? 1 : -1), diff = (void 0);
  6640. if (dir < 0 ? m.inclusiveRight : m.inclusiveLeft)
  6641. { near = movePos(doc, near, -dir, near && near.line == pos.line ? line : null); }
  6642. if (near && near.line == pos.line && (diff = cmp(near, oldPos)) && (dir < 0 ? diff < 0 : diff > 0))
  6643. { return skipAtomicInner(doc, near, pos, dir, mayClear) }
  6644. }
  6645. var far = m.find(dir < 0 ? -1 : 1);
  6646. if (dir < 0 ? m.inclusiveLeft : m.inclusiveRight)
  6647. { far = movePos(doc, far, dir, far.line == pos.line ? line : null); }
  6648. return far ? skipAtomicInner(doc, far, pos, dir, mayClear) : null
  6649. }
  6650. } }
  6651. return pos
  6652. }
  6653. // Ensure a given position is not inside an atomic range.
  6654. function skipAtomic(doc, pos, oldPos, bias, mayClear) {
  6655. var dir = bias || 1;
  6656. var found = skipAtomicInner(doc, pos, oldPos, dir, mayClear) ||
  6657. (!mayClear && skipAtomicInner(doc, pos, oldPos, dir, true)) ||
  6658. skipAtomicInner(doc, pos, oldPos, -dir, mayClear) ||
  6659. (!mayClear && skipAtomicInner(doc, pos, oldPos, -dir, true));
  6660. if (!found) {
  6661. doc.cantEdit = true;
  6662. return Pos(doc.first, 0)
  6663. }
  6664. return found
  6665. }
  6666. function movePos(doc, pos, dir, line) {
  6667. if (dir < 0 && pos.ch == 0) {
  6668. if (pos.line > doc.first) { return clipPos(doc, Pos(pos.line - 1)) }
  6669. else { return null }
  6670. } else if (dir > 0 && pos.ch == (line || getLine(doc, pos.line)).text.length) {
  6671. if (pos.line < doc.first + doc.size - 1) { return Pos(pos.line + 1, 0) }
  6672. else { return null }
  6673. } else {
  6674. return new Pos(pos.line, pos.ch + dir)
  6675. }
  6676. }
  6677. function selectAll(cm) {
  6678. cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll);
  6679. }
  6680. // UPDATING
  6681. // Allow "beforeChange" event handlers to influence a change
  6682. function filterChange(doc, change, update) {
  6683. var obj = {
  6684. canceled: false,
  6685. from: change.from,
  6686. to: change.to,
  6687. text: change.text,
  6688. origin: change.origin,
  6689. cancel: function () { return obj.canceled = true; }
  6690. };
  6691. if (update) { obj.update = function (from, to, text, origin) {
  6692. if (from) { obj.from = clipPos(doc, from); }
  6693. if (to) { obj.to = clipPos(doc, to); }
  6694. if (text) { obj.text = text; }
  6695. if (origin !== undefined) { obj.origin = origin; }
  6696. }; }
  6697. signal(doc, "beforeChange", doc, obj);
  6698. if (doc.cm) { signal(doc.cm, "beforeChange", doc.cm, obj); }
  6699. if (obj.canceled) { return null }
  6700. return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin}
  6701. }
  6702. // Apply a change to a document, and add it to the document's
  6703. // history, and propagating it to all linked documents.
  6704. function makeChange(doc, change, ignoreReadOnly) {
  6705. if (doc.cm) {
  6706. if (!doc.cm.curOp) { return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly) }
  6707. if (doc.cm.state.suppressEdits) { return }
  6708. }
  6709. if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) {
  6710. change = filterChange(doc, change, true);
  6711. if (!change) { return }
  6712. }
  6713. // Possibly split or suppress the update based on the presence
  6714. // of read-only spans in its range.
  6715. var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to);
  6716. if (split) {
  6717. for (var i = split.length - 1; i >= 0; --i)
  6718. { makeChangeInner(doc, {from: split[i].from, to: split[i].to, text: i ? [""] : change.text, origin: change.origin}); }
  6719. } else {
  6720. makeChangeInner(doc, change);
  6721. }
  6722. }
  6723. function makeChangeInner(doc, change) {
  6724. if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) { return }
  6725. var selAfter = computeSelAfterChange(doc, change);
  6726. addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN);
  6727. makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change));
  6728. var rebased = [];
  6729. linkedDocs(doc, function (doc, sharedHist) {
  6730. if (!sharedHist && indexOf(rebased, doc.history) == -1) {
  6731. rebaseHist(doc.history, change);
  6732. rebased.push(doc.history);
  6733. }
  6734. makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change));
  6735. });
  6736. }
  6737. // Revert a change stored in a document's history.
  6738. function makeChangeFromHistory(doc, type, allowSelectionOnly) {
  6739. if (doc.cm && doc.cm.state.suppressEdits && !allowSelectionOnly) { return }
  6740. var hist = doc.history, event, selAfter = doc.sel;
  6741. var source = type == "undo" ? hist.done : hist.undone, dest = type == "undo" ? hist.undone : hist.done;
  6742. // Verify that there is a useable event (so that ctrl-z won't
  6743. // needlessly clear selection events)
  6744. var i = 0;
  6745. for (; i < source.length; i++) {
  6746. event = source[i];
  6747. if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges)
  6748. { break }
  6749. }
  6750. if (i == source.length) { return }
  6751. hist.lastOrigin = hist.lastSelOrigin = null;
  6752. for (;;) {
  6753. event = source.pop();
  6754. if (event.ranges) {
  6755. pushSelectionToHistory(event, dest);
  6756. if (allowSelectionOnly && !event.equals(doc.sel)) {
  6757. setSelection(doc, event, {clearRedo: false});
  6758. return
  6759. }
  6760. selAfter = event;
  6761. }
  6762. else { break }
  6763. }
  6764. // Build up a reverse change object to add to the opposite history
  6765. // stack (redo when undoing, and vice versa).
  6766. var antiChanges = [];
  6767. pushSelectionToHistory(selAfter, dest);
  6768. dest.push({changes: antiChanges, generation: hist.generation});
  6769. hist.generation = event.generation || ++hist.maxGeneration;
  6770. var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange");
  6771. var loop = function ( i ) {
  6772. var change = event.changes[i];
  6773. change.origin = type;
  6774. if (filter && !filterChange(doc, change, false)) {
  6775. source.length = 0;
  6776. return {}
  6777. }
  6778. antiChanges.push(historyChangeFromChange(doc, change));
  6779. var after = i ? computeSelAfterChange(doc, change) : lst(source);
  6780. makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change));
  6781. if (!i && doc.cm) { doc.cm.scrollIntoView({from: change.from, to: changeEnd(change)}); }
  6782. var rebased = [];
  6783. // Propagate to the linked documents
  6784. linkedDocs(doc, function (doc, sharedHist) {
  6785. if (!sharedHist && indexOf(rebased, doc.history) == -1) {
  6786. rebaseHist(doc.history, change);
  6787. rebased.push(doc.history);
  6788. }
  6789. makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change));
  6790. });
  6791. };
  6792. for (var i$1 = event.changes.length - 1; i$1 >= 0; --i$1) {
  6793. var returned = loop( i$1 );
  6794. if ( returned ) return returned.v;
  6795. }
  6796. }
  6797. // Sub-views need their line numbers shifted when text is added
  6798. // above or below them in the parent document.
  6799. function shiftDoc(doc, distance) {
  6800. if (distance == 0) { return }
  6801. doc.first += distance;
  6802. doc.sel = new Selection(map(doc.sel.ranges, function (range) { return new Range(
  6803. Pos(range.anchor.line + distance, range.anchor.ch),
  6804. Pos(range.head.line + distance, range.head.ch)
  6805. ); }), doc.sel.primIndex);
  6806. if (doc.cm) {
  6807. regChange(doc.cm, doc.first, doc.first - distance, distance);
  6808. for (var d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++)
  6809. { regLineChange(doc.cm, l, "gutter"); }
  6810. }
  6811. }
  6812. // More lower-level change function, handling only a single document
  6813. // (not linked ones).
  6814. function makeChangeSingleDoc(doc, change, selAfter, spans) {
  6815. if (doc.cm && !doc.cm.curOp)
  6816. { return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans) }
  6817. if (change.to.line < doc.first) {
  6818. shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line));
  6819. return
  6820. }
  6821. if (change.from.line > doc.lastLine()) { return }
  6822. // Clip the change to the size of this doc
  6823. if (change.from.line < doc.first) {
  6824. var shift = change.text.length - 1 - (doc.first - change.from.line);
  6825. shiftDoc(doc, shift);
  6826. change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch),
  6827. text: [lst(change.text)], origin: change.origin};
  6828. }
  6829. var last = doc.lastLine();
  6830. if (change.to.line > last) {
  6831. change = {from: change.from, to: Pos(last, getLine(doc, last).text.length),
  6832. text: [change.text[0]], origin: change.origin};
  6833. }
  6834. change.removed = getBetween(doc, change.from, change.to);
  6835. if (!selAfter) { selAfter = computeSelAfterChange(doc, change); }
  6836. if (doc.cm) { makeChangeSingleDocInEditor(doc.cm, change, spans); }
  6837. else { updateDoc(doc, change, spans); }
  6838. setSelectionNoUndo(doc, selAfter, sel_dontScroll);
  6839. }
  6840. // Handle the interaction of a change to a document with the editor
  6841. // that this document is part of.
  6842. function makeChangeSingleDocInEditor(cm, change, spans) {
  6843. var doc = cm.doc, display = cm.display, from = change.from, to = change.to;
  6844. var recomputeMaxLength = false, checkWidthStart = from.line;
  6845. if (!cm.options.lineWrapping) {
  6846. checkWidthStart = lineNo(visualLine(getLine(doc, from.line)));
  6847. doc.iter(checkWidthStart, to.line + 1, function (line) {
  6848. if (line == display.maxLine) {
  6849. recomputeMaxLength = true;
  6850. return true
  6851. }
  6852. });
  6853. }
  6854. if (doc.sel.contains(change.from, change.to) > -1)
  6855. { signalCursorActivity(cm); }
  6856. updateDoc(doc, change, spans, estimateHeight(cm));
  6857. if (!cm.options.lineWrapping) {
  6858. doc.iter(checkWidthStart, from.line + change.text.length, function (line) {
  6859. var len = lineLength(line);
  6860. if (len > display.maxLineLength) {
  6861. display.maxLine = line;
  6862. display.maxLineLength = len;
  6863. display.maxLineChanged = true;
  6864. recomputeMaxLength = false;
  6865. }
  6866. });
  6867. if (recomputeMaxLength) { cm.curOp.updateMaxLine = true; }
  6868. }
  6869. retreatFrontier(doc, from.line);
  6870. startWorker(cm, 400);
  6871. var lendiff = change.text.length - (to.line - from.line) - 1;
  6872. // Remember that these lines changed, for updating the display
  6873. if (change.full)
  6874. { regChange(cm); }
  6875. else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change))
  6876. { regLineChange(cm, from.line, "text"); }
  6877. else
  6878. { regChange(cm, from.line, to.line + 1, lendiff); }
  6879. var changesHandler = hasHandler(cm, "changes"), changeHandler = hasHandler(cm, "change");
  6880. if (changeHandler || changesHandler) {
  6881. var obj = {
  6882. from: from, to: to,
  6883. text: change.text,
  6884. removed: change.removed,
  6885. origin: change.origin
  6886. };
  6887. if (changeHandler) { signalLater(cm, "change", cm, obj); }
  6888. if (changesHandler) { (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj); }
  6889. }
  6890. cm.display.selForContextMenu = null;
  6891. }
  6892. function replaceRange(doc, code, from, to, origin) {
  6893. if (!to) { to = from; }
  6894. if (cmp(to, from) < 0) { var assign;
  6895. (assign = [to, from], from = assign[0], to = assign[1], assign); }
  6896. if (typeof code == "string") { code = doc.splitLines(code); }
  6897. makeChange(doc, {from: from, to: to, text: code, origin: origin});
  6898. }
  6899. // Rebasing/resetting history to deal with externally-sourced changes
  6900. function rebaseHistSelSingle(pos, from, to, diff) {
  6901. if (to < pos.line) {
  6902. pos.line += diff;
  6903. } else if (from < pos.line) {
  6904. pos.line = from;
  6905. pos.ch = 0;
  6906. }
  6907. }
  6908. // Tries to rebase an array of history events given a change in the
  6909. // document. If the change touches the same lines as the event, the
  6910. // event, and everything 'behind' it, is discarded. If the change is
  6911. // before the event, the event's positions are updated. Uses a
  6912. // copy-on-write scheme for the positions, to avoid having to
  6913. // reallocate them all on every rebase, but also avoid problems with
  6914. // shared position objects being unsafely updated.
  6915. function rebaseHistArray(array, from, to, diff) {
  6916. for (var i = 0; i < array.length; ++i) {
  6917. var sub = array[i], ok = true;
  6918. if (sub.ranges) {
  6919. if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true; }
  6920. for (var j = 0; j < sub.ranges.length; j++) {
  6921. rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff);
  6922. rebaseHistSelSingle(sub.ranges[j].head, from, to, diff);
  6923. }
  6924. continue
  6925. }
  6926. for (var j$1 = 0; j$1 < sub.changes.length; ++j$1) {
  6927. var cur = sub.changes[j$1];
  6928. if (to < cur.from.line) {
  6929. cur.from = Pos(cur.from.line + diff, cur.from.ch);
  6930. cur.to = Pos(cur.to.line + diff, cur.to.ch);
  6931. } else if (from <= cur.to.line) {
  6932. ok = false;
  6933. break
  6934. }
  6935. }
  6936. if (!ok) {
  6937. array.splice(0, i + 1);
  6938. i = 0;
  6939. }
  6940. }
  6941. }
  6942. function rebaseHist(hist, change) {
  6943. var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1;
  6944. rebaseHistArray(hist.done, from, to, diff);
  6945. rebaseHistArray(hist.undone, from, to, diff);
  6946. }
  6947. // Utility for applying a change to a line by handle or number,
  6948. // returning the number and optionally registering the line as
  6949. // changed.
  6950. function changeLine(doc, handle, changeType, op) {
  6951. var no = handle, line = handle;
  6952. if (typeof handle == "number") { line = getLine(doc, clipLine(doc, handle)); }
  6953. else { no = lineNo(handle); }
  6954. if (no == null) { return null }
  6955. if (op(line, no) && doc.cm) { regLineChange(doc.cm, no, changeType); }
  6956. return line
  6957. }
  6958. // The document is represented as a BTree consisting of leaves, with
  6959. // chunk of lines in them, and branches, with up to ten leaves or
  6960. // other branch nodes below them. The top node is always a branch
  6961. // node, and is the document object itself (meaning it has
  6962. // additional methods and properties).
  6963. //
  6964. // All nodes have parent links. The tree is used both to go from
  6965. // line numbers to line objects, and to go from objects to numbers.
  6966. // It also indexes by height, and is used to convert between height
  6967. // and line object, and to find the total height of the document.
  6968. //
  6969. // See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html
  6970. function LeafChunk(lines) {
  6971. var this$1 = this;
  6972. this.lines = lines;
  6973. this.parent = null;
  6974. var height = 0;
  6975. for (var i = 0; i < lines.length; ++i) {
  6976. lines[i].parent = this$1;
  6977. height += lines[i].height;
  6978. }
  6979. this.height = height;
  6980. }
  6981. LeafChunk.prototype = {
  6982. chunkSize: function chunkSize() { return this.lines.length },
  6983. // Remove the n lines at offset 'at'.
  6984. removeInner: function removeInner(at, n) {
  6985. var this$1 = this;
  6986. for (var i = at, e = at + n; i < e; ++i) {
  6987. var line = this$1.lines[i];
  6988. this$1.height -= line.height;
  6989. cleanUpLine(line);
  6990. signalLater(line, "delete");
  6991. }
  6992. this.lines.splice(at, n);
  6993. },
  6994. // Helper used to collapse a small branch into a single leaf.
  6995. collapse: function collapse(lines) {
  6996. lines.push.apply(lines, this.lines);
  6997. },
  6998. // Insert the given array of lines at offset 'at', count them as
  6999. // having the given height.
  7000. insertInner: function insertInner(at, lines, height) {
  7001. var this$1 = this;
  7002. this.height += height;
  7003. this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at));
  7004. for (var i = 0; i < lines.length; ++i) { lines[i].parent = this$1; }
  7005. },
  7006. // Used to iterate over a part of the tree.
  7007. iterN: function iterN(at, n, op) {
  7008. var this$1 = this;
  7009. for (var e = at + n; at < e; ++at)
  7010. { if (op(this$1.lines[at])) { return true } }
  7011. }
  7012. };
  7013. function BranchChunk(children) {
  7014. var this$1 = this;
  7015. this.children = children;
  7016. var size = 0, height = 0;
  7017. for (var i = 0; i < children.length; ++i) {
  7018. var ch = children[i];
  7019. size += ch.chunkSize(); height += ch.height;
  7020. ch.parent = this$1;
  7021. }
  7022. this.size = size;
  7023. this.height = height;
  7024. this.parent = null;
  7025. }
  7026. BranchChunk.prototype = {
  7027. chunkSize: function chunkSize() { return this.size },
  7028. removeInner: function removeInner(at, n) {
  7029. var this$1 = this;
  7030. this.size -= n;
  7031. for (var i = 0; i < this.children.length; ++i) {
  7032. var child = this$1.children[i], sz = child.chunkSize();
  7033. if (at < sz) {
  7034. var rm = Math.min(n, sz - at), oldHeight = child.height;
  7035. child.removeInner(at, rm);
  7036. this$1.height -= oldHeight - child.height;
  7037. if (sz == rm) { this$1.children.splice(i--, 1); child.parent = null; }
  7038. if ((n -= rm) == 0) { break }
  7039. at = 0;
  7040. } else { at -= sz; }
  7041. }
  7042. // If the result is smaller than 25 lines, ensure that it is a
  7043. // single leaf node.
  7044. if (this.size - n < 25 &&
  7045. (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) {
  7046. var lines = [];
  7047. this.collapse(lines);
  7048. this.children = [new LeafChunk(lines)];
  7049. this.children[0].parent = this;
  7050. }
  7051. },
  7052. collapse: function collapse(lines) {
  7053. var this$1 = this;
  7054. for (var i = 0; i < this.children.length; ++i) { this$1.children[i].collapse(lines); }
  7055. },
  7056. insertInner: function insertInner(at, lines, height) {
  7057. var this$1 = this;
  7058. this.size += lines.length;
  7059. this.height += height;
  7060. for (var i = 0; i < this.children.length; ++i) {
  7061. var child = this$1.children[i], sz = child.chunkSize();
  7062. if (at <= sz) {
  7063. child.insertInner(at, lines, height);
  7064. if (child.lines && child.lines.length > 50) {
  7065. // To avoid memory thrashing when child.lines is huge (e.g. first view of a large file), it's never spliced.
  7066. // Instead, small slices are taken. They're taken in order because sequential memory accesses are fastest.
  7067. var remaining = child.lines.length % 25 + 25;
  7068. for (var pos = remaining; pos < child.lines.length;) {
  7069. var leaf = new LeafChunk(child.lines.slice(pos, pos += 25));
  7070. child.height -= leaf.height;
  7071. this$1.children.splice(++i, 0, leaf);
  7072. leaf.parent = this$1;
  7073. }
  7074. child.lines = child.lines.slice(0, remaining);
  7075. this$1.maybeSpill();
  7076. }
  7077. break
  7078. }
  7079. at -= sz;
  7080. }
  7081. },
  7082. // When a node has grown, check whether it should be split.
  7083. maybeSpill: function maybeSpill() {
  7084. if (this.children.length <= 10) { return }
  7085. var me = this;
  7086. do {
  7087. var spilled = me.children.splice(me.children.length - 5, 5);
  7088. var sibling = new BranchChunk(spilled);
  7089. if (!me.parent) { // Become the parent node
  7090. var copy = new BranchChunk(me.children);
  7091. copy.parent = me;
  7092. me.children = [copy, sibling];
  7093. me = copy;
  7094. } else {
  7095. me.size -= sibling.size;
  7096. me.height -= sibling.height;
  7097. var myIndex = indexOf(me.parent.children, me);
  7098. me.parent.children.splice(myIndex + 1, 0, sibling);
  7099. }
  7100. sibling.parent = me.parent;
  7101. } while (me.children.length > 10)
  7102. me.parent.maybeSpill();
  7103. },
  7104. iterN: function iterN(at, n, op) {
  7105. var this$1 = this;
  7106. for (var i = 0; i < this.children.length; ++i) {
  7107. var child = this$1.children[i], sz = child.chunkSize();
  7108. if (at < sz) {
  7109. var used = Math.min(n, sz - at);
  7110. if (child.iterN(at, used, op)) { return true }
  7111. if ((n -= used) == 0) { break }
  7112. at = 0;
  7113. } else { at -= sz; }
  7114. }
  7115. }
  7116. };
  7117. // Line widgets are block elements displayed above or below a line.
  7118. var LineWidget = function(doc, node, options) {
  7119. var this$1 = this;
  7120. if (options) { for (var opt in options) { if (options.hasOwnProperty(opt))
  7121. { this$1[opt] = options[opt]; } } }
  7122. this.doc = doc;
  7123. this.node = node;
  7124. };
  7125. LineWidget.prototype.clear = function () {
  7126. var this$1 = this;
  7127. var cm = this.doc.cm, ws = this.line.widgets, line = this.line, no = lineNo(line);
  7128. if (no == null || !ws) { return }
  7129. for (var i = 0; i < ws.length; ++i) { if (ws[i] == this$1) { ws.splice(i--, 1); } }
  7130. if (!ws.length) { line.widgets = null; }
  7131. var height = widgetHeight(this);
  7132. updateLineHeight(line, Math.max(0, line.height - height));
  7133. if (cm) {
  7134. runInOp(cm, function () {
  7135. adjustScrollWhenAboveVisible(cm, line, -height);
  7136. regLineChange(cm, no, "widget");
  7137. });
  7138. signalLater(cm, "lineWidgetCleared", cm, this, no);
  7139. }
  7140. };
  7141. LineWidget.prototype.changed = function () {
  7142. var this$1 = this;
  7143. var oldH = this.height, cm = this.doc.cm, line = this.line;
  7144. this.height = null;
  7145. var diff = widgetHeight(this) - oldH;
  7146. if (!diff) { return }
  7147. updateLineHeight(line, line.height + diff);
  7148. if (cm) {
  7149. runInOp(cm, function () {
  7150. cm.curOp.forceUpdate = true;
  7151. adjustScrollWhenAboveVisible(cm, line, diff);
  7152. signalLater(cm, "lineWidgetChanged", cm, this$1, lineNo(line));
  7153. });
  7154. }
  7155. };
  7156. eventMixin(LineWidget);
  7157. function adjustScrollWhenAboveVisible(cm, line, diff) {
  7158. if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop))
  7159. { addToScrollTop(cm, diff); }
  7160. }
  7161. function addLineWidget(doc, handle, node, options) {
  7162. var widget = new LineWidget(doc, node, options);
  7163. var cm = doc.cm;
  7164. if (cm && widget.noHScroll) { cm.display.alignWidgets = true; }
  7165. changeLine(doc, handle, "widget", function (line) {
  7166. var widgets = line.widgets || (line.widgets = []);
  7167. if (widget.insertAt == null) { widgets.push(widget); }
  7168. else { widgets.splice(Math.min(widgets.length - 1, Math.max(0, widget.insertAt)), 0, widget); }
  7169. widget.line = line;
  7170. if (cm && !lineIsHidden(doc, line)) {
  7171. var aboveVisible = heightAtLine(line) < doc.scrollTop;
  7172. updateLineHeight(line, line.height + widgetHeight(widget));
  7173. if (aboveVisible) { addToScrollTop(cm, widget.height); }
  7174. cm.curOp.forceUpdate = true;
  7175. }
  7176. return true
  7177. });
  7178. signalLater(cm, "lineWidgetAdded", cm, widget, typeof handle == "number" ? handle : lineNo(handle));
  7179. return widget
  7180. }
  7181. // TEXTMARKERS
  7182. // Created with markText and setBookmark methods. A TextMarker is a
  7183. // handle that can be used to clear or find a marked position in the
  7184. // document. Line objects hold arrays (markedSpans) containing
  7185. // {from, to, marker} object pointing to such marker objects, and
  7186. // indicating that such a marker is present on that line. Multiple
  7187. // lines may point to the same marker when it spans across lines.
  7188. // The spans will have null for their from/to properties when the
  7189. // marker continues beyond the start/end of the line. Markers have
  7190. // links back to the lines they currently touch.
  7191. // Collapsed markers have unique ids, in order to be able to order
  7192. // them, which is needed for uniquely determining an outer marker
  7193. // when they overlap (they may nest, but not partially overlap).
  7194. var nextMarkerId = 0;
  7195. var TextMarker = function(doc, type) {
  7196. this.lines = [];
  7197. this.type = type;
  7198. this.doc = doc;
  7199. this.id = ++nextMarkerId;
  7200. };
  7201. // Clear the marker.
  7202. TextMarker.prototype.clear = function () {
  7203. var this$1 = this;
  7204. if (this.explicitlyCleared) { return }
  7205. var cm = this.doc.cm, withOp = cm && !cm.curOp;
  7206. if (withOp) { startOperation(cm); }
  7207. if (hasHandler(this, "clear")) {
  7208. var found = this.find();
  7209. if (found) { signalLater(this, "clear", found.from, found.to); }
  7210. }
  7211. var min = null, max = null;
  7212. for (var i = 0; i < this.lines.length; ++i) {
  7213. var line = this$1.lines[i];
  7214. var span = getMarkedSpanFor(line.markedSpans, this$1);
  7215. if (cm && !this$1.collapsed) { regLineChange(cm, lineNo(line), "text"); }
  7216. else if (cm) {
  7217. if (span.to != null) { max = lineNo(line); }
  7218. if (span.from != null) { min = lineNo(line); }
  7219. }
  7220. line.markedSpans = removeMarkedSpan(line.markedSpans, span);
  7221. if (span.from == null && this$1.collapsed && !lineIsHidden(this$1.doc, line) && cm)
  7222. { updateLineHeight(line, textHeight(cm.display)); }
  7223. }
  7224. if (cm && this.collapsed && !cm.options.lineWrapping) { for (var i$1 = 0; i$1 < this.lines.length; ++i$1) {
  7225. var visual = visualLine(this$1.lines[i$1]), len = lineLength(visual);
  7226. if (len > cm.display.maxLineLength) {
  7227. cm.display.maxLine = visual;
  7228. cm.display.maxLineLength = len;
  7229. cm.display.maxLineChanged = true;
  7230. }
  7231. } }
  7232. if (min != null && cm && this.collapsed) { regChange(cm, min, max + 1); }
  7233. this.lines.length = 0;
  7234. this.explicitlyCleared = true;
  7235. if (this.atomic && this.doc.cantEdit) {
  7236. this.doc.cantEdit = false;
  7237. if (cm) { reCheckSelection(cm.doc); }
  7238. }
  7239. if (cm) { signalLater(cm, "markerCleared", cm, this, min, max); }
  7240. if (withOp) { endOperation(cm); }
  7241. if (this.parent) { this.parent.clear(); }
  7242. };
  7243. // Find the position of the marker in the document. Returns a {from,
  7244. // to} object by default. Side can be passed to get a specific side
  7245. // -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the
  7246. // Pos objects returned contain a line object, rather than a line
  7247. // number (used to prevent looking up the same line twice).
  7248. TextMarker.prototype.find = function (side, lineObj) {
  7249. var this$1 = this;
  7250. if (side == null && this.type == "bookmark") { side = 1; }
  7251. var from, to;
  7252. for (var i = 0; i < this.lines.length; ++i) {
  7253. var line = this$1.lines[i];
  7254. var span = getMarkedSpanFor(line.markedSpans, this$1);
  7255. if (span.from != null) {
  7256. from = Pos(lineObj ? line : lineNo(line), span.from);
  7257. if (side == -1) { return from }
  7258. }
  7259. if (span.to != null) {
  7260. to = Pos(lineObj ? line : lineNo(line), span.to);
  7261. if (side == 1) { return to }
  7262. }
  7263. }
  7264. return from && {from: from, to: to}
  7265. };
  7266. // Signals that the marker's widget changed, and surrounding layout
  7267. // should be recomputed.
  7268. TextMarker.prototype.changed = function () {
  7269. var this$1 = this;
  7270. var pos = this.find(-1, true), widget = this, cm = this.doc.cm;
  7271. if (!pos || !cm) { return }
  7272. runInOp(cm, function () {
  7273. var line = pos.line, lineN = lineNo(pos.line);
  7274. var view = findViewForLine(cm, lineN);
  7275. if (view) {
  7276. clearLineMeasurementCacheFor(view);
  7277. cm.curOp.selectionChanged = cm.curOp.forceUpdate = true;
  7278. }
  7279. cm.curOp.updateMaxLine = true;
  7280. if (!lineIsHidden(widget.doc, line) && widget.height != null) {
  7281. var oldHeight = widget.height;
  7282. widget.height = null;
  7283. var dHeight = widgetHeight(widget) - oldHeight;
  7284. if (dHeight)
  7285. { updateLineHeight(line, line.height + dHeight); }
  7286. }
  7287. signalLater(cm, "markerChanged", cm, this$1);
  7288. });
  7289. };
  7290. TextMarker.prototype.attachLine = function (line) {
  7291. if (!this.lines.length && this.doc.cm) {
  7292. var op = this.doc.cm.curOp;
  7293. if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1)
  7294. { (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this); }
  7295. }
  7296. this.lines.push(line);
  7297. };
  7298. TextMarker.prototype.detachLine = function (line) {
  7299. this.lines.splice(indexOf(this.lines, line), 1);
  7300. if (!this.lines.length && this.doc.cm) {
  7301. var op = this.doc.cm.curOp;(op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this);
  7302. }
  7303. };
  7304. eventMixin(TextMarker);
  7305. // Create a marker, wire it up to the right lines, and
  7306. function markText(doc, from, to, options, type) {
  7307. // Shared markers (across linked documents) are handled separately
  7308. // (markTextShared will call out to this again, once per
  7309. // document).
  7310. if (options && options.shared) { return markTextShared(doc, from, to, options, type) }
  7311. // Ensure we are in an operation.
  7312. if (doc.cm && !doc.cm.curOp) { return operation(doc.cm, markText)(doc, from, to, options, type) }
  7313. var marker = new TextMarker(doc, type), diff = cmp(from, to);
  7314. if (options) { copyObj(options, marker, false); }
  7315. // Don't connect empty markers unless clearWhenEmpty is false
  7316. if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false)
  7317. { return marker }
  7318. if (marker.replacedWith) {
  7319. // Showing up as a widget implies collapsed (widget replaces text)
  7320. marker.collapsed = true;
  7321. marker.widgetNode = eltP("span", [marker.replacedWith], "CodeMirror-widget");
  7322. if (!options.handleMouseEvents) { marker.widgetNode.setAttribute("cm-ignore-events", "true"); }
  7323. if (options.insertLeft) { marker.widgetNode.insertLeft = true; }
  7324. }
  7325. if (marker.collapsed) {
  7326. if (conflictingCollapsedRange(doc, from.line, from, to, marker) ||
  7327. from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker))
  7328. { throw new Error("Inserting collapsed marker partially overlapping an existing one") }
  7329. seeCollapsedSpans();
  7330. }
  7331. if (marker.addToHistory)
  7332. { addChangeToHistory(doc, {from: from, to: to, origin: "markText"}, doc.sel, NaN); }
  7333. var curLine = from.line, cm = doc.cm, updateMaxLine;
  7334. doc.iter(curLine, to.line + 1, function (line) {
  7335. if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine)
  7336. { updateMaxLine = true; }
  7337. if (marker.collapsed && curLine != from.line) { updateLineHeight(line, 0); }
  7338. addMarkedSpan(line, new MarkedSpan(marker,
  7339. curLine == from.line ? from.ch : null,
  7340. curLine == to.line ? to.ch : null));
  7341. ++curLine;
  7342. });
  7343. // lineIsHidden depends on the presence of the spans, so needs a second pass
  7344. if (marker.collapsed) { doc.iter(from.line, to.line + 1, function (line) {
  7345. if (lineIsHidden(doc, line)) { updateLineHeight(line, 0); }
  7346. }); }
  7347. if (marker.clearOnEnter) { on(marker, "beforeCursorEnter", function () { return marker.clear(); }); }
  7348. if (marker.readOnly) {
  7349. seeReadOnlySpans();
  7350. if (doc.history.done.length || doc.history.undone.length)
  7351. { doc.clearHistory(); }
  7352. }
  7353. if (marker.collapsed) {
  7354. marker.id = ++nextMarkerId;
  7355. marker.atomic = true;
  7356. }
  7357. if (cm) {
  7358. // Sync editor state
  7359. if (updateMaxLine) { cm.curOp.updateMaxLine = true; }
  7360. if (marker.collapsed)
  7361. { regChange(cm, from.line, to.line + 1); }
  7362. else if (marker.className || marker.title || marker.startStyle || marker.endStyle || marker.css)
  7363. { for (var i = from.line; i <= to.line; i++) { regLineChange(cm, i, "text"); } }
  7364. if (marker.atomic) { reCheckSelection(cm.doc); }
  7365. signalLater(cm, "markerAdded", cm, marker);
  7366. }
  7367. return marker
  7368. }
  7369. // SHARED TEXTMARKERS
  7370. // A shared marker spans multiple linked documents. It is
  7371. // implemented as a meta-marker-object controlling multiple normal
  7372. // markers.
  7373. var SharedTextMarker = function(markers, primary) {
  7374. var this$1 = this;
  7375. this.markers = markers;
  7376. this.primary = primary;
  7377. for (var i = 0; i < markers.length; ++i)
  7378. { markers[i].parent = this$1; }
  7379. };
  7380. SharedTextMarker.prototype.clear = function () {
  7381. var this$1 = this;
  7382. if (this.explicitlyCleared) { return }
  7383. this.explicitlyCleared = true;
  7384. for (var i = 0; i < this.markers.length; ++i)
  7385. { this$1.markers[i].clear(); }
  7386. signalLater(this, "clear");
  7387. };
  7388. SharedTextMarker.prototype.find = function (side, lineObj) {
  7389. return this.primary.find(side, lineObj)
  7390. };
  7391. eventMixin(SharedTextMarker);
  7392. function markTextShared(doc, from, to, options, type) {
  7393. options = copyObj(options);
  7394. options.shared = false;
  7395. var markers = [markText(doc, from, to, options, type)], primary = markers[0];
  7396. var widget = options.widgetNode;
  7397. linkedDocs(doc, function (doc) {
  7398. if (widget) { options.widgetNode = widget.cloneNode(true); }
  7399. markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type));
  7400. for (var i = 0; i < doc.linked.length; ++i)
  7401. { if (doc.linked[i].isParent) { return } }
  7402. primary = lst(markers);
  7403. });
  7404. return new SharedTextMarker(markers, primary)
  7405. }
  7406. function findSharedMarkers(doc) {
  7407. return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())), function (m) { return m.parent; })
  7408. }
  7409. function copySharedMarkers(doc, markers) {
  7410. for (var i = 0; i < markers.length; i++) {
  7411. var marker = markers[i], pos = marker.find();
  7412. var mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to);
  7413. if (cmp(mFrom, mTo)) {
  7414. var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type);
  7415. marker.markers.push(subMark);
  7416. subMark.parent = marker;
  7417. }
  7418. }
  7419. }
  7420. function detachSharedMarkers(markers) {
  7421. var loop = function ( i ) {
  7422. var marker = markers[i], linked = [marker.primary.doc];
  7423. linkedDocs(marker.primary.doc, function (d) { return linked.push(d); });
  7424. for (var j = 0; j < marker.markers.length; j++) {
  7425. var subMarker = marker.markers[j];
  7426. if (indexOf(linked, subMarker.doc) == -1) {
  7427. subMarker.parent = null;
  7428. marker.markers.splice(j--, 1);
  7429. }
  7430. }
  7431. };
  7432. for (var i = 0; i < markers.length; i++) loop( i );
  7433. }
  7434. var nextDocId = 0;
  7435. var Doc = function(text, mode, firstLine, lineSep, direction) {
  7436. if (!(this instanceof Doc)) { return new Doc(text, mode, firstLine, lineSep, direction) }
  7437. if (firstLine == null) { firstLine = 0; }
  7438. BranchChunk.call(this, [new LeafChunk([new Line("", null)])]);
  7439. this.first = firstLine;
  7440. this.scrollTop = this.scrollLeft = 0;
  7441. this.cantEdit = false;
  7442. this.cleanGeneration = 1;
  7443. this.modeFrontier = this.highlightFrontier = firstLine;
  7444. var start = Pos(firstLine, 0);
  7445. this.sel = simpleSelection(start);
  7446. this.history = new History(null);
  7447. this.id = ++nextDocId;
  7448. this.modeOption = mode;
  7449. this.lineSep = lineSep;
  7450. this.direction = (direction == "rtl") ? "rtl" : "ltr";
  7451. this.extend = false;
  7452. if (typeof text == "string") { text = this.splitLines(text); }
  7453. updateDoc(this, {from: start, to: start, text: text});
  7454. setSelection(this, simpleSelection(start), sel_dontScroll);
  7455. };
  7456. Doc.prototype = createObj(BranchChunk.prototype, {
  7457. constructor: Doc,
  7458. // Iterate over the document. Supports two forms -- with only one
  7459. // argument, it calls that for each line in the document. With
  7460. // three, it iterates over the range given by the first two (with
  7461. // the second being non-inclusive).
  7462. iter: function(from, to, op) {
  7463. if (op) { this.iterN(from - this.first, to - from, op); }
  7464. else { this.iterN(this.first, this.first + this.size, from); }
  7465. },
  7466. // Non-public interface for adding and removing lines.
  7467. insert: function(at, lines) {
  7468. var height = 0;
  7469. for (var i = 0; i < lines.length; ++i) { height += lines[i].height; }
  7470. this.insertInner(at - this.first, lines, height);
  7471. },
  7472. remove: function(at, n) { this.removeInner(at - this.first, n); },
  7473. // From here, the methods are part of the public interface. Most
  7474. // are also available from CodeMirror (editor) instances.
  7475. getValue: function(lineSep) {
  7476. var lines = getLines(this, this.first, this.first + this.size);
  7477. if (lineSep === false) { return lines }
  7478. return lines.join(lineSep || this.lineSeparator())
  7479. },
  7480. setValue: docMethodOp(function(code) {
  7481. var top = Pos(this.first, 0), last = this.first + this.size - 1;
  7482. makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length),
  7483. text: this.splitLines(code), origin: "setValue", full: true}, true);
  7484. if (this.cm) { scrollToCoords(this.cm, 0, 0); }
  7485. setSelection(this, simpleSelection(top), sel_dontScroll);
  7486. }),
  7487. replaceRange: function(code, from, to, origin) {
  7488. from = clipPos(this, from);
  7489. to = to ? clipPos(this, to) : from;
  7490. replaceRange(this, code, from, to, origin);
  7491. },
  7492. getRange: function(from, to, lineSep) {
  7493. var lines = getBetween(this, clipPos(this, from), clipPos(this, to));
  7494. if (lineSep === false) { return lines }
  7495. return lines.join(lineSep || this.lineSeparator())
  7496. },
  7497. getLine: function(line) {var l = this.getLineHandle(line); return l && l.text},
  7498. getLineHandle: function(line) {if (isLine(this, line)) { return getLine(this, line) }},
  7499. getLineNumber: function(line) {return lineNo(line)},
  7500. getLineHandleVisualStart: function(line) {
  7501. if (typeof line == "number") { line = getLine(this, line); }
  7502. return visualLine(line)
  7503. },
  7504. lineCount: function() {return this.size},
  7505. firstLine: function() {return this.first},
  7506. lastLine: function() {return this.first + this.size - 1},
  7507. clipPos: function(pos) {return clipPos(this, pos)},
  7508. getCursor: function(start) {
  7509. var range$$1 = this.sel.primary(), pos;
  7510. if (start == null || start == "head") { pos = range$$1.head; }
  7511. else if (start == "anchor") { pos = range$$1.anchor; }
  7512. else if (start == "end" || start == "to" || start === false) { pos = range$$1.to(); }
  7513. else { pos = range$$1.from(); }
  7514. return pos
  7515. },
  7516. listSelections: function() { return this.sel.ranges },
  7517. somethingSelected: function() {return this.sel.somethingSelected()},
  7518. setCursor: docMethodOp(function(line, ch, options) {
  7519. setSimpleSelection(this, clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line), null, options);
  7520. }),
  7521. setSelection: docMethodOp(function(anchor, head, options) {
  7522. setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options);
  7523. }),
  7524. extendSelection: docMethodOp(function(head, other, options) {
  7525. extendSelection(this, clipPos(this, head), other && clipPos(this, other), options);
  7526. }),
  7527. extendSelections: docMethodOp(function(heads, options) {
  7528. extendSelections(this, clipPosArray(this, heads), options);
  7529. }),
  7530. extendSelectionsBy: docMethodOp(function(f, options) {
  7531. var heads = map(this.sel.ranges, f);
  7532. extendSelections(this, clipPosArray(this, heads), options);
  7533. }),
  7534. setSelections: docMethodOp(function(ranges, primary, options) {
  7535. var this$1 = this;
  7536. if (!ranges.length) { return }
  7537. var out = [];
  7538. for (var i = 0; i < ranges.length; i++)
  7539. { out[i] = new Range(clipPos(this$1, ranges[i].anchor),
  7540. clipPos(this$1, ranges[i].head)); }
  7541. if (primary == null) { primary = Math.min(ranges.length - 1, this.sel.primIndex); }
  7542. setSelection(this, normalizeSelection(out, primary), options);
  7543. }),
  7544. addSelection: docMethodOp(function(anchor, head, options) {
  7545. var ranges = this.sel.ranges.slice(0);
  7546. ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor)));
  7547. setSelection(this, normalizeSelection(ranges, ranges.length - 1), options);
  7548. }),
  7549. getSelection: function(lineSep) {
  7550. var this$1 = this;
  7551. var ranges = this.sel.ranges, lines;
  7552. for (var i = 0; i < ranges.length; i++) {
  7553. var sel = getBetween(this$1, ranges[i].from(), ranges[i].to());
  7554. lines = lines ? lines.concat(sel) : sel;
  7555. }
  7556. if (lineSep === false) { return lines }
  7557. else { return lines.join(lineSep || this.lineSeparator()) }
  7558. },
  7559. getSelections: function(lineSep) {
  7560. var this$1 = this;
  7561. var parts = [], ranges = this.sel.ranges;
  7562. for (var i = 0; i < ranges.length; i++) {
  7563. var sel = getBetween(this$1, ranges[i].from(), ranges[i].to());
  7564. if (lineSep !== false) { sel = sel.join(lineSep || this$1.lineSeparator()); }
  7565. parts[i] = sel;
  7566. }
  7567. return parts
  7568. },
  7569. replaceSelection: function(code, collapse, origin) {
  7570. var dup = [];
  7571. for (var i = 0; i < this.sel.ranges.length; i++)
  7572. { dup[i] = code; }
  7573. this.replaceSelections(dup, collapse, origin || "+input");
  7574. },
  7575. replaceSelections: docMethodOp(function(code, collapse, origin) {
  7576. var this$1 = this;
  7577. var changes = [], sel = this.sel;
  7578. for (var i = 0; i < sel.ranges.length; i++) {
  7579. var range$$1 = sel.ranges[i];
  7580. changes[i] = {from: range$$1.from(), to: range$$1.to(), text: this$1.splitLines(code[i]), origin: origin};
  7581. }
  7582. var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse);
  7583. for (var i$1 = changes.length - 1; i$1 >= 0; i$1--)
  7584. { makeChange(this$1, changes[i$1]); }
  7585. if (newSel) { setSelectionReplaceHistory(this, newSel); }
  7586. else if (this.cm) { ensureCursorVisible(this.cm); }
  7587. }),
  7588. undo: docMethodOp(function() {makeChangeFromHistory(this, "undo");}),
  7589. redo: docMethodOp(function() {makeChangeFromHistory(this, "redo");}),
  7590. undoSelection: docMethodOp(function() {makeChangeFromHistory(this, "undo", true);}),
  7591. redoSelection: docMethodOp(function() {makeChangeFromHistory(this, "redo", true);}),
  7592. setExtending: function(val) {this.extend = val;},
  7593. getExtending: function() {return this.extend},
  7594. historySize: function() {
  7595. var hist = this.history, done = 0, undone = 0;
  7596. for (var i = 0; i < hist.done.length; i++) { if (!hist.done[i].ranges) { ++done; } }
  7597. for (var i$1 = 0; i$1 < hist.undone.length; i$1++) { if (!hist.undone[i$1].ranges) { ++undone; } }
  7598. return {undo: done, redo: undone}
  7599. },
  7600. clearHistory: function() {this.history = new History(this.history.maxGeneration);},
  7601. markClean: function() {
  7602. this.cleanGeneration = this.changeGeneration(true);
  7603. },
  7604. changeGeneration: function(forceSplit) {
  7605. if (forceSplit)
  7606. { this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null; }
  7607. return this.history.generation
  7608. },
  7609. isClean: function (gen) {
  7610. return this.history.generation == (gen || this.cleanGeneration)
  7611. },
  7612. getHistory: function() {
  7613. return {done: copyHistoryArray(this.history.done),
  7614. undone: copyHistoryArray(this.history.undone)}
  7615. },
  7616. setHistory: function(histData) {
  7617. var hist = this.history = new History(this.history.maxGeneration);
  7618. hist.done = copyHistoryArray(histData.done.slice(0), null, true);
  7619. hist.undone = copyHistoryArray(histData.undone.slice(0), null, true);
  7620. },
  7621. setGutterMarker: docMethodOp(function(line, gutterID, value) {
  7622. return changeLine(this, line, "gutter", function (line) {
  7623. var markers = line.gutterMarkers || (line.gutterMarkers = {});
  7624. markers[gutterID] = value;
  7625. if (!value && isEmpty(markers)) { line.gutterMarkers = null; }
  7626. return true
  7627. })
  7628. }),
  7629. clearGutter: docMethodOp(function(gutterID) {
  7630. var this$1 = this;
  7631. this.iter(function (line) {
  7632. if (line.gutterMarkers && line.gutterMarkers[gutterID]) {
  7633. changeLine(this$1, line, "gutter", function () {
  7634. line.gutterMarkers[gutterID] = null;
  7635. if (isEmpty(line.gutterMarkers)) { line.gutterMarkers = null; }
  7636. return true
  7637. });
  7638. }
  7639. });
  7640. }),
  7641. lineInfo: function(line) {
  7642. var n;
  7643. if (typeof line == "number") {
  7644. if (!isLine(this, line)) { return null }
  7645. n = line;
  7646. line = getLine(this, line);
  7647. if (!line) { return null }
  7648. } else {
  7649. n = lineNo(line);
  7650. if (n == null) { return null }
  7651. }
  7652. return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers,
  7653. textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass,
  7654. widgets: line.widgets}
  7655. },
  7656. addLineClass: docMethodOp(function(handle, where, cls) {
  7657. return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) {
  7658. var prop = where == "text" ? "textClass"
  7659. : where == "background" ? "bgClass"
  7660. : where == "gutter" ? "gutterClass" : "wrapClass";
  7661. if (!line[prop]) { line[prop] = cls; }
  7662. else if (classTest(cls).test(line[prop])) { return false }
  7663. else { line[prop] += " " + cls; }
  7664. return true
  7665. })
  7666. }),
  7667. removeLineClass: docMethodOp(function(handle, where, cls) {
  7668. return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) {
  7669. var prop = where == "text" ? "textClass"
  7670. : where == "background" ? "bgClass"
  7671. : where == "gutter" ? "gutterClass" : "wrapClass";
  7672. var cur = line[prop];
  7673. if (!cur) { return false }
  7674. else if (cls == null) { line[prop] = null; }
  7675. else {
  7676. var found = cur.match(classTest(cls));
  7677. if (!found) { return false }
  7678. var end = found.index + found[0].length;
  7679. line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null;
  7680. }
  7681. return true
  7682. })
  7683. }),
  7684. addLineWidget: docMethodOp(function(handle, node, options) {
  7685. return addLineWidget(this, handle, node, options)
  7686. }),
  7687. removeLineWidget: function(widget) { widget.clear(); },
  7688. markText: function(from, to, options) {
  7689. return markText(this, clipPos(this, from), clipPos(this, to), options, options && options.type || "range")
  7690. },
  7691. setBookmark: function(pos, options) {
  7692. var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options),
  7693. insertLeft: options && options.insertLeft,
  7694. clearWhenEmpty: false, shared: options && options.shared,
  7695. handleMouseEvents: options && options.handleMouseEvents};
  7696. pos = clipPos(this, pos);
  7697. return markText(this, pos, pos, realOpts, "bookmark")
  7698. },
  7699. findMarksAt: function(pos) {
  7700. pos = clipPos(this, pos);
  7701. var markers = [], spans = getLine(this, pos.line).markedSpans;
  7702. if (spans) { for (var i = 0; i < spans.length; ++i) {
  7703. var span = spans[i];
  7704. if ((span.from == null || span.from <= pos.ch) &&
  7705. (span.to == null || span.to >= pos.ch))
  7706. { markers.push(span.marker.parent || span.marker); }
  7707. } }
  7708. return markers
  7709. },
  7710. findMarks: function(from, to, filter) {
  7711. from = clipPos(this, from); to = clipPos(this, to);
  7712. var found = [], lineNo$$1 = from.line;
  7713. this.iter(from.line, to.line + 1, function (line) {
  7714. var spans = line.markedSpans;
  7715. if (spans) { for (var i = 0; i < spans.length; i++) {
  7716. var span = spans[i];
  7717. if (!(span.to != null && lineNo$$1 == from.line && from.ch >= span.to ||
  7718. span.from == null && lineNo$$1 != from.line ||
  7719. span.from != null && lineNo$$1 == to.line && span.from >= to.ch) &&
  7720. (!filter || filter(span.marker)))
  7721. { found.push(span.marker.parent || span.marker); }
  7722. } }
  7723. ++lineNo$$1;
  7724. });
  7725. return found
  7726. },
  7727. getAllMarks: function() {
  7728. var markers = [];
  7729. this.iter(function (line) {
  7730. var sps = line.markedSpans;
  7731. if (sps) { for (var i = 0; i < sps.length; ++i)
  7732. { if (sps[i].from != null) { markers.push(sps[i].marker); } } }
  7733. });
  7734. return markers
  7735. },
  7736. posFromIndex: function(off) {
  7737. var ch, lineNo$$1 = this.first, sepSize = this.lineSeparator().length;
  7738. this.iter(function (line) {
  7739. var sz = line.text.length + sepSize;
  7740. if (sz > off) { ch = off; return true }
  7741. off -= sz;
  7742. ++lineNo$$1;
  7743. });
  7744. return clipPos(this, Pos(lineNo$$1, ch))
  7745. },
  7746. indexFromPos: function (coords) {
  7747. coords = clipPos(this, coords);
  7748. var index = coords.ch;
  7749. if (coords.line < this.first || coords.ch < 0) { return 0 }
  7750. var sepSize = this.lineSeparator().length;
  7751. this.iter(this.first, coords.line, function (line) { // iter aborts when callback returns a truthy value
  7752. index += line.text.length + sepSize;
  7753. });
  7754. return index
  7755. },
  7756. copy: function(copyHistory) {
  7757. var doc = new Doc(getLines(this, this.first, this.first + this.size),
  7758. this.modeOption, this.first, this.lineSep, this.direction);
  7759. doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft;
  7760. doc.sel = this.sel;
  7761. doc.extend = false;
  7762. if (copyHistory) {
  7763. doc.history.undoDepth = this.history.undoDepth;
  7764. doc.setHistory(this.getHistory());
  7765. }
  7766. return doc
  7767. },
  7768. linkedDoc: function(options) {
  7769. if (!options) { options = {}; }
  7770. var from = this.first, to = this.first + this.size;
  7771. if (options.from != null && options.from > from) { from = options.from; }
  7772. if (options.to != null && options.to < to) { to = options.to; }
  7773. var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from, this.lineSep, this.direction);
  7774. if (options.sharedHist) { copy.history = this.history
  7775. ; }(this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist});
  7776. copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}];
  7777. copySharedMarkers(copy, findSharedMarkers(this));
  7778. return copy
  7779. },
  7780. unlinkDoc: function(other) {
  7781. var this$1 = this;
  7782. if (other instanceof CodeMirror$1) { other = other.doc; }
  7783. if (this.linked) { for (var i = 0; i < this.linked.length; ++i) {
  7784. var link = this$1.linked[i];
  7785. if (link.doc != other) { continue }
  7786. this$1.linked.splice(i, 1);
  7787. other.unlinkDoc(this$1);
  7788. detachSharedMarkers(findSharedMarkers(this$1));
  7789. break
  7790. } }
  7791. // If the histories were shared, split them again
  7792. if (other.history == this.history) {
  7793. var splitIds = [other.id];
  7794. linkedDocs(other, function (doc) { return splitIds.push(doc.id); }, true);
  7795. other.history = new History(null);
  7796. other.history.done = copyHistoryArray(this.history.done, splitIds);
  7797. other.history.undone = copyHistoryArray(this.history.undone, splitIds);
  7798. }
  7799. },
  7800. iterLinkedDocs: function(f) {linkedDocs(this, f);},
  7801. getMode: function() {return this.mode},
  7802. getEditor: function() {return this.cm},
  7803. splitLines: function(str) {
  7804. if (this.lineSep) { return str.split(this.lineSep) }
  7805. return splitLinesAuto(str)
  7806. },
  7807. lineSeparator: function() { return this.lineSep || "\n" },
  7808. setDirection: docMethodOp(function (dir) {
  7809. if (dir != "rtl") { dir = "ltr"; }
  7810. if (dir == this.direction) { return }
  7811. this.direction = dir;
  7812. this.iter(function (line) { return line.order = null; });
  7813. if (this.cm) { directionChanged(this.cm); }
  7814. })
  7815. });
  7816. // Public alias.
  7817. Doc.prototype.eachLine = Doc.prototype.iter;
  7818. // Kludge to work around strange IE behavior where it'll sometimes
  7819. // re-fire a series of drag-related events right after the drop (#1551)
  7820. var lastDrop = 0;
  7821. function onDrop(e) {
  7822. var cm = this;
  7823. clearDragCursor(cm);
  7824. if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e))
  7825. { return }
  7826. e_preventDefault(e);
  7827. if (ie) { lastDrop = +new Date; }
  7828. var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files;
  7829. if (!pos || cm.isReadOnly()) { return }
  7830. // Might be a file drop, in which case we simply extract the text
  7831. // and insert it.
  7832. if (files && files.length && window.FileReader && window.File) {
  7833. var n = files.length, text = Array(n), read = 0;
  7834. var loadFile = function (file, i) {
  7835. if (cm.options.allowDropFileTypes &&
  7836. indexOf(cm.options.allowDropFileTypes, file.type) == -1)
  7837. { return }
  7838. var reader = new FileReader;
  7839. reader.onload = operation(cm, function () {
  7840. var content = reader.result;
  7841. if (/[\x00-\x08\x0e-\x1f]{2}/.test(content)) { content = ""; }
  7842. text[i] = content;
  7843. if (++read == n) {
  7844. pos = clipPos(cm.doc, pos);
  7845. var change = {from: pos, to: pos,
  7846. text: cm.doc.splitLines(text.join(cm.doc.lineSeparator())),
  7847. origin: "paste"};
  7848. makeChange(cm.doc, change);
  7849. setSelectionReplaceHistory(cm.doc, simpleSelection(pos, changeEnd(change)));
  7850. }
  7851. });
  7852. reader.readAsText(file);
  7853. };
  7854. for (var i = 0; i < n; ++i) { loadFile(files[i], i); }
  7855. } else { // Normal drop
  7856. // Don't do a replace if the drop happened inside of the selected text.
  7857. if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) {
  7858. cm.state.draggingText(e);
  7859. // Ensure the editor is re-focused
  7860. setTimeout(function () { return cm.display.input.focus(); }, 20);
  7861. return
  7862. }
  7863. try {
  7864. var text$1 = e.dataTransfer.getData("Text");
  7865. if (text$1) {
  7866. var selected;
  7867. if (cm.state.draggingText && !cm.state.draggingText.copy)
  7868. { selected = cm.listSelections(); }
  7869. setSelectionNoUndo(cm.doc, simpleSelection(pos, pos));
  7870. if (selected) { for (var i$1 = 0; i$1 < selected.length; ++i$1)
  7871. { replaceRange(cm.doc, "", selected[i$1].anchor, selected[i$1].head, "drag"); } }
  7872. cm.replaceSelection(text$1, "around", "paste");
  7873. cm.display.input.focus();
  7874. }
  7875. }
  7876. catch(e){}
  7877. }
  7878. }
  7879. function onDragStart(cm, e) {
  7880. if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return }
  7881. if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) { return }
  7882. e.dataTransfer.setData("Text", cm.getSelection());
  7883. e.dataTransfer.effectAllowed = "copyMove";
  7884. // Use dummy image instead of default browsers image.
  7885. // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there.
  7886. if (e.dataTransfer.setDragImage && !safari) {
  7887. var img = elt("img", null, null, "position: fixed; left: 0; top: 0;");
  7888. img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";
  7889. if (presto) {
  7890. img.width = img.height = 1;
  7891. cm.display.wrapper.appendChild(img);
  7892. // Force a relayout, or Opera won't use our image for some obscure reason
  7893. img._top = img.offsetTop;
  7894. }
  7895. e.dataTransfer.setDragImage(img, 0, 0);
  7896. if (presto) { img.parentNode.removeChild(img); }
  7897. }
  7898. }
  7899. function onDragOver(cm, e) {
  7900. var pos = posFromMouse(cm, e);
  7901. if (!pos) { return }
  7902. var frag = document.createDocumentFragment();
  7903. drawSelectionCursor(cm, pos, frag);
  7904. if (!cm.display.dragCursor) {
  7905. cm.display.dragCursor = elt("div", null, "CodeMirror-cursors CodeMirror-dragcursors");
  7906. cm.display.lineSpace.insertBefore(cm.display.dragCursor, cm.display.cursorDiv);
  7907. }
  7908. removeChildrenAndAdd(cm.display.dragCursor, frag);
  7909. }
  7910. function clearDragCursor(cm) {
  7911. if (cm.display.dragCursor) {
  7912. cm.display.lineSpace.removeChild(cm.display.dragCursor);
  7913. cm.display.dragCursor = null;
  7914. }
  7915. }
  7916. // These must be handled carefully, because naively registering a
  7917. // handler for each editor will cause the editors to never be
  7918. // garbage collected.
  7919. function forEachCodeMirror(f) {
  7920. if (!document.getElementsByClassName) { return }
  7921. var byClass = document.getElementsByClassName("CodeMirror");
  7922. for (var i = 0; i < byClass.length; i++) {
  7923. var cm = byClass[i].CodeMirror;
  7924. if (cm) { f(cm); }
  7925. }
  7926. }
  7927. var globalsRegistered = false;
  7928. function ensureGlobalHandlers() {
  7929. if (globalsRegistered) { return }
  7930. registerGlobalHandlers();
  7931. globalsRegistered = true;
  7932. }
  7933. function registerGlobalHandlers() {
  7934. // When the window resizes, we need to refresh active editors.
  7935. var resizeTimer;
  7936. on(window, "resize", function () {
  7937. if (resizeTimer == null) { resizeTimer = setTimeout(function () {
  7938. resizeTimer = null;
  7939. forEachCodeMirror(onResize);
  7940. }, 100); }
  7941. });
  7942. // When the window loses focus, we want to show the editor as blurred
  7943. on(window, "blur", function () { return forEachCodeMirror(onBlur); });
  7944. }
  7945. // Called when the window resizes
  7946. function onResize(cm) {
  7947. var d = cm.display;
  7948. if (d.lastWrapHeight == d.wrapper.clientHeight && d.lastWrapWidth == d.wrapper.clientWidth)
  7949. { return }
  7950. // Might be a text scaling operation, clear size caches.
  7951. d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
  7952. d.scrollbarsClipped = false;
  7953. cm.setSize();
  7954. }
  7955. var keyNames = {
  7956. 3: "Enter", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt",
  7957. 19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End",
  7958. 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert",
  7959. 46: "Delete", 59: ";", 61: "=", 91: "Mod", 92: "Mod", 93: "Mod",
  7960. 106: "*", 107: "=", 109: "-", 110: ".", 111: "/", 127: "Delete",
  7961. 173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\",
  7962. 221: "]", 222: "'", 63232: "Up", 63233: "Down", 63234: "Left", 63235: "Right", 63272: "Delete",
  7963. 63273: "Home", 63275: "End", 63276: "PageUp", 63277: "PageDown", 63302: "Insert"
  7964. };
  7965. // Number keys
  7966. for (var i = 0; i < 10; i++) { keyNames[i + 48] = keyNames[i + 96] = String(i); }
  7967. // Alphabetic keys
  7968. for (var i$1 = 65; i$1 <= 90; i$1++) { keyNames[i$1] = String.fromCharCode(i$1); }
  7969. // Function keys
  7970. for (var i$2 = 1; i$2 <= 12; i$2++) { keyNames[i$2 + 111] = keyNames[i$2 + 63235] = "F" + i$2; }
  7971. var keyMap = {};
  7972. keyMap.basic = {
  7973. "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown",
  7974. "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown",
  7975. "Delete": "delCharAfter", "Backspace": "delCharBefore", "Shift-Backspace": "delCharBefore",
  7976. "Tab": "defaultTab", "Shift-Tab": "indentAuto",
  7977. "Enter": "newlineAndIndent", "Insert": "toggleOverwrite",
  7978. "Esc": "singleSelection"
  7979. };
  7980. // Note that the save and find-related commands aren't defined by
  7981. // default. User code or addons can define them. Unknown commands
  7982. // are simply ignored.
  7983. keyMap.pcDefault = {
  7984. "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo",
  7985. "Ctrl-Home": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Up": "goLineUp", "Ctrl-Down": "goLineDown",
  7986. "Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd",
  7987. "Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find",
  7988. "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll",
  7989. "Ctrl-[": "indentLess", "Ctrl-]": "indentMore",
  7990. "Ctrl-U": "undoSelection", "Shift-Ctrl-U": "redoSelection", "Alt-U": "redoSelection",
  7991. fallthrough: "basic"
  7992. };
  7993. // Very basic readline/emacs-style bindings, which are standard on Mac.
  7994. keyMap.emacsy = {
  7995. "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown",
  7996. "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd",
  7997. "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp", "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore",
  7998. "Alt-D": "delWordAfter", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars",
  7999. "Ctrl-O": "openLine"
  8000. };
  8001. keyMap.macDefault = {
  8002. "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo",
  8003. "Cmd-Home": "goDocStart", "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft",
  8004. "Alt-Right": "goGroupRight", "Cmd-Left": "goLineLeft", "Cmd-Right": "goLineRight", "Alt-Backspace": "delGroupBefore",
  8005. "Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find",
  8006. "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll",
  8007. "Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delWrappedLineLeft", "Cmd-Delete": "delWrappedLineRight",
  8008. "Cmd-U": "undoSelection", "Shift-Cmd-U": "redoSelection", "Ctrl-Up": "goDocStart", "Ctrl-Down": "goDocEnd",
  8009. fallthrough: ["basic", "emacsy"]
  8010. };
  8011. keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault;
  8012. // KEYMAP DISPATCH
  8013. function normalizeKeyName(name) {
  8014. var parts = name.split(/-(?!$)/);
  8015. name = parts[parts.length - 1];
  8016. var alt, ctrl, shift, cmd;
  8017. for (var i = 0; i < parts.length - 1; i++) {
  8018. var mod = parts[i];
  8019. if (/^(cmd|meta|m)$/i.test(mod)) { cmd = true; }
  8020. else if (/^a(lt)?$/i.test(mod)) { alt = true; }
  8021. else if (/^(c|ctrl|control)$/i.test(mod)) { ctrl = true; }
  8022. else if (/^s(hift)?$/i.test(mod)) { shift = true; }
  8023. else { throw new Error("Unrecognized modifier name: " + mod) }
  8024. }
  8025. if (alt) { name = "Alt-" + name; }
  8026. if (ctrl) { name = "Ctrl-" + name; }
  8027. if (cmd) { name = "Cmd-" + name; }
  8028. if (shift) { name = "Shift-" + name; }
  8029. return name
  8030. }
  8031. // This is a kludge to keep keymaps mostly working as raw objects
  8032. // (backwards compatibility) while at the same time support features
  8033. // like normalization and multi-stroke key bindings. It compiles a
  8034. // new normalized keymap, and then updates the old object to reflect
  8035. // this.
  8036. function normalizeKeyMap(keymap) {
  8037. var copy = {};
  8038. for (var keyname in keymap) { if (keymap.hasOwnProperty(keyname)) {
  8039. var value = keymap[keyname];
  8040. if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) { continue }
  8041. if (value == "...") { delete keymap[keyname]; continue }
  8042. var keys = map(keyname.split(" "), normalizeKeyName);
  8043. for (var i = 0; i < keys.length; i++) {
  8044. var val = (void 0), name = (void 0);
  8045. if (i == keys.length - 1) {
  8046. name = keys.join(" ");
  8047. val = value;
  8048. } else {
  8049. name = keys.slice(0, i + 1).join(" ");
  8050. val = "...";
  8051. }
  8052. var prev = copy[name];
  8053. if (!prev) { copy[name] = val; }
  8054. else if (prev != val) { throw new Error("Inconsistent bindings for " + name) }
  8055. }
  8056. delete keymap[keyname];
  8057. } }
  8058. for (var prop in copy) { keymap[prop] = copy[prop]; }
  8059. return keymap
  8060. }
  8061. function lookupKey(key, map$$1, handle, context) {
  8062. map$$1 = getKeyMap(map$$1);
  8063. var found = map$$1.call ? map$$1.call(key, context) : map$$1[key];
  8064. if (found === false) { return "nothing" }
  8065. if (found === "...") { return "multi" }
  8066. if (found != null && handle(found)) { return "handled" }
  8067. if (map$$1.fallthrough) {
  8068. if (Object.prototype.toString.call(map$$1.fallthrough) != "[object Array]")
  8069. { return lookupKey(key, map$$1.fallthrough, handle, context) }
  8070. for (var i = 0; i < map$$1.fallthrough.length; i++) {
  8071. var result = lookupKey(key, map$$1.fallthrough[i], handle, context);
  8072. if (result) { return result }
  8073. }
  8074. }
  8075. }
  8076. // Modifier key presses don't count as 'real' key presses for the
  8077. // purpose of keymap fallthrough.
  8078. function isModifierKey(value) {
  8079. var name = typeof value == "string" ? value : keyNames[value.keyCode];
  8080. return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod"
  8081. }
  8082. function addModifierNames(name, event, noShift) {
  8083. var base = name;
  8084. if (event.altKey && base != "Alt") { name = "Alt-" + name; }
  8085. if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != "Ctrl") { name = "Ctrl-" + name; }
  8086. if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != "Cmd") { name = "Cmd-" + name; }
  8087. if (!noShift && event.shiftKey && base != "Shift") { name = "Shift-" + name; }
  8088. return name
  8089. }
  8090. // Look up the name of a key as indicated by an event object.
  8091. function keyName(event, noShift) {
  8092. if (presto && event.keyCode == 34 && event["char"]) { return false }
  8093. var name = keyNames[event.keyCode];
  8094. if (name == null || event.altGraphKey) { return false }
  8095. return addModifierNames(name, event, noShift)
  8096. }
  8097. function getKeyMap(val) {
  8098. return typeof val == "string" ? keyMap[val] : val
  8099. }
  8100. // Helper for deleting text near the selection(s), used to implement
  8101. // backspace, delete, and similar functionality.
  8102. function deleteNearSelection(cm, compute) {
  8103. var ranges = cm.doc.sel.ranges, kill = [];
  8104. // Build up a set of ranges to kill first, merging overlapping
  8105. // ranges.
  8106. for (var i = 0; i < ranges.length; i++) {
  8107. var toKill = compute(ranges[i]);
  8108. while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) {
  8109. var replaced = kill.pop();
  8110. if (cmp(replaced.from, toKill.from) < 0) {
  8111. toKill.from = replaced.from;
  8112. break
  8113. }
  8114. }
  8115. kill.push(toKill);
  8116. }
  8117. // Next, remove those actual ranges.
  8118. runInOp(cm, function () {
  8119. for (var i = kill.length - 1; i >= 0; i--)
  8120. { replaceRange(cm.doc, "", kill[i].from, kill[i].to, "+delete"); }
  8121. ensureCursorVisible(cm);
  8122. });
  8123. }
  8124. function moveCharLogically(line, ch, dir) {
  8125. var target = skipExtendingChars(line.text, ch + dir, dir);
  8126. return target < 0 || target > line.text.length ? null : target
  8127. }
  8128. function moveLogically(line, start, dir) {
  8129. var ch = moveCharLogically(line, start.ch, dir);
  8130. return ch == null ? null : new Pos(start.line, ch, dir < 0 ? "after" : "before")
  8131. }
  8132. function endOfLine(visually, cm, lineObj, lineNo, dir) {
  8133. if (visually) {
  8134. var order = getOrder(lineObj, cm.doc.direction);
  8135. if (order) {
  8136. var part = dir < 0 ? lst(order) : order[0];
  8137. var moveInStorageOrder = (dir < 0) == (part.level == 1);
  8138. var sticky = moveInStorageOrder ? "after" : "before";
  8139. var ch;
  8140. // With a wrapped rtl chunk (possibly spanning multiple bidi parts),
  8141. // it could be that the last bidi part is not on the last visual line,
  8142. // since visual lines contain content order-consecutive chunks.
  8143. // Thus, in rtl, we are looking for the first (content-order) character
  8144. // in the rtl chunk that is on the last line (that is, the same line
  8145. // as the last (content-order) character).
  8146. if (part.level > 0 || cm.doc.direction == "rtl") {
  8147. var prep = prepareMeasureForLine(cm, lineObj);
  8148. ch = dir < 0 ? lineObj.text.length - 1 : 0;
  8149. var targetTop = measureCharPrepared(cm, prep, ch).top;
  8150. ch = findFirst(function (ch) { return measureCharPrepared(cm, prep, ch).top == targetTop; }, (dir < 0) == (part.level == 1) ? part.from : part.to - 1, ch);
  8151. if (sticky == "before") { ch = moveCharLogically(lineObj, ch, 1); }
  8152. } else { ch = dir < 0 ? part.to : part.from; }
  8153. return new Pos(lineNo, ch, sticky)
  8154. }
  8155. }
  8156. return new Pos(lineNo, dir < 0 ? lineObj.text.length : 0, dir < 0 ? "before" : "after")
  8157. }
  8158. function moveVisually(cm, line, start, dir) {
  8159. var bidi = getOrder(line, cm.doc.direction);
  8160. if (!bidi) { return moveLogically(line, start, dir) }
  8161. if (start.ch >= line.text.length) {
  8162. start.ch = line.text.length;
  8163. start.sticky = "before";
  8164. } else if (start.ch <= 0) {
  8165. start.ch = 0;
  8166. start.sticky = "after";
  8167. }
  8168. var partPos = getBidiPartAt(bidi, start.ch, start.sticky), part = bidi[partPos];
  8169. if (cm.doc.direction == "ltr" && part.level % 2 == 0 && (dir > 0 ? part.to > start.ch : part.from < start.ch)) {
  8170. // Case 1: We move within an ltr part in an ltr editor. Even with wrapped lines,
  8171. // nothing interesting happens.
  8172. return moveLogically(line, start, dir)
  8173. }
  8174. var mv = function (pos, dir) { return moveCharLogically(line, pos instanceof Pos ? pos.ch : pos, dir); };
  8175. var prep;
  8176. var getWrappedLineExtent = function (ch) {
  8177. if (!cm.options.lineWrapping) { return {begin: 0, end: line.text.length} }
  8178. prep = prep || prepareMeasureForLine(cm, line);
  8179. return wrappedLineExtentChar(cm, line, prep, ch)
  8180. };
  8181. var wrappedLineExtent = getWrappedLineExtent(start.sticky == "before" ? mv(start, -1) : start.ch);
  8182. if (cm.doc.direction == "rtl" || part.level == 1) {
  8183. var moveInStorageOrder = (part.level == 1) == (dir < 0);
  8184. var ch = mv(start, moveInStorageOrder ? 1 : -1);
  8185. if (ch != null && (!moveInStorageOrder ? ch >= part.from && ch >= wrappedLineExtent.begin : ch <= part.to && ch <= wrappedLineExtent.end)) {
  8186. // Case 2: We move within an rtl part or in an rtl editor on the same visual line
  8187. var sticky = moveInStorageOrder ? "before" : "after";
  8188. return new Pos(start.line, ch, sticky)
  8189. }
  8190. }
  8191. // Case 3: Could not move within this bidi part in this visual line, so leave
  8192. // the current bidi part
  8193. var searchInVisualLine = function (partPos, dir, wrappedLineExtent) {
  8194. var getRes = function (ch, moveInStorageOrder) { return moveInStorageOrder
  8195. ? new Pos(start.line, mv(ch, 1), "before")
  8196. : new Pos(start.line, ch, "after"); };
  8197. for (; partPos >= 0 && partPos < bidi.length; partPos += dir) {
  8198. var part = bidi[partPos];
  8199. var moveInStorageOrder = (dir > 0) == (part.level != 1);
  8200. var ch = moveInStorageOrder ? wrappedLineExtent.begin : mv(wrappedLineExtent.end, -1);
  8201. if (part.from <= ch && ch < part.to) { return getRes(ch, moveInStorageOrder) }
  8202. ch = moveInStorageOrder ? part.from : mv(part.to, -1);
  8203. if (wrappedLineExtent.begin <= ch && ch < wrappedLineExtent.end) { return getRes(ch, moveInStorageOrder) }
  8204. }
  8205. };
  8206. // Case 3a: Look for other bidi parts on the same visual line
  8207. var res = searchInVisualLine(partPos + dir, dir, wrappedLineExtent);
  8208. if (res) { return res }
  8209. // Case 3b: Look for other bidi parts on the next visual line
  8210. var nextCh = dir > 0 ? wrappedLineExtent.end : mv(wrappedLineExtent.begin, -1);
  8211. if (nextCh != null && !(dir > 0 && nextCh == line.text.length)) {
  8212. res = searchInVisualLine(dir > 0 ? 0 : bidi.length - 1, dir, getWrappedLineExtent(nextCh));
  8213. if (res) { return res }
  8214. }
  8215. // Case 4: Nowhere to move
  8216. return null
  8217. }
  8218. // Commands are parameter-less actions that can be performed on an
  8219. // editor, mostly used for keybindings.
  8220. var commands = {
  8221. selectAll: selectAll,
  8222. singleSelection: function (cm) { return cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll); },
  8223. killLine: function (cm) { return deleteNearSelection(cm, function (range) {
  8224. if (range.empty()) {
  8225. var len = getLine(cm.doc, range.head.line).text.length;
  8226. if (range.head.ch == len && range.head.line < cm.lastLine())
  8227. { return {from: range.head, to: Pos(range.head.line + 1, 0)} }
  8228. else
  8229. { return {from: range.head, to: Pos(range.head.line, len)} }
  8230. } else {
  8231. return {from: range.from(), to: range.to()}
  8232. }
  8233. }); },
  8234. deleteLine: function (cm) { return deleteNearSelection(cm, function (range) { return ({
  8235. from: Pos(range.from().line, 0),
  8236. to: clipPos(cm.doc, Pos(range.to().line + 1, 0))
  8237. }); }); },
  8238. delLineLeft: function (cm) { return deleteNearSelection(cm, function (range) { return ({
  8239. from: Pos(range.from().line, 0), to: range.from()
  8240. }); }); },
  8241. delWrappedLineLeft: function (cm) { return deleteNearSelection(cm, function (range) {
  8242. var top = cm.charCoords(range.head, "div").top + 5;
  8243. var leftPos = cm.coordsChar({left: 0, top: top}, "div");
  8244. return {from: leftPos, to: range.from()}
  8245. }); },
  8246. delWrappedLineRight: function (cm) { return deleteNearSelection(cm, function (range) {
  8247. var top = cm.charCoords(range.head, "div").top + 5;
  8248. var rightPos = cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div");
  8249. return {from: range.from(), to: rightPos }
  8250. }); },
  8251. undo: function (cm) { return cm.undo(); },
  8252. redo: function (cm) { return cm.redo(); },
  8253. undoSelection: function (cm) { return cm.undoSelection(); },
  8254. redoSelection: function (cm) { return cm.redoSelection(); },
  8255. goDocStart: function (cm) { return cm.extendSelection(Pos(cm.firstLine(), 0)); },
  8256. goDocEnd: function (cm) { return cm.extendSelection(Pos(cm.lastLine())); },
  8257. goLineStart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStart(cm, range.head.line); },
  8258. {origin: "+move", bias: 1}
  8259. ); },
  8260. goLineStartSmart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStartSmart(cm, range.head); },
  8261. {origin: "+move", bias: 1}
  8262. ); },
  8263. goLineEnd: function (cm) { return cm.extendSelectionsBy(function (range) { return lineEnd(cm, range.head.line); },
  8264. {origin: "+move", bias: -1}
  8265. ); },
  8266. goLineRight: function (cm) { return cm.extendSelectionsBy(function (range) {
  8267. var top = cm.cursorCoords(range.head, "div").top + 5;
  8268. return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div")
  8269. }, sel_move); },
  8270. goLineLeft: function (cm) { return cm.extendSelectionsBy(function (range) {
  8271. var top = cm.cursorCoords(range.head, "div").top + 5;
  8272. return cm.coordsChar({left: 0, top: top}, "div")
  8273. }, sel_move); },
  8274. goLineLeftSmart: function (cm) { return cm.extendSelectionsBy(function (range) {
  8275. var top = cm.cursorCoords(range.head, "div").top + 5;
  8276. var pos = cm.coordsChar({left: 0, top: top}, "div");
  8277. if (pos.ch < cm.getLine(pos.line).search(/\S/)) { return lineStartSmart(cm, range.head) }
  8278. return pos
  8279. }, sel_move); },
  8280. goLineUp: function (cm) { return cm.moveV(-1, "line"); },
  8281. goLineDown: function (cm) { return cm.moveV(1, "line"); },
  8282. goPageUp: function (cm) { return cm.moveV(-1, "page"); },
  8283. goPageDown: function (cm) { return cm.moveV(1, "page"); },
  8284. goCharLeft: function (cm) { return cm.moveH(-1, "char"); },
  8285. goCharRight: function (cm) { return cm.moveH(1, "char"); },
  8286. goColumnLeft: function (cm) { return cm.moveH(-1, "column"); },
  8287. goColumnRight: function (cm) { return cm.moveH(1, "column"); },
  8288. goWordLeft: function (cm) { return cm.moveH(-1, "word"); },
  8289. goGroupRight: function (cm) { return cm.moveH(1, "group"); },
  8290. goGroupLeft: function (cm) { return cm.moveH(-1, "group"); },
  8291. goWordRight: function (cm) { return cm.moveH(1, "word"); },
  8292. delCharBefore: function (cm) { return cm.deleteH(-1, "char"); },
  8293. delCharAfter: function (cm) { return cm.deleteH(1, "char"); },
  8294. delWordBefore: function (cm) { return cm.deleteH(-1, "word"); },
  8295. delWordAfter: function (cm) { return cm.deleteH(1, "word"); },
  8296. delGroupBefore: function (cm) { return cm.deleteH(-1, "group"); },
  8297. delGroupAfter: function (cm) { return cm.deleteH(1, "group"); },
  8298. indentAuto: function (cm) { return cm.indentSelection("smart"); },
  8299. indentMore: function (cm) { return cm.indentSelection("add"); },
  8300. indentLess: function (cm) { return cm.indentSelection("subtract"); },
  8301. insertTab: function (cm) { return cm.replaceSelection("\t"); },
  8302. insertSoftTab: function (cm) {
  8303. var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize;
  8304. for (var i = 0; i < ranges.length; i++) {
  8305. var pos = ranges[i].from();
  8306. var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize);
  8307. spaces.push(spaceStr(tabSize - col % tabSize));
  8308. }
  8309. cm.replaceSelections(spaces);
  8310. },
  8311. defaultTab: function (cm) {
  8312. if (cm.somethingSelected()) { cm.indentSelection("add"); }
  8313. else { cm.execCommand("insertTab"); }
  8314. },
  8315. // Swap the two chars left and right of each selection's head.
  8316. // Move cursor behind the two swapped characters afterwards.
  8317. //
  8318. // Doesn't consider line feeds a character.
  8319. // Doesn't scan more than one line above to find a character.
  8320. // Doesn't do anything on an empty line.
  8321. // Doesn't do anything with non-empty selections.
  8322. transposeChars: function (cm) { return runInOp(cm, function () {
  8323. var ranges = cm.listSelections(), newSel = [];
  8324. for (var i = 0; i < ranges.length; i++) {
  8325. if (!ranges[i].empty()) { continue }
  8326. var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text;
  8327. if (line) {
  8328. if (cur.ch == line.length) { cur = new Pos(cur.line, cur.ch - 1); }
  8329. if (cur.ch > 0) {
  8330. cur = new Pos(cur.line, cur.ch + 1);
  8331. cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2),
  8332. Pos(cur.line, cur.ch - 2), cur, "+transpose");
  8333. } else if (cur.line > cm.doc.first) {
  8334. var prev = getLine(cm.doc, cur.line - 1).text;
  8335. if (prev) {
  8336. cur = new Pos(cur.line, 1);
  8337. cm.replaceRange(line.charAt(0) + cm.doc.lineSeparator() +
  8338. prev.charAt(prev.length - 1),
  8339. Pos(cur.line - 1, prev.length - 1), cur, "+transpose");
  8340. }
  8341. }
  8342. }
  8343. newSel.push(new Range(cur, cur));
  8344. }
  8345. cm.setSelections(newSel);
  8346. }); },
  8347. newlineAndIndent: function (cm) { return runInOp(cm, function () {
  8348. var sels = cm.listSelections();
  8349. for (var i = sels.length - 1; i >= 0; i--)
  8350. { cm.replaceRange(cm.doc.lineSeparator(), sels[i].anchor, sels[i].head, "+input"); }
  8351. sels = cm.listSelections();
  8352. for (var i$1 = 0; i$1 < sels.length; i$1++)
  8353. { cm.indentLine(sels[i$1].from().line, null, true); }
  8354. ensureCursorVisible(cm);
  8355. }); },
  8356. openLine: function (cm) { return cm.replaceSelection("\n", "start"); },
  8357. toggleOverwrite: function (cm) { return cm.toggleOverwrite(); }
  8358. };
  8359. function lineStart(cm, lineN) {
  8360. var line = getLine(cm.doc, lineN);
  8361. var visual = visualLine(line);
  8362. if (visual != line) { lineN = lineNo(visual); }
  8363. return endOfLine(true, cm, visual, lineN, 1)
  8364. }
  8365. function lineEnd(cm, lineN) {
  8366. var line = getLine(cm.doc, lineN);
  8367. var visual = visualLineEnd(line);
  8368. if (visual != line) { lineN = lineNo(visual); }
  8369. return endOfLine(true, cm, line, lineN, -1)
  8370. }
  8371. function lineStartSmart(cm, pos) {
  8372. var start = lineStart(cm, pos.line);
  8373. var line = getLine(cm.doc, start.line);
  8374. var order = getOrder(line, cm.doc.direction);
  8375. if (!order || order[0].level == 0) {
  8376. var firstNonWS = Math.max(0, line.text.search(/\S/));
  8377. var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch;
  8378. return Pos(start.line, inWS ? 0 : firstNonWS, start.sticky)
  8379. }
  8380. return start
  8381. }
  8382. // Run a handler that was bound to a key.
  8383. function doHandleBinding(cm, bound, dropShift) {
  8384. if (typeof bound == "string") {
  8385. bound = commands[bound];
  8386. if (!bound) { return false }
  8387. }
  8388. // Ensure previous input has been read, so that the handler sees a
  8389. // consistent view of the document
  8390. cm.display.input.ensurePolled();
  8391. var prevShift = cm.display.shift, done = false;
  8392. try {
  8393. if (cm.isReadOnly()) { cm.state.suppressEdits = true; }
  8394. if (dropShift) { cm.display.shift = false; }
  8395. done = bound(cm) != Pass;
  8396. } finally {
  8397. cm.display.shift = prevShift;
  8398. cm.state.suppressEdits = false;
  8399. }
  8400. return done
  8401. }
  8402. function lookupKeyForEditor(cm, name, handle) {
  8403. for (var i = 0; i < cm.state.keyMaps.length; i++) {
  8404. var result = lookupKey(name, cm.state.keyMaps[i], handle, cm);
  8405. if (result) { return result }
  8406. }
  8407. return (cm.options.extraKeys && lookupKey(name, cm.options.extraKeys, handle, cm))
  8408. || lookupKey(name, cm.options.keyMap, handle, cm)
  8409. }
  8410. // Note that, despite the name, this function is also used to check
  8411. // for bound mouse clicks.
  8412. var stopSeq = new Delayed;
  8413. function dispatchKey(cm, name, e, handle) {
  8414. var seq = cm.state.keySeq;
  8415. if (seq) {
  8416. if (isModifierKey(name)) { return "handled" }
  8417. if (/\'$/.test(name))
  8418. { cm.state.keySeq = null; }
  8419. else
  8420. { stopSeq.set(50, function () {
  8421. if (cm.state.keySeq == seq) {
  8422. cm.state.keySeq = null;
  8423. cm.display.input.reset();
  8424. }
  8425. }); }
  8426. if (dispatchKeyInner(cm, seq + " " + name, e, handle)) { return true }
  8427. }
  8428. return dispatchKeyInner(cm, name, e, handle)
  8429. }
  8430. function dispatchKeyInner(cm, name, e, handle) {
  8431. var result = lookupKeyForEditor(cm, name, handle);
  8432. if (result == "multi")
  8433. { cm.state.keySeq = name; }
  8434. if (result == "handled")
  8435. { signalLater(cm, "keyHandled", cm, name, e); }
  8436. if (result == "handled" || result == "multi") {
  8437. e_preventDefault(e);
  8438. restartBlink(cm);
  8439. }
  8440. return !!result
  8441. }
  8442. // Handle a key from the keydown event.
  8443. function handleKeyBinding(cm, e) {
  8444. var name = keyName(e, true);
  8445. if (!name) { return false }
  8446. if (e.shiftKey && !cm.state.keySeq) {
  8447. // First try to resolve full name (including 'Shift-'). Failing
  8448. // that, see if there is a cursor-motion command (starting with
  8449. // 'go') bound to the keyname without 'Shift-'.
  8450. return dispatchKey(cm, "Shift-" + name, e, function (b) { return doHandleBinding(cm, b, true); })
  8451. || dispatchKey(cm, name, e, function (b) {
  8452. if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion)
  8453. { return doHandleBinding(cm, b) }
  8454. })
  8455. } else {
  8456. return dispatchKey(cm, name, e, function (b) { return doHandleBinding(cm, b); })
  8457. }
  8458. }
  8459. // Handle a key from the keypress event
  8460. function handleCharBinding(cm, e, ch) {
  8461. return dispatchKey(cm, "'" + ch + "'", e, function (b) { return doHandleBinding(cm, b, true); })
  8462. }
  8463. var lastStoppedKey = null;
  8464. function onKeyDown(e) {
  8465. var cm = this;
  8466. cm.curOp.focus = activeElt();
  8467. if (signalDOMEvent(cm, e)) { return }
  8468. // IE does strange things with escape.
  8469. if (ie && ie_version < 11 && e.keyCode == 27) { e.returnValue = false; }
  8470. var code = e.keyCode;
  8471. cm.display.shift = code == 16 || e.shiftKey;
  8472. var handled = handleKeyBinding(cm, e);
  8473. if (presto) {
  8474. lastStoppedKey = handled ? code : null;
  8475. // Opera has no cut event... we try to at least catch the key combo
  8476. if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey))
  8477. { cm.replaceSelection("", null, "cut"); }
  8478. }
  8479. // Turn mouse into crosshair when Alt is held on Mac.
  8480. if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className))
  8481. { showCrossHair(cm); }
  8482. }
  8483. function showCrossHair(cm) {
  8484. var lineDiv = cm.display.lineDiv;
  8485. addClass(lineDiv, "CodeMirror-crosshair");
  8486. function up(e) {
  8487. if (e.keyCode == 18 || !e.altKey) {
  8488. rmClass(lineDiv, "CodeMirror-crosshair");
  8489. off(document, "keyup", up);
  8490. off(document, "mouseover", up);
  8491. }
  8492. }
  8493. on(document, "keyup", up);
  8494. on(document, "mouseover", up);
  8495. }
  8496. function onKeyUp(e) {
  8497. if (e.keyCode == 16) { this.doc.sel.shift = false; }
  8498. signalDOMEvent(this, e);
  8499. }
  8500. function onKeyPress(e) {
  8501. var cm = this;
  8502. if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) { return }
  8503. var keyCode = e.keyCode, charCode = e.charCode;
  8504. if (presto && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return}
  8505. if ((presto && (!e.which || e.which < 10)) && handleKeyBinding(cm, e)) { return }
  8506. var ch = String.fromCharCode(charCode == null ? keyCode : charCode);
  8507. // Some browsers fire keypress events for backspace
  8508. if (ch == "\x08") { return }
  8509. if (handleCharBinding(cm, e, ch)) { return }
  8510. cm.display.input.onKeyPress(e);
  8511. }
  8512. var DOUBLECLICK_DELAY = 400;
  8513. var PastClick = function(time, pos, button) {
  8514. this.time = time;
  8515. this.pos = pos;
  8516. this.button = button;
  8517. };
  8518. PastClick.prototype.compare = function (time, pos, button) {
  8519. return this.time + DOUBLECLICK_DELAY > time &&
  8520. cmp(pos, this.pos) == 0 && button == this.button
  8521. };
  8522. var lastClick;
  8523. var lastDoubleClick;
  8524. function clickRepeat(pos, button) {
  8525. var now = +new Date;
  8526. if (lastDoubleClick && lastDoubleClick.compare(now, pos, button)) {
  8527. lastClick = lastDoubleClick = null;
  8528. return "triple"
  8529. } else if (lastClick && lastClick.compare(now, pos, button)) {
  8530. lastDoubleClick = new PastClick(now, pos, button);
  8531. lastClick = null;
  8532. return "double"
  8533. } else {
  8534. lastClick = new PastClick(now, pos, button);
  8535. lastDoubleClick = null;
  8536. return "single"
  8537. }
  8538. }
  8539. // A mouse down can be a single click, double click, triple click,
  8540. // start of selection drag, start of text drag, new cursor
  8541. // (ctrl-click), rectangle drag (alt-drag), or xwin
  8542. // middle-click-paste. Or it might be a click on something we should
  8543. // not interfere with, such as a scrollbar or widget.
  8544. function onMouseDown(e) {
  8545. var cm = this, display = cm.display;
  8546. if (signalDOMEvent(cm, e) || display.activeTouch && display.input.supportsTouch()) { return }
  8547. display.input.ensurePolled();
  8548. display.shift = e.shiftKey;
  8549. if (eventInWidget(display, e)) {
  8550. if (!webkit) {
  8551. // Briefly turn off draggability, to allow widgets to do
  8552. // normal dragging things.
  8553. display.scroller.draggable = false;
  8554. setTimeout(function () { return display.scroller.draggable = true; }, 100);
  8555. }
  8556. return
  8557. }
  8558. if (clickInGutter(cm, e)) { return }
  8559. var pos = posFromMouse(cm, e), button = e_button(e), repeat = pos ? clickRepeat(pos, button) : "single";
  8560. window.focus();
  8561. // #3261: make sure, that we're not starting a second selection
  8562. if (button == 1 && cm.state.selectingText)
  8563. { cm.state.selectingText(e); }
  8564. if (pos && handleMappedButton(cm, button, pos, repeat, e)) { return }
  8565. if (button == 1) {
  8566. if (pos) { leftButtonDown(cm, pos, repeat, e); }
  8567. else if (e_target(e) == display.scroller) { e_preventDefault(e); }
  8568. } else if (button == 2) {
  8569. if (pos) { extendSelection(cm.doc, pos); }
  8570. setTimeout(function () { return display.input.focus(); }, 20);
  8571. } else if (button == 3) {
  8572. if (captureRightClick) { onContextMenu(cm, e); }
  8573. else { delayBlurEvent(cm); }
  8574. }
  8575. }
  8576. function handleMappedButton(cm, button, pos, repeat, event) {
  8577. var name = "Click";
  8578. if (repeat == "double") { name = "Double" + name; }
  8579. else if (repeat == "triple") { name = "Triple" + name; }
  8580. name = (button == 1 ? "Left" : button == 2 ? "Middle" : "Right") + name;
  8581. return dispatchKey(cm, addModifierNames(name, event), event, function (bound) {
  8582. if (typeof bound == "string") { bound = commands[bound]; }
  8583. if (!bound) { return false }
  8584. var done = false;
  8585. try {
  8586. if (cm.isReadOnly()) { cm.state.suppressEdits = true; }
  8587. done = bound(cm, pos) != Pass;
  8588. } finally {
  8589. cm.state.suppressEdits = false;
  8590. }
  8591. return done
  8592. })
  8593. }
  8594. function configureMouse(cm, repeat, event) {
  8595. var option = cm.getOption("configureMouse");
  8596. var value = option ? option(cm, repeat, event) : {};
  8597. if (value.unit == null) {
  8598. var rect = chromeOS ? event.shiftKey && event.metaKey : event.altKey;
  8599. value.unit = rect ? "rectangle" : repeat == "single" ? "char" : repeat == "double" ? "word" : "line";
  8600. }
  8601. if (value.extend == null || cm.doc.extend) { value.extend = cm.doc.extend || event.shiftKey; }
  8602. if (value.addNew == null) { value.addNew = mac ? event.metaKey : event.ctrlKey; }
  8603. if (value.moveOnDrag == null) { value.moveOnDrag = !(mac ? event.altKey : event.ctrlKey); }
  8604. return value
  8605. }
  8606. function leftButtonDown(cm, pos, repeat, event) {
  8607. if (ie) { setTimeout(bind(ensureFocus, cm), 0); }
  8608. else { cm.curOp.focus = activeElt(); }
  8609. var behavior = configureMouse(cm, repeat, event);
  8610. var sel = cm.doc.sel, contained;
  8611. if (cm.options.dragDrop && dragAndDrop && !cm.isReadOnly() &&
  8612. repeat == "single" && (contained = sel.contains(pos)) > -1 &&
  8613. (cmp((contained = sel.ranges[contained]).from(), pos) < 0 || pos.xRel > 0) &&
  8614. (cmp(contained.to(), pos) > 0 || pos.xRel < 0))
  8615. { leftButtonStartDrag(cm, event, pos, behavior); }
  8616. else
  8617. { leftButtonSelect(cm, event, pos, behavior); }
  8618. }
  8619. // Start a text drag. When it ends, see if any dragging actually
  8620. // happen, and treat as a click if it didn't.
  8621. function leftButtonStartDrag(cm, event, pos, behavior) {
  8622. var display = cm.display, moved = false;
  8623. var dragEnd = operation(cm, function (e) {
  8624. if (webkit) { display.scroller.draggable = false; }
  8625. cm.state.draggingText = false;
  8626. off(document, "mouseup", dragEnd);
  8627. off(document, "mousemove", mouseMove);
  8628. off(display.scroller, "dragstart", dragStart);
  8629. off(display.scroller, "drop", dragEnd);
  8630. if (!moved) {
  8631. e_preventDefault(e);
  8632. if (!behavior.addNew)
  8633. { extendSelection(cm.doc, pos, null, null, behavior.extend); }
  8634. // Work around unexplainable focus problem in IE9 (#2127) and Chrome (#3081)
  8635. if (webkit || ie && ie_version == 9)
  8636. { setTimeout(function () {document.body.focus(); display.input.focus();}, 20); }
  8637. else
  8638. { display.input.focus(); }
  8639. }
  8640. });
  8641. var mouseMove = function(e2) {
  8642. moved = moved || Math.abs(event.clientX - e2.clientX) + Math.abs(event.clientY - e2.clientY) >= 10;
  8643. };
  8644. var dragStart = function () { return moved = true; };
  8645. // Let the drag handler handle this.
  8646. if (webkit) { display.scroller.draggable = true; }
  8647. cm.state.draggingText = dragEnd;
  8648. dragEnd.copy = !behavior.moveOnDrag;
  8649. // IE's approach to draggable
  8650. if (display.scroller.dragDrop) { display.scroller.dragDrop(); }
  8651. on(document, "mouseup", dragEnd);
  8652. on(document, "mousemove", mouseMove);
  8653. on(display.scroller, "dragstart", dragStart);
  8654. on(display.scroller, "drop", dragEnd);
  8655. delayBlurEvent(cm);
  8656. setTimeout(function () { return display.input.focus(); }, 20);
  8657. }
  8658. function rangeForUnit(cm, pos, unit) {
  8659. if (unit == "char") { return new Range(pos, pos) }
  8660. if (unit == "word") { return cm.findWordAt(pos) }
  8661. if (unit == "line") { return new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))) }
  8662. var result = unit(cm, pos);
  8663. return new Range(result.from, result.to)
  8664. }
  8665. // Normal selection, as opposed to text dragging.
  8666. function leftButtonSelect(cm, event, start, behavior) {
  8667. var display = cm.display, doc = cm.doc;
  8668. e_preventDefault(event);
  8669. var ourRange, ourIndex, startSel = doc.sel, ranges = startSel.ranges;
  8670. if (behavior.addNew && !behavior.extend) {
  8671. ourIndex = doc.sel.contains(start);
  8672. if (ourIndex > -1)
  8673. { ourRange = ranges[ourIndex]; }
  8674. else
  8675. { ourRange = new Range(start, start); }
  8676. } else {
  8677. ourRange = doc.sel.primary();
  8678. ourIndex = doc.sel.primIndex;
  8679. }
  8680. if (behavior.unit == "rectangle") {
  8681. if (!behavior.addNew) { ourRange = new Range(start, start); }
  8682. start = posFromMouse(cm, event, true, true);
  8683. ourIndex = -1;
  8684. } else {
  8685. var range$$1 = rangeForUnit(cm, start, behavior.unit);
  8686. if (behavior.extend)
  8687. { ourRange = extendRange(ourRange, range$$1.anchor, range$$1.head, behavior.extend); }
  8688. else
  8689. { ourRange = range$$1; }
  8690. }
  8691. if (!behavior.addNew) {
  8692. ourIndex = 0;
  8693. setSelection(doc, new Selection([ourRange], 0), sel_mouse);
  8694. startSel = doc.sel;
  8695. } else if (ourIndex == -1) {
  8696. ourIndex = ranges.length;
  8697. setSelection(doc, normalizeSelection(ranges.concat([ourRange]), ourIndex),
  8698. {scroll: false, origin: "*mouse"});
  8699. } else if (ranges.length > 1 && ranges[ourIndex].empty() && behavior.unit == "char" && !behavior.extend) {
  8700. setSelection(doc, normalizeSelection(ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0),
  8701. {scroll: false, origin: "*mouse"});
  8702. startSel = doc.sel;
  8703. } else {
  8704. replaceOneSelection(doc, ourIndex, ourRange, sel_mouse);
  8705. }
  8706. var lastPos = start;
  8707. function extendTo(pos) {
  8708. if (cmp(lastPos, pos) == 0) { return }
  8709. lastPos = pos;
  8710. if (behavior.unit == "rectangle") {
  8711. var ranges = [], tabSize = cm.options.tabSize;
  8712. var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize);
  8713. var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize);
  8714. var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol);
  8715. for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line));
  8716. line <= end; line++) {
  8717. var text = getLine(doc, line).text, leftPos = findColumn(text, left, tabSize);
  8718. if (left == right)
  8719. { ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos))); }
  8720. else if (text.length > leftPos)
  8721. { ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize)))); }
  8722. }
  8723. if (!ranges.length) { ranges.push(new Range(start, start)); }
  8724. setSelection(doc, normalizeSelection(startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex),
  8725. {origin: "*mouse", scroll: false});
  8726. cm.scrollIntoView(pos);
  8727. } else {
  8728. var oldRange = ourRange;
  8729. var range$$1 = rangeForUnit(cm, pos, behavior.unit);
  8730. var anchor = oldRange.anchor, head;
  8731. if (cmp(range$$1.anchor, anchor) > 0) {
  8732. head = range$$1.head;
  8733. anchor = minPos(oldRange.from(), range$$1.anchor);
  8734. } else {
  8735. head = range$$1.anchor;
  8736. anchor = maxPos(oldRange.to(), range$$1.head);
  8737. }
  8738. var ranges$1 = startSel.ranges.slice(0);
  8739. ranges$1[ourIndex] = bidiSimplify(cm, new Range(clipPos(doc, anchor), head));
  8740. setSelection(doc, normalizeSelection(ranges$1, ourIndex), sel_mouse);
  8741. }
  8742. }
  8743. var editorSize = display.wrapper.getBoundingClientRect();
  8744. // Used to ensure timeout re-tries don't fire when another extend
  8745. // happened in the meantime (clearTimeout isn't reliable -- at
  8746. // least on Chrome, the timeouts still happen even when cleared,
  8747. // if the clear happens after their scheduled firing time).
  8748. var counter = 0;
  8749. function extend(e) {
  8750. var curCount = ++counter;
  8751. var cur = posFromMouse(cm, e, true, behavior.unit == "rectangle");
  8752. if (!cur) { return }
  8753. if (cmp(cur, lastPos) != 0) {
  8754. cm.curOp.focus = activeElt();
  8755. extendTo(cur);
  8756. var visible = visibleLines(display, doc);
  8757. if (cur.line >= visible.to || cur.line < visible.from)
  8758. { setTimeout(operation(cm, function () {if (counter == curCount) { extend(e); }}), 150); }
  8759. } else {
  8760. var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0;
  8761. if (outside) { setTimeout(operation(cm, function () {
  8762. if (counter != curCount) { return }
  8763. display.scroller.scrollTop += outside;
  8764. extend(e);
  8765. }), 50); }
  8766. }
  8767. }
  8768. function done(e) {
  8769. cm.state.selectingText = false;
  8770. counter = Infinity;
  8771. e_preventDefault(e);
  8772. display.input.focus();
  8773. off(document, "mousemove", move);
  8774. off(document, "mouseup", up);
  8775. doc.history.lastSelOrigin = null;
  8776. }
  8777. var move = operation(cm, function (e) {
  8778. if (!e_button(e)) { done(e); }
  8779. else { extend(e); }
  8780. });
  8781. var up = operation(cm, done);
  8782. cm.state.selectingText = up;
  8783. on(document, "mousemove", move);
  8784. on(document, "mouseup", up);
  8785. }
  8786. // Used when mouse-selecting to adjust the anchor to the proper side
  8787. // of a bidi jump depending on the visual position of the head.
  8788. function bidiSimplify(cm, range$$1) {
  8789. var anchor = range$$1.anchor;
  8790. var head = range$$1.head;
  8791. var anchorLine = getLine(cm.doc, anchor.line);
  8792. if (cmp(anchor, head) == 0 && anchor.sticky == head.sticky) { return range$$1 }
  8793. var order = getOrder(anchorLine);
  8794. if (!order) { return range$$1 }
  8795. var index = getBidiPartAt(order, anchor.ch, anchor.sticky), part = order[index];
  8796. if (part.from != anchor.ch && part.to != anchor.ch) { return range$$1 }
  8797. var boundary = index + ((part.from == anchor.ch) == (part.level != 1) ? 0 : 1);
  8798. if (boundary == 0 || boundary == order.length) { return range$$1 }
  8799. // Compute the relative visual position of the head compared to the
  8800. // anchor (<0 is to the left, >0 to the right)
  8801. var leftSide;
  8802. if (head.line != anchor.line) {
  8803. leftSide = (head.line - anchor.line) * (cm.doc.direction == "ltr" ? 1 : -1) > 0;
  8804. } else {
  8805. var headIndex = getBidiPartAt(order, head.ch, head.sticky);
  8806. var dir = headIndex - index || (head.ch - anchor.ch) * (part.level == 1 ? -1 : 1);
  8807. if (headIndex == boundary - 1 || headIndex == boundary)
  8808. { leftSide = dir < 0; }
  8809. else
  8810. { leftSide = dir > 0; }
  8811. }
  8812. var usePart = order[boundary + (leftSide ? -1 : 0)];
  8813. var from = leftSide == (usePart.level == 1);
  8814. var ch = from ? usePart.from : usePart.to, sticky = from ? "after" : "before";
  8815. return anchor.ch == ch && anchor.sticky == sticky ? range$$1 : new Range(new Pos(anchor.line, ch, sticky), head)
  8816. }
  8817. // Determines whether an event happened in the gutter, and fires the
  8818. // handlers for the corresponding event.
  8819. function gutterEvent(cm, e, type, prevent) {
  8820. var mX, mY;
  8821. if (e.touches) {
  8822. mX = e.touches[0].clientX;
  8823. mY = e.touches[0].clientY;
  8824. } else {
  8825. try { mX = e.clientX; mY = e.clientY; }
  8826. catch(e) { return false }
  8827. }
  8828. if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) { return false }
  8829. if (prevent) { e_preventDefault(e); }
  8830. var display = cm.display;
  8831. var lineBox = display.lineDiv.getBoundingClientRect();
  8832. if (mY > lineBox.bottom || !hasHandler(cm, type)) { return e_defaultPrevented(e) }
  8833. mY -= lineBox.top - display.viewOffset;
  8834. for (var i = 0; i < cm.options.gutters.length; ++i) {
  8835. var g = display.gutters.childNodes[i];
  8836. if (g && g.getBoundingClientRect().right >= mX) {
  8837. var line = lineAtHeight(cm.doc, mY);
  8838. var gutter = cm.options.gutters[i];
  8839. signal(cm, type, cm, line, gutter, e);
  8840. return e_defaultPrevented(e)
  8841. }
  8842. }
  8843. }
  8844. function clickInGutter(cm, e) {
  8845. return gutterEvent(cm, e, "gutterClick", true)
  8846. }
  8847. // CONTEXT MENU HANDLING
  8848. // To make the context menu work, we need to briefly unhide the
  8849. // textarea (making it as unobtrusive as possible) to let the
  8850. // right-click take effect on it.
  8851. function onContextMenu(cm, e) {
  8852. if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) { return }
  8853. if (signalDOMEvent(cm, e, "contextmenu")) { return }
  8854. cm.display.input.onContextMenu(e);
  8855. }
  8856. function contextMenuInGutter(cm, e) {
  8857. if (!hasHandler(cm, "gutterContextMenu")) { return false }
  8858. return gutterEvent(cm, e, "gutterContextMenu", false)
  8859. }
  8860. function themeChanged(cm) {
  8861. cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") +
  8862. cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-");
  8863. clearCaches(cm);
  8864. }
  8865. var Init = {toString: function(){return "CodeMirror.Init"}};
  8866. var defaults = {};
  8867. var optionHandlers = {};
  8868. function defineOptions(CodeMirror) {
  8869. var optionHandlers = CodeMirror.optionHandlers;
  8870. function option(name, deflt, handle, notOnInit) {
  8871. CodeMirror.defaults[name] = deflt;
  8872. if (handle) { optionHandlers[name] =
  8873. notOnInit ? function (cm, val, old) {if (old != Init) { handle(cm, val, old); }} : handle; }
  8874. }
  8875. CodeMirror.defineOption = option;
  8876. // Passed to option handlers when there is no old value.
  8877. CodeMirror.Init = Init;
  8878. // These two are, on init, called from the constructor because they
  8879. // have to be initialized before the editor can start at all.
  8880. option("value", "", function (cm, val) { return cm.setValue(val); }, true);
  8881. option("mode", null, function (cm, val) {
  8882. cm.doc.modeOption = val;
  8883. loadMode(cm);
  8884. }, true);
  8885. option("indentUnit", 2, loadMode, true);
  8886. option("indentWithTabs", false);
  8887. option("smartIndent", true);
  8888. option("tabSize", 4, function (cm) {
  8889. resetModeState(cm);
  8890. clearCaches(cm);
  8891. regChange(cm);
  8892. }, true);
  8893. option("lineSeparator", null, function (cm, val) {
  8894. cm.doc.lineSep = val;
  8895. if (!val) { return }
  8896. var newBreaks = [], lineNo = cm.doc.first;
  8897. cm.doc.iter(function (line) {
  8898. for (var pos = 0;;) {
  8899. var found = line.text.indexOf(val, pos);
  8900. if (found == -1) { break }
  8901. pos = found + val.length;
  8902. newBreaks.push(Pos(lineNo, found));
  8903. }
  8904. lineNo++;
  8905. });
  8906. for (var i = newBreaks.length - 1; i >= 0; i--)
  8907. { replaceRange(cm.doc, val, newBreaks[i], Pos(newBreaks[i].line, newBreaks[i].ch + val.length)); }
  8908. });
  8909. option("specialChars", /[\u0000-\u001f\u007f-\u009f\u00ad\u061c\u200b-\u200f\u2028\u2029\ufeff]/g, function (cm, val, old) {
  8910. cm.state.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g");
  8911. if (old != Init) { cm.refresh(); }
  8912. });
  8913. option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function (cm) { return cm.refresh(); }, true);
  8914. option("electricChars", true);
  8915. option("inputStyle", mobile ? "contenteditable" : "textarea", function () {
  8916. throw new Error("inputStyle can not (yet) be changed in a running editor") // FIXME
  8917. }, true);
  8918. option("spellcheck", false, function (cm, val) { return cm.getInputField().spellcheck = val; }, true);
  8919. option("rtlMoveVisually", !windows);
  8920. option("wholeLineUpdateBefore", true);
  8921. option("theme", "default", function (cm) {
  8922. themeChanged(cm);
  8923. guttersChanged(cm);
  8924. }, true);
  8925. option("keyMap", "default", function (cm, val, old) {
  8926. var next = getKeyMap(val);
  8927. var prev = old != Init && getKeyMap(old);
  8928. if (prev && prev.detach) { prev.detach(cm, next); }
  8929. if (next.attach) { next.attach(cm, prev || null); }
  8930. });
  8931. option("extraKeys", null);
  8932. option("configureMouse", null);
  8933. option("lineWrapping", false, wrappingChanged, true);
  8934. option("gutters", [], function (cm) {
  8935. setGuttersForLineNumbers(cm.options);
  8936. guttersChanged(cm);
  8937. }, true);
  8938. option("fixedGutter", true, function (cm, val) {
  8939. cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0";
  8940. cm.refresh();
  8941. }, true);
  8942. option("coverGutterNextToScrollbar", false, function (cm) { return updateScrollbars(cm); }, true);
  8943. option("scrollbarStyle", "native", function (cm) {
  8944. initScrollbars(cm);
  8945. updateScrollbars(cm);
  8946. cm.display.scrollbars.setScrollTop(cm.doc.scrollTop);
  8947. cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft);
  8948. }, true);
  8949. option("lineNumbers", false, function (cm) {
  8950. setGuttersForLineNumbers(cm.options);
  8951. guttersChanged(cm);
  8952. }, true);
  8953. option("firstLineNumber", 1, guttersChanged, true);
  8954. option("lineNumberFormatter", function (integer) { return integer; }, guttersChanged, true);
  8955. option("showCursorWhenSelecting", false, updateSelection, true);
  8956. option("resetSelectionOnContextMenu", true);
  8957. option("lineWiseCopyCut", true);
  8958. option("pasteLinesPerSelection", true);
  8959. option("readOnly", false, function (cm, val) {
  8960. if (val == "nocursor") {
  8961. onBlur(cm);
  8962. cm.display.input.blur();
  8963. }
  8964. cm.display.input.readOnlyChanged(val);
  8965. });
  8966. option("disableInput", false, function (cm, val) {if (!val) { cm.display.input.reset(); }}, true);
  8967. option("dragDrop", true, dragDropChanged);
  8968. option("allowDropFileTypes", null);
  8969. option("cursorBlinkRate", 530);
  8970. option("cursorScrollMargin", 0);
  8971. option("cursorHeight", 1, updateSelection, true);
  8972. option("singleCursorHeightPerLine", true, updateSelection, true);
  8973. option("workTime", 100);
  8974. option("workDelay", 100);
  8975. option("flattenSpans", true, resetModeState, true);
  8976. option("addModeClass", false, resetModeState, true);
  8977. option("pollInterval", 100);
  8978. option("undoDepth", 200, function (cm, val) { return cm.doc.history.undoDepth = val; });
  8979. option("historyEventDelay", 1250);
  8980. option("viewportMargin", 10, function (cm) { return cm.refresh(); }, true);
  8981. option("maxHighlightLength", 10000, resetModeState, true);
  8982. option("moveInputWithCursor", true, function (cm, val) {
  8983. if (!val) { cm.display.input.resetPosition(); }
  8984. });
  8985. option("tabindex", null, function (cm, val) { return cm.display.input.getField().tabIndex = val || ""; });
  8986. option("autofocus", null);
  8987. option("direction", "ltr", function (cm, val) { return cm.doc.setDirection(val); }, true);
  8988. }
  8989. function guttersChanged(cm) {
  8990. updateGutters(cm);
  8991. regChange(cm);
  8992. alignHorizontally(cm);
  8993. }
  8994. function dragDropChanged(cm, value, old) {
  8995. var wasOn = old && old != Init;
  8996. if (!value != !wasOn) {
  8997. var funcs = cm.display.dragFunctions;
  8998. var toggle = value ? on : off;
  8999. toggle(cm.display.scroller, "dragstart", funcs.start);
  9000. toggle(cm.display.scroller, "dragenter", funcs.enter);
  9001. toggle(cm.display.scroller, "dragover", funcs.over);
  9002. toggle(cm.display.scroller, "dragleave", funcs.leave);
  9003. toggle(cm.display.scroller, "drop", funcs.drop);
  9004. }
  9005. }
  9006. function wrappingChanged(cm) {
  9007. if (cm.options.lineWrapping) {
  9008. addClass(cm.display.wrapper, "CodeMirror-wrap");
  9009. cm.display.sizer.style.minWidth = "";
  9010. cm.display.sizerWidth = null;
  9011. } else {
  9012. rmClass(cm.display.wrapper, "CodeMirror-wrap");
  9013. findMaxLine(cm);
  9014. }
  9015. estimateLineHeights(cm);
  9016. regChange(cm);
  9017. clearCaches(cm);
  9018. setTimeout(function () { return updateScrollbars(cm); }, 100);
  9019. }
  9020. // A CodeMirror instance represents an editor. This is the object
  9021. // that user code is usually dealing with.
  9022. function CodeMirror$1(place, options) {
  9023. var this$1 = this;
  9024. if (!(this instanceof CodeMirror$1)) { return new CodeMirror$1(place, options) }
  9025. this.options = options = options ? copyObj(options) : {};
  9026. // Determine effective options based on given values and defaults.
  9027. copyObj(defaults, options, false);
  9028. setGuttersForLineNumbers(options);
  9029. var doc = options.value;
  9030. if (typeof doc == "string") { doc = new Doc(doc, options.mode, null, options.lineSeparator, options.direction); }
  9031. this.doc = doc;
  9032. var input = new CodeMirror$1.inputStyles[options.inputStyle](this);
  9033. var display = this.display = new Display(place, doc, input);
  9034. display.wrapper.CodeMirror = this;
  9035. updateGutters(this);
  9036. themeChanged(this);
  9037. if (options.lineWrapping)
  9038. { this.display.wrapper.className += " CodeMirror-wrap"; }
  9039. initScrollbars(this);
  9040. this.state = {
  9041. keyMaps: [], // stores maps added by addKeyMap
  9042. overlays: [], // highlighting overlays, as added by addOverlay
  9043. modeGen: 0, // bumped when mode/overlay changes, used to invalidate highlighting info
  9044. overwrite: false,
  9045. delayingBlurEvent: false,
  9046. focused: false,
  9047. suppressEdits: false, // used to disable editing during key handlers when in readOnly mode
  9048. pasteIncoming: false, cutIncoming: false, // help recognize paste/cut edits in input.poll
  9049. selectingText: false,
  9050. draggingText: false,
  9051. highlight: new Delayed(), // stores highlight worker timeout
  9052. keySeq: null, // Unfinished key sequence
  9053. specialChars: null
  9054. };
  9055. if (options.autofocus && !mobile) { display.input.focus(); }
  9056. // Override magic textarea content restore that IE sometimes does
  9057. // on our hidden textarea on reload
  9058. if (ie && ie_version < 11) { setTimeout(function () { return this$1.display.input.reset(true); }, 20); }
  9059. registerEventHandlers(this);
  9060. ensureGlobalHandlers();
  9061. startOperation(this);
  9062. this.curOp.forceUpdate = true;
  9063. attachDoc(this, doc);
  9064. if ((options.autofocus && !mobile) || this.hasFocus())
  9065. { setTimeout(bind(onFocus, this), 20); }
  9066. else
  9067. { onBlur(this); }
  9068. for (var opt in optionHandlers) { if (optionHandlers.hasOwnProperty(opt))
  9069. { optionHandlers[opt](this$1, options[opt], Init); } }
  9070. maybeUpdateLineNumberWidth(this);
  9071. if (options.finishInit) { options.finishInit(this); }
  9072. for (var i = 0; i < initHooks.length; ++i) { initHooks[i](this$1); }
  9073. endOperation(this);
  9074. // Suppress optimizelegibility in Webkit, since it breaks text
  9075. // measuring on line wrapping boundaries.
  9076. if (webkit && options.lineWrapping &&
  9077. getComputedStyle(display.lineDiv).textRendering == "optimizelegibility")
  9078. { display.lineDiv.style.textRendering = "auto"; }
  9079. }
  9080. // The default configuration options.
  9081. CodeMirror$1.defaults = defaults;
  9082. // Functions to run when options are changed.
  9083. CodeMirror$1.optionHandlers = optionHandlers;
  9084. // Attach the necessary event handlers when initializing the editor
  9085. function registerEventHandlers(cm) {
  9086. var d = cm.display;
  9087. on(d.scroller, "mousedown", operation(cm, onMouseDown));
  9088. // Older IE's will not fire a second mousedown for a double click
  9089. if (ie && ie_version < 11)
  9090. { on(d.scroller, "dblclick", operation(cm, function (e) {
  9091. if (signalDOMEvent(cm, e)) { return }
  9092. var pos = posFromMouse(cm, e);
  9093. if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) { return }
  9094. e_preventDefault(e);
  9095. var word = cm.findWordAt(pos);
  9096. extendSelection(cm.doc, word.anchor, word.head);
  9097. })); }
  9098. else
  9099. { on(d.scroller, "dblclick", function (e) { return signalDOMEvent(cm, e) || e_preventDefault(e); }); }
  9100. // Some browsers fire contextmenu *after* opening the menu, at
  9101. // which point we can't mess with it anymore. Context menu is
  9102. // handled in onMouseDown for these browsers.
  9103. if (!captureRightClick) { on(d.scroller, "contextmenu", function (e) { return onContextMenu(cm, e); }); }
  9104. // Used to suppress mouse event handling when a touch happens
  9105. var touchFinished, prevTouch = {end: 0};
  9106. function finishTouch() {
  9107. if (d.activeTouch) {
  9108. touchFinished = setTimeout(function () { return d.activeTouch = null; }, 1000);
  9109. prevTouch = d.activeTouch;
  9110. prevTouch.end = +new Date;
  9111. }
  9112. }
  9113. function isMouseLikeTouchEvent(e) {
  9114. if (e.touches.length != 1) { return false }
  9115. var touch = e.touches[0];
  9116. return touch.radiusX <= 1 && touch.radiusY <= 1
  9117. }
  9118. function farAway(touch, other) {
  9119. if (other.left == null) { return true }
  9120. var dx = other.left - touch.left, dy = other.top - touch.top;
  9121. return dx * dx + dy * dy > 20 * 20
  9122. }
  9123. on(d.scroller, "touchstart", function (e) {
  9124. if (!signalDOMEvent(cm, e) && !isMouseLikeTouchEvent(e) && !clickInGutter(cm, e)) {
  9125. d.input.ensurePolled();
  9126. clearTimeout(touchFinished);
  9127. var now = +new Date;
  9128. d.activeTouch = {start: now, moved: false,
  9129. prev: now - prevTouch.end <= 300 ? prevTouch : null};
  9130. if (e.touches.length == 1) {
  9131. d.activeTouch.left = e.touches[0].pageX;
  9132. d.activeTouch.top = e.touches[0].pageY;
  9133. }
  9134. }
  9135. });
  9136. on(d.scroller, "touchmove", function () {
  9137. if (d.activeTouch) { d.activeTouch.moved = true; }
  9138. });
  9139. on(d.scroller, "touchend", function (e) {
  9140. var touch = d.activeTouch;
  9141. if (touch && !eventInWidget(d, e) && touch.left != null &&
  9142. !touch.moved && new Date - touch.start < 300) {
  9143. var pos = cm.coordsChar(d.activeTouch, "page"), range;
  9144. if (!touch.prev || farAway(touch, touch.prev)) // Single tap
  9145. { range = new Range(pos, pos); }
  9146. else if (!touch.prev.prev || farAway(touch, touch.prev.prev)) // Double tap
  9147. { range = cm.findWordAt(pos); }
  9148. else // Triple tap
  9149. { range = new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))); }
  9150. cm.setSelection(range.anchor, range.head);
  9151. cm.focus();
  9152. e_preventDefault(e);
  9153. }
  9154. finishTouch();
  9155. });
  9156. on(d.scroller, "touchcancel", finishTouch);
  9157. // Sync scrolling between fake scrollbars and real scrollable
  9158. // area, ensure viewport is updated when scrolling.
  9159. on(d.scroller, "scroll", function () {
  9160. if (d.scroller.clientHeight) {
  9161. updateScrollTop(cm, d.scroller.scrollTop);
  9162. setScrollLeft(cm, d.scroller.scrollLeft, true);
  9163. signal(cm, "scroll", cm);
  9164. }
  9165. });
  9166. // Listen to wheel events in order to try and update the viewport on time.
  9167. on(d.scroller, "mousewheel", function (e) { return onScrollWheel(cm, e); });
  9168. on(d.scroller, "DOMMouseScroll", function (e) { return onScrollWheel(cm, e); });
  9169. // Prevent wrapper from ever scrolling
  9170. on(d.wrapper, "scroll", function () { return d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; });
  9171. d.dragFunctions = {
  9172. enter: function (e) {if (!signalDOMEvent(cm, e)) { e_stop(e); }},
  9173. over: function (e) {if (!signalDOMEvent(cm, e)) { onDragOver(cm, e); e_stop(e); }},
  9174. start: function (e) { return onDragStart(cm, e); },
  9175. drop: operation(cm, onDrop),
  9176. leave: function (e) {if (!signalDOMEvent(cm, e)) { clearDragCursor(cm); }}
  9177. };
  9178. var inp = d.input.getField();
  9179. on(inp, "keyup", function (e) { return onKeyUp.call(cm, e); });
  9180. on(inp, "keydown", operation(cm, onKeyDown));
  9181. on(inp, "keypress", operation(cm, onKeyPress));
  9182. on(inp, "focus", function (e) { return onFocus(cm, e); });
  9183. on(inp, "blur", function (e) { return onBlur(cm, e); });
  9184. }
  9185. var initHooks = [];
  9186. CodeMirror$1.defineInitHook = function (f) { return initHooks.push(f); };
  9187. // Indent the given line. The how parameter can be "smart",
  9188. // "add"/null, "subtract", or "prev". When aggressive is false
  9189. // (typically set to true for forced single-line indents), empty
  9190. // lines are not indented, and places where the mode returns Pass
  9191. // are left alone.
  9192. function indentLine(cm, n, how, aggressive) {
  9193. var doc = cm.doc, state;
  9194. if (how == null) { how = "add"; }
  9195. if (how == "smart") {
  9196. // Fall back to "prev" when the mode doesn't have an indentation
  9197. // method.
  9198. if (!doc.mode.indent) { how = "prev"; }
  9199. else { state = getContextBefore(cm, n).state; }
  9200. }
  9201. var tabSize = cm.options.tabSize;
  9202. var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize);
  9203. if (line.stateAfter) { line.stateAfter = null; }
  9204. var curSpaceString = line.text.match(/^\s*/)[0], indentation;
  9205. if (!aggressive && !/\S/.test(line.text)) {
  9206. indentation = 0;
  9207. how = "not";
  9208. } else if (how == "smart") {
  9209. indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text);
  9210. if (indentation == Pass || indentation > 150) {
  9211. if (!aggressive) { return }
  9212. how = "prev";
  9213. }
  9214. }
  9215. if (how == "prev") {
  9216. if (n > doc.first) { indentation = countColumn(getLine(doc, n-1).text, null, tabSize); }
  9217. else { indentation = 0; }
  9218. } else if (how == "add") {
  9219. indentation = curSpace + cm.options.indentUnit;
  9220. } else if (how == "subtract") {
  9221. indentation = curSpace - cm.options.indentUnit;
  9222. } else if (typeof how == "number") {
  9223. indentation = curSpace + how;
  9224. }
  9225. indentation = Math.max(0, indentation);
  9226. var indentString = "", pos = 0;
  9227. if (cm.options.indentWithTabs)
  9228. { for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";} }
  9229. if (pos < indentation) { indentString += spaceStr(indentation - pos); }
  9230. if (indentString != curSpaceString) {
  9231. replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input");
  9232. line.stateAfter = null;
  9233. return true
  9234. } else {
  9235. // Ensure that, if the cursor was in the whitespace at the start
  9236. // of the line, it is moved to the end of that space.
  9237. for (var i$1 = 0; i$1 < doc.sel.ranges.length; i$1++) {
  9238. var range = doc.sel.ranges[i$1];
  9239. if (range.head.line == n && range.head.ch < curSpaceString.length) {
  9240. var pos$1 = Pos(n, curSpaceString.length);
  9241. replaceOneSelection(doc, i$1, new Range(pos$1, pos$1));
  9242. break
  9243. }
  9244. }
  9245. }
  9246. }
  9247. // This will be set to a {lineWise: bool, text: [string]} object, so
  9248. // that, when pasting, we know what kind of selections the copied
  9249. // text was made out of.
  9250. var lastCopied = null;
  9251. function setLastCopied(newLastCopied) {
  9252. lastCopied = newLastCopied;
  9253. }
  9254. function applyTextInput(cm, inserted, deleted, sel, origin) {
  9255. var doc = cm.doc;
  9256. cm.display.shift = false;
  9257. if (!sel) { sel = doc.sel; }
  9258. var paste = cm.state.pasteIncoming || origin == "paste";
  9259. var textLines = splitLinesAuto(inserted), multiPaste = null;
  9260. // When pasing N lines into N selections, insert one line per selection
  9261. if (paste && sel.ranges.length > 1) {
  9262. if (lastCopied && lastCopied.text.join("\n") == inserted) {
  9263. if (sel.ranges.length % lastCopied.text.length == 0) {
  9264. multiPaste = [];
  9265. for (var i = 0; i < lastCopied.text.length; i++)
  9266. { multiPaste.push(doc.splitLines(lastCopied.text[i])); }
  9267. }
  9268. } else if (textLines.length == sel.ranges.length && cm.options.pasteLinesPerSelection) {
  9269. multiPaste = map(textLines, function (l) { return [l]; });
  9270. }
  9271. }
  9272. var updateInput;
  9273. // Normal behavior is to insert the new text into every selection
  9274. for (var i$1 = sel.ranges.length - 1; i$1 >= 0; i$1--) {
  9275. var range$$1 = sel.ranges[i$1];
  9276. var from = range$$1.from(), to = range$$1.to();
  9277. if (range$$1.empty()) {
  9278. if (deleted && deleted > 0) // Handle deletion
  9279. { from = Pos(from.line, from.ch - deleted); }
  9280. else if (cm.state.overwrite && !paste) // Handle overwrite
  9281. { to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length)); }
  9282. else if (lastCopied && lastCopied.lineWise && lastCopied.text.join("\n") == inserted)
  9283. { from = to = Pos(from.line, 0); }
  9284. }
  9285. updateInput = cm.curOp.updateInput;
  9286. var changeEvent = {from: from, to: to, text: multiPaste ? multiPaste[i$1 % multiPaste.length] : textLines,
  9287. origin: origin || (paste ? "paste" : cm.state.cutIncoming ? "cut" : "+input")};
  9288. makeChange(cm.doc, changeEvent);
  9289. signalLater(cm, "inputRead", cm, changeEvent);
  9290. }
  9291. if (inserted && !paste)
  9292. { triggerElectric(cm, inserted); }
  9293. ensureCursorVisible(cm);
  9294. cm.curOp.updateInput = updateInput;
  9295. cm.curOp.typing = true;
  9296. cm.state.pasteIncoming = cm.state.cutIncoming = false;
  9297. }
  9298. function handlePaste(e, cm) {
  9299. var pasted = e.clipboardData && e.clipboardData.getData("Text");
  9300. if (pasted) {
  9301. e.preventDefault();
  9302. if (!cm.isReadOnly() && !cm.options.disableInput)
  9303. { runInOp(cm, function () { return applyTextInput(cm, pasted, 0, null, "paste"); }); }
  9304. return true
  9305. }
  9306. }
  9307. function triggerElectric(cm, inserted) {
  9308. // When an 'electric' character is inserted, immediately trigger a reindent
  9309. if (!cm.options.electricChars || !cm.options.smartIndent) { return }
  9310. var sel = cm.doc.sel;
  9311. for (var i = sel.ranges.length - 1; i >= 0; i--) {
  9312. var range$$1 = sel.ranges[i];
  9313. if (range$$1.head.ch > 100 || (i && sel.ranges[i - 1].head.line == range$$1.head.line)) { continue }
  9314. var mode = cm.getModeAt(range$$1.head);
  9315. var indented = false;
  9316. if (mode.electricChars) {
  9317. for (var j = 0; j < mode.electricChars.length; j++)
  9318. { if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) {
  9319. indented = indentLine(cm, range$$1.head.line, "smart");
  9320. break
  9321. } }
  9322. } else if (mode.electricInput) {
  9323. if (mode.electricInput.test(getLine(cm.doc, range$$1.head.line).text.slice(0, range$$1.head.ch)))
  9324. { indented = indentLine(cm, range$$1.head.line, "smart"); }
  9325. }
  9326. if (indented) { signalLater(cm, "electricInput", cm, range$$1.head.line); }
  9327. }
  9328. }
  9329. function copyableRanges(cm) {
  9330. var text = [], ranges = [];
  9331. for (var i = 0; i < cm.doc.sel.ranges.length; i++) {
  9332. var line = cm.doc.sel.ranges[i].head.line;
  9333. var lineRange = {anchor: Pos(line, 0), head: Pos(line + 1, 0)};
  9334. ranges.push(lineRange);
  9335. text.push(cm.getRange(lineRange.anchor, lineRange.head));
  9336. }
  9337. return {text: text, ranges: ranges}
  9338. }
  9339. function disableBrowserMagic(field, spellcheck) {
  9340. field.setAttribute("autocorrect", "off");
  9341. field.setAttribute("autocapitalize", "off");
  9342. field.setAttribute("spellcheck", !!spellcheck);
  9343. }
  9344. function hiddenTextarea() {
  9345. var te = elt("textarea", null, null, "position: absolute; bottom: -1em; padding: 0; width: 1px; height: 1em; outline: none");
  9346. var div = elt("div", [te], null, "overflow: hidden; position: relative; width: 3px; height: 0px;");
  9347. // The textarea is kept positioned near the cursor to prevent the
  9348. // fact that it'll be scrolled into view on input from scrolling
  9349. // our fake cursor out of view. On webkit, when wrap=off, paste is
  9350. // very slow. So make the area wide instead.
  9351. if (webkit) { te.style.width = "1000px"; }
  9352. else { te.setAttribute("wrap", "off"); }
  9353. // If border: 0; -- iOS fails to open keyboard (issue #1287)
  9354. if (ios) { te.style.border = "1px solid black"; }
  9355. disableBrowserMagic(te);
  9356. return div
  9357. }
  9358. // The publicly visible API. Note that methodOp(f) means
  9359. // 'wrap f in an operation, performed on its `this` parameter'.
  9360. // This is not the complete set of editor methods. Most of the
  9361. // methods defined on the Doc type are also injected into
  9362. // CodeMirror.prototype, for backwards compatibility and
  9363. // convenience.
  9364. var addEditorMethods = function(CodeMirror) {
  9365. var optionHandlers = CodeMirror.optionHandlers;
  9366. var helpers = CodeMirror.helpers = {};
  9367. CodeMirror.prototype = {
  9368. constructor: CodeMirror,
  9369. focus: function(){window.focus(); this.display.input.focus();},
  9370. setOption: function(option, value) {
  9371. var options = this.options, old = options[option];
  9372. if (options[option] == value && option != "mode") { return }
  9373. options[option] = value;
  9374. if (optionHandlers.hasOwnProperty(option))
  9375. { operation(this, optionHandlers[option])(this, value, old); }
  9376. signal(this, "optionChange", this, option);
  9377. },
  9378. getOption: function(option) {return this.options[option]},
  9379. getDoc: function() {return this.doc},
  9380. addKeyMap: function(map$$1, bottom) {
  9381. this.state.keyMaps[bottom ? "push" : "unshift"](getKeyMap(map$$1));
  9382. },
  9383. removeKeyMap: function(map$$1) {
  9384. var maps = this.state.keyMaps;
  9385. for (var i = 0; i < maps.length; ++i)
  9386. { if (maps[i] == map$$1 || maps[i].name == map$$1) {
  9387. maps.splice(i, 1);
  9388. return true
  9389. } }
  9390. },
  9391. addOverlay: methodOp(function(spec, options) {
  9392. var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec);
  9393. if (mode.startState) { throw new Error("Overlays may not be stateful.") }
  9394. insertSorted(this.state.overlays,
  9395. {mode: mode, modeSpec: spec, opaque: options && options.opaque,
  9396. priority: (options && options.priority) || 0},
  9397. function (overlay) { return overlay.priority; });
  9398. this.state.modeGen++;
  9399. regChange(this);
  9400. }),
  9401. removeOverlay: methodOp(function(spec) {
  9402. var this$1 = this;
  9403. var overlays = this.state.overlays;
  9404. for (var i = 0; i < overlays.length; ++i) {
  9405. var cur = overlays[i].modeSpec;
  9406. if (cur == spec || typeof spec == "string" && cur.name == spec) {
  9407. overlays.splice(i, 1);
  9408. this$1.state.modeGen++;
  9409. regChange(this$1);
  9410. return
  9411. }
  9412. }
  9413. }),
  9414. indentLine: methodOp(function(n, dir, aggressive) {
  9415. if (typeof dir != "string" && typeof dir != "number") {
  9416. if (dir == null) { dir = this.options.smartIndent ? "smart" : "prev"; }
  9417. else { dir = dir ? "add" : "subtract"; }
  9418. }
  9419. if (isLine(this.doc, n)) { indentLine(this, n, dir, aggressive); }
  9420. }),
  9421. indentSelection: methodOp(function(how) {
  9422. var this$1 = this;
  9423. var ranges = this.doc.sel.ranges, end = -1;
  9424. for (var i = 0; i < ranges.length; i++) {
  9425. var range$$1 = ranges[i];
  9426. if (!range$$1.empty()) {
  9427. var from = range$$1.from(), to = range$$1.to();
  9428. var start = Math.max(end, from.line);
  9429. end = Math.min(this$1.lastLine(), to.line - (to.ch ? 0 : 1)) + 1;
  9430. for (var j = start; j < end; ++j)
  9431. { indentLine(this$1, j, how); }
  9432. var newRanges = this$1.doc.sel.ranges;
  9433. if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i].from().ch > 0)
  9434. { replaceOneSelection(this$1.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll); }
  9435. } else if (range$$1.head.line > end) {
  9436. indentLine(this$1, range$$1.head.line, how, true);
  9437. end = range$$1.head.line;
  9438. if (i == this$1.doc.sel.primIndex) { ensureCursorVisible(this$1); }
  9439. }
  9440. }
  9441. }),
  9442. // Fetch the parser token for a given character. Useful for hacks
  9443. // that want to inspect the mode state (say, for completion).
  9444. getTokenAt: function(pos, precise) {
  9445. return takeToken(this, pos, precise)
  9446. },
  9447. getLineTokens: function(line, precise) {
  9448. return takeToken(this, Pos(line), precise, true)
  9449. },
  9450. getTokenTypeAt: function(pos) {
  9451. pos = clipPos(this.doc, pos);
  9452. var styles = getLineStyles(this, getLine(this.doc, pos.line));
  9453. var before = 0, after = (styles.length - 1) / 2, ch = pos.ch;
  9454. var type;
  9455. if (ch == 0) { type = styles[2]; }
  9456. else { for (;;) {
  9457. var mid = (before + after) >> 1;
  9458. if ((mid ? styles[mid * 2 - 1] : 0) >= ch) { after = mid; }
  9459. else if (styles[mid * 2 + 1] < ch) { before = mid + 1; }
  9460. else { type = styles[mid * 2 + 2]; break }
  9461. } }
  9462. var cut = type ? type.indexOf("overlay ") : -1;
  9463. return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1)
  9464. },
  9465. getModeAt: function(pos) {
  9466. var mode = this.doc.mode;
  9467. if (!mode.innerMode) { return mode }
  9468. return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode
  9469. },
  9470. getHelper: function(pos, type) {
  9471. return this.getHelpers(pos, type)[0]
  9472. },
  9473. getHelpers: function(pos, type) {
  9474. var this$1 = this;
  9475. var found = [];
  9476. if (!helpers.hasOwnProperty(type)) { return found }
  9477. var help = helpers[type], mode = this.getModeAt(pos);
  9478. if (typeof mode[type] == "string") {
  9479. if (help[mode[type]]) { found.push(help[mode[type]]); }
  9480. } else if (mode[type]) {
  9481. for (var i = 0; i < mode[type].length; i++) {
  9482. var val = help[mode[type][i]];
  9483. if (val) { found.push(val); }
  9484. }
  9485. } else if (mode.helperType && help[mode.helperType]) {
  9486. found.push(help[mode.helperType]);
  9487. } else if (help[mode.name]) {
  9488. found.push(help[mode.name]);
  9489. }
  9490. for (var i$1 = 0; i$1 < help._global.length; i$1++) {
  9491. var cur = help._global[i$1];
  9492. if (cur.pred(mode, this$1) && indexOf(found, cur.val) == -1)
  9493. { found.push(cur.val); }
  9494. }
  9495. return found
  9496. },
  9497. getStateAfter: function(line, precise) {
  9498. var doc = this.doc;
  9499. line = clipLine(doc, line == null ? doc.first + doc.size - 1: line);
  9500. return getContextBefore(this, line + 1, precise).state
  9501. },
  9502. cursorCoords: function(start, mode) {
  9503. var pos, range$$1 = this.doc.sel.primary();
  9504. if (start == null) { pos = range$$1.head; }
  9505. else if (typeof start == "object") { pos = clipPos(this.doc, start); }
  9506. else { pos = start ? range$$1.from() : range$$1.to(); }
  9507. return cursorCoords(this, pos, mode || "page")
  9508. },
  9509. charCoords: function(pos, mode) {
  9510. return charCoords(this, clipPos(this.doc, pos), mode || "page")
  9511. },
  9512. coordsChar: function(coords, mode) {
  9513. coords = fromCoordSystem(this, coords, mode || "page");
  9514. return coordsChar(this, coords.left, coords.top)
  9515. },
  9516. lineAtHeight: function(height, mode) {
  9517. height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top;
  9518. return lineAtHeight(this.doc, height + this.display.viewOffset)
  9519. },
  9520. heightAtLine: function(line, mode, includeWidgets) {
  9521. var end = false, lineObj;
  9522. if (typeof line == "number") {
  9523. var last = this.doc.first + this.doc.size - 1;
  9524. if (line < this.doc.first) { line = this.doc.first; }
  9525. else if (line > last) { line = last; end = true; }
  9526. lineObj = getLine(this.doc, line);
  9527. } else {
  9528. lineObj = line;
  9529. }
  9530. return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || "page", includeWidgets || end).top +
  9531. (end ? this.doc.height - heightAtLine(lineObj) : 0)
  9532. },
  9533. defaultTextHeight: function() { return textHeight(this.display) },
  9534. defaultCharWidth: function() { return charWidth(this.display) },
  9535. getViewport: function() { return {from: this.display.viewFrom, to: this.display.viewTo}},
  9536. addWidget: function(pos, node, scroll, vert, horiz) {
  9537. var display = this.display;
  9538. pos = cursorCoords(this, clipPos(this.doc, pos));
  9539. var top = pos.bottom, left = pos.left;
  9540. node.style.position = "absolute";
  9541. node.setAttribute("cm-ignore-events", "true");
  9542. this.display.input.setUneditable(node);
  9543. display.sizer.appendChild(node);
  9544. if (vert == "over") {
  9545. top = pos.top;
  9546. } else if (vert == "above" || vert == "near") {
  9547. var vspace = Math.max(display.wrapper.clientHeight, this.doc.height),
  9548. hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth);
  9549. // Default to positioning above (if specified and possible); otherwise default to positioning below
  9550. if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight)
  9551. { top = pos.top - node.offsetHeight; }
  9552. else if (pos.bottom + node.offsetHeight <= vspace)
  9553. { top = pos.bottom; }
  9554. if (left + node.offsetWidth > hspace)
  9555. { left = hspace - node.offsetWidth; }
  9556. }
  9557. node.style.top = top + "px";
  9558. node.style.left = node.style.right = "";
  9559. if (horiz == "right") {
  9560. left = display.sizer.clientWidth - node.offsetWidth;
  9561. node.style.right = "0px";
  9562. } else {
  9563. if (horiz == "left") { left = 0; }
  9564. else if (horiz == "middle") { left = (display.sizer.clientWidth - node.offsetWidth) / 2; }
  9565. node.style.left = left + "px";
  9566. }
  9567. if (scroll)
  9568. { scrollIntoView(this, {left: left, top: top, right: left + node.offsetWidth, bottom: top + node.offsetHeight}); }
  9569. },
  9570. triggerOnKeyDown: methodOp(onKeyDown),
  9571. triggerOnKeyPress: methodOp(onKeyPress),
  9572. triggerOnKeyUp: onKeyUp,
  9573. triggerOnMouseDown: methodOp(onMouseDown),
  9574. execCommand: function(cmd) {
  9575. if (commands.hasOwnProperty(cmd))
  9576. { return commands[cmd].call(null, this) }
  9577. },
  9578. triggerElectric: methodOp(function(text) { triggerElectric(this, text); }),
  9579. findPosH: function(from, amount, unit, visually) {
  9580. var this$1 = this;
  9581. var dir = 1;
  9582. if (amount < 0) { dir = -1; amount = -amount; }
  9583. var cur = clipPos(this.doc, from);
  9584. for (var i = 0; i < amount; ++i) {
  9585. cur = findPosH(this$1.doc, cur, dir, unit, visually);
  9586. if (cur.hitSide) { break }
  9587. }
  9588. return cur
  9589. },
  9590. moveH: methodOp(function(dir, unit) {
  9591. var this$1 = this;
  9592. this.extendSelectionsBy(function (range$$1) {
  9593. if (this$1.display.shift || this$1.doc.extend || range$$1.empty())
  9594. { return findPosH(this$1.doc, range$$1.head, dir, unit, this$1.options.rtlMoveVisually) }
  9595. else
  9596. { return dir < 0 ? range$$1.from() : range$$1.to() }
  9597. }, sel_move);
  9598. }),
  9599. deleteH: methodOp(function(dir, unit) {
  9600. var sel = this.doc.sel, doc = this.doc;
  9601. if (sel.somethingSelected())
  9602. { doc.replaceSelection("", null, "+delete"); }
  9603. else
  9604. { deleteNearSelection(this, function (range$$1) {
  9605. var other = findPosH(doc, range$$1.head, dir, unit, false);
  9606. return dir < 0 ? {from: other, to: range$$1.head} : {from: range$$1.head, to: other}
  9607. }); }
  9608. }),
  9609. findPosV: function(from, amount, unit, goalColumn) {
  9610. var this$1 = this;
  9611. var dir = 1, x = goalColumn;
  9612. if (amount < 0) { dir = -1; amount = -amount; }
  9613. var cur = clipPos(this.doc, from);
  9614. for (var i = 0; i < amount; ++i) {
  9615. var coords = cursorCoords(this$1, cur, "div");
  9616. if (x == null) { x = coords.left; }
  9617. else { coords.left = x; }
  9618. cur = findPosV(this$1, coords, dir, unit);
  9619. if (cur.hitSide) { break }
  9620. }
  9621. return cur
  9622. },
  9623. moveV: methodOp(function(dir, unit) {
  9624. var this$1 = this;
  9625. var doc = this.doc, goals = [];
  9626. var collapse = !this.display.shift && !doc.extend && doc.sel.somethingSelected();
  9627. doc.extendSelectionsBy(function (range$$1) {
  9628. if (collapse)
  9629. { return dir < 0 ? range$$1.from() : range$$1.to() }
  9630. var headPos = cursorCoords(this$1, range$$1.head, "div");
  9631. if (range$$1.goalColumn != null) { headPos.left = range$$1.goalColumn; }
  9632. goals.push(headPos.left);
  9633. var pos = findPosV(this$1, headPos, dir, unit);
  9634. if (unit == "page" && range$$1 == doc.sel.primary())
  9635. { addToScrollTop(this$1, charCoords(this$1, pos, "div").top - headPos.top); }
  9636. return pos
  9637. }, sel_move);
  9638. if (goals.length) { for (var i = 0; i < doc.sel.ranges.length; i++)
  9639. { doc.sel.ranges[i].goalColumn = goals[i]; } }
  9640. }),
  9641. // Find the word at the given position (as returned by coordsChar).
  9642. findWordAt: function(pos) {
  9643. var doc = this.doc, line = getLine(doc, pos.line).text;
  9644. var start = pos.ch, end = pos.ch;
  9645. if (line) {
  9646. var helper = this.getHelper(pos, "wordChars");
  9647. if ((pos.sticky == "before" || end == line.length) && start) { --start; } else { ++end; }
  9648. var startChar = line.charAt(start);
  9649. var check = isWordChar(startChar, helper)
  9650. ? function (ch) { return isWordChar(ch, helper); }
  9651. : /\s/.test(startChar) ? function (ch) { return /\s/.test(ch); }
  9652. : function (ch) { return (!/\s/.test(ch) && !isWordChar(ch)); };
  9653. while (start > 0 && check(line.charAt(start - 1))) { --start; }
  9654. while (end < line.length && check(line.charAt(end))) { ++end; }
  9655. }
  9656. return new Range(Pos(pos.line, start), Pos(pos.line, end))
  9657. },
  9658. toggleOverwrite: function(value) {
  9659. if (value != null && value == this.state.overwrite) { return }
  9660. if (this.state.overwrite = !this.state.overwrite)
  9661. { addClass(this.display.cursorDiv, "CodeMirror-overwrite"); }
  9662. else
  9663. { rmClass(this.display.cursorDiv, "CodeMirror-overwrite"); }
  9664. signal(this, "overwriteToggle", this, this.state.overwrite);
  9665. },
  9666. hasFocus: function() { return this.display.input.getField() == activeElt() },
  9667. isReadOnly: function() { return !!(this.options.readOnly || this.doc.cantEdit) },
  9668. scrollTo: methodOp(function (x, y) { scrollToCoords(this, x, y); }),
  9669. getScrollInfo: function() {
  9670. var scroller = this.display.scroller;
  9671. return {left: scroller.scrollLeft, top: scroller.scrollTop,
  9672. height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight,
  9673. width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth,
  9674. clientHeight: displayHeight(this), clientWidth: displayWidth(this)}
  9675. },
  9676. scrollIntoView: methodOp(function(range$$1, margin) {
  9677. if (range$$1 == null) {
  9678. range$$1 = {from: this.doc.sel.primary().head, to: null};
  9679. if (margin == null) { margin = this.options.cursorScrollMargin; }
  9680. } else if (typeof range$$1 == "number") {
  9681. range$$1 = {from: Pos(range$$1, 0), to: null};
  9682. } else if (range$$1.from == null) {
  9683. range$$1 = {from: range$$1, to: null};
  9684. }
  9685. if (!range$$1.to) { range$$1.to = range$$1.from; }
  9686. range$$1.margin = margin || 0;
  9687. if (range$$1.from.line != null) {
  9688. scrollToRange(this, range$$1);
  9689. } else {
  9690. scrollToCoordsRange(this, range$$1.from, range$$1.to, range$$1.margin);
  9691. }
  9692. }),
  9693. setSize: methodOp(function(width, height) {
  9694. var this$1 = this;
  9695. var interpret = function (val) { return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val; };
  9696. if (width != null) { this.display.wrapper.style.width = interpret(width); }
  9697. if (height != null) { this.display.wrapper.style.height = interpret(height); }
  9698. if (this.options.lineWrapping) { clearLineMeasurementCache(this); }
  9699. var lineNo$$1 = this.display.viewFrom;
  9700. this.doc.iter(lineNo$$1, this.display.viewTo, function (line) {
  9701. if (line.widgets) { for (var i = 0; i < line.widgets.length; i++)
  9702. { if (line.widgets[i].noHScroll) { regLineChange(this$1, lineNo$$1, "widget"); break } } }
  9703. ++lineNo$$1;
  9704. });
  9705. this.curOp.forceUpdate = true;
  9706. signal(this, "refresh", this);
  9707. }),
  9708. operation: function(f){return runInOp(this, f)},
  9709. startOperation: function(){return startOperation(this)},
  9710. endOperation: function(){return endOperation(this)},
  9711. refresh: methodOp(function() {
  9712. var oldHeight = this.display.cachedTextHeight;
  9713. regChange(this);
  9714. this.curOp.forceUpdate = true;
  9715. clearCaches(this);
  9716. scrollToCoords(this, this.doc.scrollLeft, this.doc.scrollTop);
  9717. updateGutterSpace(this);
  9718. if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5)
  9719. { estimateLineHeights(this); }
  9720. signal(this, "refresh", this);
  9721. }),
  9722. swapDoc: methodOp(function(doc) {
  9723. var old = this.doc;
  9724. old.cm = null;
  9725. attachDoc(this, doc);
  9726. clearCaches(this);
  9727. this.display.input.reset();
  9728. scrollToCoords(this, doc.scrollLeft, doc.scrollTop);
  9729. this.curOp.forceScroll = true;
  9730. signalLater(this, "swapDoc", this, old);
  9731. return old
  9732. }),
  9733. getInputField: function(){return this.display.input.getField()},
  9734. getWrapperElement: function(){return this.display.wrapper},
  9735. getScrollerElement: function(){return this.display.scroller},
  9736. getGutterElement: function(){return this.display.gutters}
  9737. };
  9738. eventMixin(CodeMirror);
  9739. CodeMirror.registerHelper = function(type, name, value) {
  9740. if (!helpers.hasOwnProperty(type)) { helpers[type] = CodeMirror[type] = {_global: []}; }
  9741. helpers[type][name] = value;
  9742. };
  9743. CodeMirror.registerGlobalHelper = function(type, name, predicate, value) {
  9744. CodeMirror.registerHelper(type, name, value);
  9745. helpers[type]._global.push({pred: predicate, val: value});
  9746. };
  9747. };
  9748. // Used for horizontal relative motion. Dir is -1 or 1 (left or
  9749. // right), unit can be "char", "column" (like char, but doesn't
  9750. // cross line boundaries), "word" (across next word), or "group" (to
  9751. // the start of next group of word or non-word-non-whitespace
  9752. // chars). The visually param controls whether, in right-to-left
  9753. // text, direction 1 means to move towards the next index in the
  9754. // string, or towards the character to the right of the current
  9755. // position. The resulting position will have a hitSide=true
  9756. // property if it reached the end of the document.
  9757. function findPosH(doc, pos, dir, unit, visually) {
  9758. var oldPos = pos;
  9759. var origDir = dir;
  9760. var lineObj = getLine(doc, pos.line);
  9761. function findNextLine() {
  9762. var l = pos.line + dir;
  9763. if (l < doc.first || l >= doc.first + doc.size) { return false }
  9764. pos = new Pos(l, pos.ch, pos.sticky);
  9765. return lineObj = getLine(doc, l)
  9766. }
  9767. function moveOnce(boundToLine) {
  9768. var next;
  9769. if (visually) {
  9770. next = moveVisually(doc.cm, lineObj, pos, dir);
  9771. } else {
  9772. next = moveLogically(lineObj, pos, dir);
  9773. }
  9774. if (next == null) {
  9775. if (!boundToLine && findNextLine())
  9776. { pos = endOfLine(visually, doc.cm, lineObj, pos.line, dir); }
  9777. else
  9778. { return false }
  9779. } else {
  9780. pos = next;
  9781. }
  9782. return true
  9783. }
  9784. if (unit == "char") {
  9785. moveOnce();
  9786. } else if (unit == "column") {
  9787. moveOnce(true);
  9788. } else if (unit == "word" || unit == "group") {
  9789. var sawType = null, group = unit == "group";
  9790. var helper = doc.cm && doc.cm.getHelper(pos, "wordChars");
  9791. for (var first = true;; first = false) {
  9792. if (dir < 0 && !moveOnce(!first)) { break }
  9793. var cur = lineObj.text.charAt(pos.ch) || "\n";
  9794. var type = isWordChar(cur, helper) ? "w"
  9795. : group && cur == "\n" ? "n"
  9796. : !group || /\s/.test(cur) ? null
  9797. : "p";
  9798. if (group && !first && !type) { type = "s"; }
  9799. if (sawType && sawType != type) {
  9800. if (dir < 0) {dir = 1; moveOnce(); pos.sticky = "after";}
  9801. break
  9802. }
  9803. if (type) { sawType = type; }
  9804. if (dir > 0 && !moveOnce(!first)) { break }
  9805. }
  9806. }
  9807. var result = skipAtomic(doc, pos, oldPos, origDir, true);
  9808. if (equalCursorPos(oldPos, result)) { result.hitSide = true; }
  9809. return result
  9810. }
  9811. // For relative vertical movement. Dir may be -1 or 1. Unit can be
  9812. // "page" or "line". The resulting position will have a hitSide=true
  9813. // property if it reached the end of the document.
  9814. function findPosV(cm, pos, dir, unit) {
  9815. var doc = cm.doc, x = pos.left, y;
  9816. if (unit == "page") {
  9817. var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight);
  9818. var moveAmount = Math.max(pageSize - .5 * textHeight(cm.display), 3);
  9819. y = (dir > 0 ? pos.bottom : pos.top) + dir * moveAmount;
  9820. } else if (unit == "line") {
  9821. y = dir > 0 ? pos.bottom + 3 : pos.top - 3;
  9822. }
  9823. var target;
  9824. for (;;) {
  9825. target = coordsChar(cm, x, y);
  9826. if (!target.outside) { break }
  9827. if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break }
  9828. y += dir * 5;
  9829. }
  9830. return target
  9831. }
  9832. // CONTENTEDITABLE INPUT STYLE
  9833. var ContentEditableInput = function(cm) {
  9834. this.cm = cm;
  9835. this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null;
  9836. this.polling = new Delayed();
  9837. this.composing = null;
  9838. this.gracePeriod = false;
  9839. this.readDOMTimeout = null;
  9840. };
  9841. ContentEditableInput.prototype.init = function (display) {
  9842. var this$1 = this;
  9843. var input = this, cm = input.cm;
  9844. var div = input.div = display.lineDiv;
  9845. disableBrowserMagic(div, cm.options.spellcheck);
  9846. on(div, "paste", function (e) {
  9847. if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { return }
  9848. // IE doesn't fire input events, so we schedule a read for the pasted content in this way
  9849. if (ie_version <= 11) { setTimeout(operation(cm, function () { return this$1.updateFromDOM(); }), 20); }
  9850. });
  9851. on(div, "compositionstart", function (e) {
  9852. this$1.composing = {data: e.data, done: false};
  9853. });
  9854. on(div, "compositionupdate", function (e) {
  9855. if (!this$1.composing) { this$1.composing = {data: e.data, done: false}; }
  9856. });
  9857. on(div, "compositionend", function (e) {
  9858. if (this$1.composing) {
  9859. if (e.data != this$1.composing.data) { this$1.readFromDOMSoon(); }
  9860. this$1.composing.done = true;
  9861. }
  9862. });
  9863. on(div, "touchstart", function () { return input.forceCompositionEnd(); });
  9864. on(div, "input", function () {
  9865. if (!this$1.composing) { this$1.readFromDOMSoon(); }
  9866. });
  9867. function onCopyCut(e) {
  9868. if (signalDOMEvent(cm, e)) { return }
  9869. if (cm.somethingSelected()) {
  9870. setLastCopied({lineWise: false, text: cm.getSelections()});
  9871. if (e.type == "cut") { cm.replaceSelection("", null, "cut"); }
  9872. } else if (!cm.options.lineWiseCopyCut) {
  9873. return
  9874. } else {
  9875. var ranges = copyableRanges(cm);
  9876. setLastCopied({lineWise: true, text: ranges.text});
  9877. if (e.type == "cut") {
  9878. cm.operation(function () {
  9879. cm.setSelections(ranges.ranges, 0, sel_dontScroll);
  9880. cm.replaceSelection("", null, "cut");
  9881. });
  9882. }
  9883. }
  9884. if (e.clipboardData) {
  9885. e.clipboardData.clearData();
  9886. var content = lastCopied.text.join("\n");
  9887. // iOS exposes the clipboard API, but seems to discard content inserted into it
  9888. e.clipboardData.setData("Text", content);
  9889. if (e.clipboardData.getData("Text") == content) {
  9890. e.preventDefault();
  9891. return
  9892. }
  9893. }
  9894. // Old-fashioned briefly-focus-a-textarea hack
  9895. var kludge = hiddenTextarea(), te = kludge.firstChild;
  9896. cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild);
  9897. te.value = lastCopied.text.join("\n");
  9898. var hadFocus = document.activeElement;
  9899. selectInput(te);
  9900. setTimeout(function () {
  9901. cm.display.lineSpace.removeChild(kludge);
  9902. hadFocus.focus();
  9903. if (hadFocus == div) { input.showPrimarySelection(); }
  9904. }, 50);
  9905. }
  9906. on(div, "copy", onCopyCut);
  9907. on(div, "cut", onCopyCut);
  9908. };
  9909. ContentEditableInput.prototype.prepareSelection = function () {
  9910. var result = prepareSelection(this.cm, false);
  9911. result.focus = this.cm.state.focused;
  9912. return result
  9913. };
  9914. ContentEditableInput.prototype.showSelection = function (info, takeFocus) {
  9915. if (!info || !this.cm.display.view.length) { return }
  9916. if (info.focus || takeFocus) { this.showPrimarySelection(); }
  9917. this.showMultipleSelections(info);
  9918. };
  9919. ContentEditableInput.prototype.showPrimarySelection = function () {
  9920. var sel = window.getSelection(), cm = this.cm, prim = cm.doc.sel.primary();
  9921. var from = prim.from(), to = prim.to();
  9922. if (cm.display.viewTo == cm.display.viewFrom || from.line >= cm.display.viewTo || to.line < cm.display.viewFrom) {
  9923. sel.removeAllRanges();
  9924. return
  9925. }
  9926. var curAnchor = domToPos(cm, sel.anchorNode, sel.anchorOffset);
  9927. var curFocus = domToPos(cm, sel.focusNode, sel.focusOffset);
  9928. if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad &&
  9929. cmp(minPos(curAnchor, curFocus), from) == 0 &&
  9930. cmp(maxPos(curAnchor, curFocus), to) == 0)
  9931. { return }
  9932. var view = cm.display.view;
  9933. var start = (from.line >= cm.display.viewFrom && posToDOM(cm, from)) ||
  9934. {node: view[0].measure.map[2], offset: 0};
  9935. var end = to.line < cm.display.viewTo && posToDOM(cm, to);
  9936. if (!end) {
  9937. var measure = view[view.length - 1].measure;
  9938. var map$$1 = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map;
  9939. end = {node: map$$1[map$$1.length - 1], offset: map$$1[map$$1.length - 2] - map$$1[map$$1.length - 3]};
  9940. }
  9941. if (!start || !end) {
  9942. sel.removeAllRanges();
  9943. return
  9944. }
  9945. var old = sel.rangeCount && sel.getRangeAt(0), rng;
  9946. try { rng = range(start.node, start.offset, end.offset, end.node); }
  9947. catch(e) {} // Our model of the DOM might be outdated, in which case the range we try to set can be impossible
  9948. if (rng) {
  9949. if (!gecko && cm.state.focused) {
  9950. sel.collapse(start.node, start.offset);
  9951. if (!rng.collapsed) {
  9952. sel.removeAllRanges();
  9953. sel.addRange(rng);
  9954. }
  9955. } else {
  9956. sel.removeAllRanges();
  9957. sel.addRange(rng);
  9958. }
  9959. if (old && sel.anchorNode == null) { sel.addRange(old); }
  9960. else if (gecko) { this.startGracePeriod(); }
  9961. }
  9962. this.rememberSelection();
  9963. };
  9964. ContentEditableInput.prototype.startGracePeriod = function () {
  9965. var this$1 = this;
  9966. clearTimeout(this.gracePeriod);
  9967. this.gracePeriod = setTimeout(function () {
  9968. this$1.gracePeriod = false;
  9969. if (this$1.selectionChanged())
  9970. { this$1.cm.operation(function () { return this$1.cm.curOp.selectionChanged = true; }); }
  9971. }, 20);
  9972. };
  9973. ContentEditableInput.prototype.showMultipleSelections = function (info) {
  9974. removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors);
  9975. removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection);
  9976. };
  9977. ContentEditableInput.prototype.rememberSelection = function () {
  9978. var sel = window.getSelection();
  9979. this.lastAnchorNode = sel.anchorNode; this.lastAnchorOffset = sel.anchorOffset;
  9980. this.lastFocusNode = sel.focusNode; this.lastFocusOffset = sel.focusOffset;
  9981. };
  9982. ContentEditableInput.prototype.selectionInEditor = function () {
  9983. var sel = window.getSelection();
  9984. if (!sel.rangeCount) { return false }
  9985. var node = sel.getRangeAt(0).commonAncestorContainer;
  9986. return contains(this.div, node)
  9987. };
  9988. ContentEditableInput.prototype.focus = function () {
  9989. if (this.cm.options.readOnly != "nocursor") {
  9990. if (!this.selectionInEditor())
  9991. { this.showSelection(this.prepareSelection(), true); }
  9992. this.div.focus();
  9993. }
  9994. };
  9995. ContentEditableInput.prototype.blur = function () { this.div.blur(); };
  9996. ContentEditableInput.prototype.getField = function () { return this.div };
  9997. ContentEditableInput.prototype.supportsTouch = function () { return true };
  9998. ContentEditableInput.prototype.receivedFocus = function () {
  9999. var input = this;
  10000. if (this.selectionInEditor())
  10001. { this.pollSelection(); }
  10002. else
  10003. { runInOp(this.cm, function () { return input.cm.curOp.selectionChanged = true; }); }
  10004. function poll() {
  10005. if (input.cm.state.focused) {
  10006. input.pollSelection();
  10007. input.polling.set(input.cm.options.pollInterval, poll);
  10008. }
  10009. }
  10010. this.polling.set(this.cm.options.pollInterval, poll);
  10011. };
  10012. ContentEditableInput.prototype.selectionChanged = function () {
  10013. var sel = window.getSelection();
  10014. return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset ||
  10015. sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset
  10016. };
  10017. ContentEditableInput.prototype.pollSelection = function () {
  10018. if (this.readDOMTimeout != null || this.gracePeriod || !this.selectionChanged()) { return }
  10019. var sel = window.getSelection(), cm = this.cm;
  10020. // On Android Chrome (version 56, at least), backspacing into an
  10021. // uneditable block element will put the cursor in that element,
  10022. // and then, because it's not editable, hide the virtual keyboard.
  10023. // Because Android doesn't allow us to actually detect backspace
  10024. // presses in a sane way, this code checks for when that happens
  10025. // and simulates a backspace press in this case.
  10026. if (android && chrome && this.cm.options.gutters.length && isInGutter(sel.anchorNode)) {
  10027. this.cm.triggerOnKeyDown({type: "keydown", keyCode: 8, preventDefault: Math.abs});
  10028. this.blur();
  10029. this.focus();
  10030. return
  10031. }
  10032. if (this.composing) { return }
  10033. this.rememberSelection();
  10034. var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset);
  10035. var head = domToPos(cm, sel.focusNode, sel.focusOffset);
  10036. if (anchor && head) { runInOp(cm, function () {
  10037. setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll);
  10038. if (anchor.bad || head.bad) { cm.curOp.selectionChanged = true; }
  10039. }); }
  10040. };
  10041. ContentEditableInput.prototype.pollContent = function () {
  10042. if (this.readDOMTimeout != null) {
  10043. clearTimeout(this.readDOMTimeout);
  10044. this.readDOMTimeout = null;
  10045. }
  10046. var cm = this.cm, display = cm.display, sel = cm.doc.sel.primary();
  10047. var from = sel.from(), to = sel.to();
  10048. if (from.ch == 0 && from.line > cm.firstLine())
  10049. { from = Pos(from.line - 1, getLine(cm.doc, from.line - 1).length); }
  10050. if (to.ch == getLine(cm.doc, to.line).text.length && to.line < cm.lastLine())
  10051. { to = Pos(to.line + 1, 0); }
  10052. if (from.line < display.viewFrom || to.line > display.viewTo - 1) { return false }
  10053. var fromIndex, fromLine, fromNode;
  10054. if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) {
  10055. fromLine = lineNo(display.view[0].line);
  10056. fromNode = display.view[0].node;
  10057. } else {
  10058. fromLine = lineNo(display.view[fromIndex].line);
  10059. fromNode = display.view[fromIndex - 1].node.nextSibling;
  10060. }
  10061. var toIndex = findViewIndex(cm, to.line);
  10062. var toLine, toNode;
  10063. if (toIndex == display.view.length - 1) {
  10064. toLine = display.viewTo - 1;
  10065. toNode = display.lineDiv.lastChild;
  10066. } else {
  10067. toLine = lineNo(display.view[toIndex + 1].line) - 1;
  10068. toNode = display.view[toIndex + 1].node.previousSibling;
  10069. }
  10070. if (!fromNode) { return false }
  10071. var newText = cm.doc.splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine));
  10072. var oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length));
  10073. while (newText.length > 1 && oldText.length > 1) {
  10074. if (lst(newText) == lst(oldText)) { newText.pop(); oldText.pop(); toLine--; }
  10075. else if (newText[0] == oldText[0]) { newText.shift(); oldText.shift(); fromLine++; }
  10076. else { break }
  10077. }
  10078. var cutFront = 0, cutEnd = 0;
  10079. var newTop = newText[0], oldTop = oldText[0], maxCutFront = Math.min(newTop.length, oldTop.length);
  10080. while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront))
  10081. { ++cutFront; }
  10082. var newBot = lst(newText), oldBot = lst(oldText);
  10083. var maxCutEnd = Math.min(newBot.length - (newText.length == 1 ? cutFront : 0),
  10084. oldBot.length - (oldText.length == 1 ? cutFront : 0));
  10085. while (cutEnd < maxCutEnd &&
  10086. newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1))
  10087. { ++cutEnd; }
  10088. // Try to move start of change to start of selection if ambiguous
  10089. if (newText.length == 1 && oldText.length == 1 && fromLine == from.line) {
  10090. while (cutFront && cutFront > from.ch &&
  10091. newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) {
  10092. cutFront--;
  10093. cutEnd++;
  10094. }
  10095. }
  10096. newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd).replace(/^\u200b+/, "");
  10097. newText[0] = newText[0].slice(cutFront).replace(/\u200b+$/, "");
  10098. var chFrom = Pos(fromLine, cutFront);
  10099. var chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0);
  10100. if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) {
  10101. replaceRange(cm.doc, newText, chFrom, chTo, "+input");
  10102. return true
  10103. }
  10104. };
  10105. ContentEditableInput.prototype.ensurePolled = function () {
  10106. this.forceCompositionEnd();
  10107. };
  10108. ContentEditableInput.prototype.reset = function () {
  10109. this.forceCompositionEnd();
  10110. };
  10111. ContentEditableInput.prototype.forceCompositionEnd = function () {
  10112. if (!this.composing) { return }
  10113. clearTimeout(this.readDOMTimeout);
  10114. this.composing = null;
  10115. this.updateFromDOM();
  10116. this.div.blur();
  10117. this.div.focus();
  10118. };
  10119. ContentEditableInput.prototype.readFromDOMSoon = function () {
  10120. var this$1 = this;
  10121. if (this.readDOMTimeout != null) { return }
  10122. this.readDOMTimeout = setTimeout(function () {
  10123. this$1.readDOMTimeout = null;
  10124. if (this$1.composing) {
  10125. if (this$1.composing.done) { this$1.composing = null; }
  10126. else { return }
  10127. }
  10128. this$1.updateFromDOM();
  10129. }, 80);
  10130. };
  10131. ContentEditableInput.prototype.updateFromDOM = function () {
  10132. var this$1 = this;
  10133. if (this.cm.isReadOnly() || !this.pollContent())
  10134. { runInOp(this.cm, function () { return regChange(this$1.cm); }); }
  10135. };
  10136. ContentEditableInput.prototype.setUneditable = function (node) {
  10137. node.contentEditable = "false";
  10138. };
  10139. ContentEditableInput.prototype.onKeyPress = function (e) {
  10140. if (e.charCode == 0) { return }
  10141. e.preventDefault();
  10142. if (!this.cm.isReadOnly())
  10143. { operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0); }
  10144. };
  10145. ContentEditableInput.prototype.readOnlyChanged = function (val) {
  10146. this.div.contentEditable = String(val != "nocursor");
  10147. };
  10148. ContentEditableInput.prototype.onContextMenu = function () {};
  10149. ContentEditableInput.prototype.resetPosition = function () {};
  10150. ContentEditableInput.prototype.needsContentAttribute = true;
  10151. function posToDOM(cm, pos) {
  10152. var view = findViewForLine(cm, pos.line);
  10153. if (!view || view.hidden) { return null }
  10154. var line = getLine(cm.doc, pos.line);
  10155. var info = mapFromLineView(view, line, pos.line);
  10156. var order = getOrder(line, cm.doc.direction), side = "left";
  10157. if (order) {
  10158. var partPos = getBidiPartAt(order, pos.ch);
  10159. side = partPos % 2 ? "right" : "left";
  10160. }
  10161. var result = nodeAndOffsetInLineMap(info.map, pos.ch, side);
  10162. result.offset = result.collapse == "right" ? result.end : result.start;
  10163. return result
  10164. }
  10165. function isInGutter(node) {
  10166. for (var scan = node; scan; scan = scan.parentNode)
  10167. { if (/CodeMirror-gutter-wrapper/.test(scan.className)) { return true } }
  10168. return false
  10169. }
  10170. function badPos(pos, bad) { if (bad) { pos.bad = true; } return pos }
  10171. function domTextBetween(cm, from, to, fromLine, toLine) {
  10172. var text = "", closing = false, lineSep = cm.doc.lineSeparator();
  10173. function recognizeMarker(id) { return function (marker) { return marker.id == id; } }
  10174. function close() {
  10175. if (closing) {
  10176. text += lineSep;
  10177. closing = false;
  10178. }
  10179. }
  10180. function addText(str) {
  10181. if (str) {
  10182. close();
  10183. text += str;
  10184. }
  10185. }
  10186. function walk(node) {
  10187. if (node.nodeType == 1) {
  10188. var cmText = node.getAttribute("cm-text");
  10189. if (cmText != null) {
  10190. addText(cmText || node.textContent.replace(/\u200b/g, ""));
  10191. return
  10192. }
  10193. var markerID = node.getAttribute("cm-marker"), range$$1;
  10194. if (markerID) {
  10195. var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID));
  10196. if (found.length && (range$$1 = found[0].find(0)))
  10197. { addText(getBetween(cm.doc, range$$1.from, range$$1.to).join(lineSep)); }
  10198. return
  10199. }
  10200. if (node.getAttribute("contenteditable") == "false") { return }
  10201. var isBlock = /^(pre|div|p)$/i.test(node.nodeName);
  10202. if (isBlock) { close(); }
  10203. for (var i = 0; i < node.childNodes.length; i++)
  10204. { walk(node.childNodes[i]); }
  10205. if (isBlock) { closing = true; }
  10206. } else if (node.nodeType == 3) {
  10207. addText(node.nodeValue);
  10208. }
  10209. }
  10210. for (;;) {
  10211. walk(from);
  10212. if (from == to) { break }
  10213. from = from.nextSibling;
  10214. }
  10215. return text
  10216. }
  10217. function domToPos(cm, node, offset) {
  10218. var lineNode;
  10219. if (node == cm.display.lineDiv) {
  10220. lineNode = cm.display.lineDiv.childNodes[offset];
  10221. if (!lineNode) { return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true) }
  10222. node = null; offset = 0;
  10223. } else {
  10224. for (lineNode = node;; lineNode = lineNode.parentNode) {
  10225. if (!lineNode || lineNode == cm.display.lineDiv) { return null }
  10226. if (lineNode.parentNode && lineNode.parentNode == cm.display.lineDiv) { break }
  10227. }
  10228. }
  10229. for (var i = 0; i < cm.display.view.length; i++) {
  10230. var lineView = cm.display.view[i];
  10231. if (lineView.node == lineNode)
  10232. { return locateNodeInLineView(lineView, node, offset) }
  10233. }
  10234. }
  10235. function locateNodeInLineView(lineView, node, offset) {
  10236. var wrapper = lineView.text.firstChild, bad = false;
  10237. if (!node || !contains(wrapper, node)) { return badPos(Pos(lineNo(lineView.line), 0), true) }
  10238. if (node == wrapper) {
  10239. bad = true;
  10240. node = wrapper.childNodes[offset];
  10241. offset = 0;
  10242. if (!node) {
  10243. var line = lineView.rest ? lst(lineView.rest) : lineView.line;
  10244. return badPos(Pos(lineNo(line), line.text.length), bad)
  10245. }
  10246. }
  10247. var textNode = node.nodeType == 3 ? node : null, topNode = node;
  10248. if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) {
  10249. textNode = node.firstChild;
  10250. if (offset) { offset = textNode.nodeValue.length; }
  10251. }
  10252. while (topNode.parentNode != wrapper) { topNode = topNode.parentNode; }
  10253. var measure = lineView.measure, maps = measure.maps;
  10254. function find(textNode, topNode, offset) {
  10255. for (var i = -1; i < (maps ? maps.length : 0); i++) {
  10256. var map$$1 = i < 0 ? measure.map : maps[i];
  10257. for (var j = 0; j < map$$1.length; j += 3) {
  10258. var curNode = map$$1[j + 2];
  10259. if (curNode == textNode || curNode == topNode) {
  10260. var line = lineNo(i < 0 ? lineView.line : lineView.rest[i]);
  10261. var ch = map$$1[j] + offset;
  10262. if (offset < 0 || curNode != textNode) { ch = map$$1[j + (offset ? 1 : 0)]; }
  10263. return Pos(line, ch)
  10264. }
  10265. }
  10266. }
  10267. }
  10268. var found = find(textNode, topNode, offset);
  10269. if (found) { return badPos(found, bad) }
  10270. // FIXME this is all really shaky. might handle the few cases it needs to handle, but likely to cause problems
  10271. for (var after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) {
  10272. found = find(after, after.firstChild, 0);
  10273. if (found)
  10274. { return badPos(Pos(found.line, found.ch - dist), bad) }
  10275. else
  10276. { dist += after.textContent.length; }
  10277. }
  10278. for (var before = topNode.previousSibling, dist$1 = offset; before; before = before.previousSibling) {
  10279. found = find(before, before.firstChild, -1);
  10280. if (found)
  10281. { return badPos(Pos(found.line, found.ch + dist$1), bad) }
  10282. else
  10283. { dist$1 += before.textContent.length; }
  10284. }
  10285. }
  10286. // TEXTAREA INPUT STYLE
  10287. var TextareaInput = function(cm) {
  10288. this.cm = cm;
  10289. // See input.poll and input.reset
  10290. this.prevInput = "";
  10291. // Flag that indicates whether we expect input to appear real soon
  10292. // now (after some event like 'keypress' or 'input') and are
  10293. // polling intensively.
  10294. this.pollingFast = false;
  10295. // Self-resetting timeout for the poller
  10296. this.polling = new Delayed();
  10297. // Used to work around IE issue with selection being forgotten when focus moves away from textarea
  10298. this.hasSelection = false;
  10299. this.composing = null;
  10300. };
  10301. TextareaInput.prototype.init = function (display) {
  10302. var this$1 = this;
  10303. var input = this, cm = this.cm;
  10304. // Wraps and hides input textarea
  10305. var div = this.wrapper = hiddenTextarea();
  10306. // The semihidden textarea that is focused when the editor is
  10307. // focused, and receives input.
  10308. var te = this.textarea = div.firstChild;
  10309. display.wrapper.insertBefore(div, display.wrapper.firstChild);
  10310. // Needed to hide big blue blinking cursor on Mobile Safari (doesn't seem to work in iOS 8 anymore)
  10311. if (ios) { te.style.width = "0px"; }
  10312. on(te, "input", function () {
  10313. if (ie && ie_version >= 9 && this$1.hasSelection) { this$1.hasSelection = null; }
  10314. input.poll();
  10315. });
  10316. on(te, "paste", function (e) {
  10317. if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { return }
  10318. cm.state.pasteIncoming = true;
  10319. input.fastPoll();
  10320. });
  10321. function prepareCopyCut(e) {
  10322. if (signalDOMEvent(cm, e)) { return }
  10323. if (cm.somethingSelected()) {
  10324. setLastCopied({lineWise: false, text: cm.getSelections()});
  10325. } else if (!cm.options.lineWiseCopyCut) {
  10326. return
  10327. } else {
  10328. var ranges = copyableRanges(cm);
  10329. setLastCopied({lineWise: true, text: ranges.text});
  10330. if (e.type == "cut") {
  10331. cm.setSelections(ranges.ranges, null, sel_dontScroll);
  10332. } else {
  10333. input.prevInput = "";
  10334. te.value = ranges.text.join("\n");
  10335. selectInput(te);
  10336. }
  10337. }
  10338. if (e.type == "cut") { cm.state.cutIncoming = true; }
  10339. }
  10340. on(te, "cut", prepareCopyCut);
  10341. on(te, "copy", prepareCopyCut);
  10342. on(display.scroller, "paste", function (e) {
  10343. if (eventInWidget(display, e) || signalDOMEvent(cm, e)) { return }
  10344. cm.state.pasteIncoming = true;
  10345. input.focus();
  10346. });
  10347. // Prevent normal selection in the editor (we handle our own)
  10348. on(display.lineSpace, "selectstart", function (e) {
  10349. if (!eventInWidget(display, e)) { e_preventDefault(e); }
  10350. });
  10351. on(te, "compositionstart", function () {
  10352. var start = cm.getCursor("from");
  10353. if (input.composing) { input.composing.range.clear(); }
  10354. input.composing = {
  10355. start: start,
  10356. range: cm.markText(start, cm.getCursor("to"), {className: "CodeMirror-composing"})
  10357. };
  10358. });
  10359. on(te, "compositionend", function () {
  10360. if (input.composing) {
  10361. input.poll();
  10362. input.composing.range.clear();
  10363. input.composing = null;
  10364. }
  10365. });
  10366. };
  10367. TextareaInput.prototype.prepareSelection = function () {
  10368. // Redraw the selection and/or cursor
  10369. var cm = this.cm, display = cm.display, doc = cm.doc;
  10370. var result = prepareSelection(cm);
  10371. // Move the hidden textarea near the cursor to prevent scrolling artifacts
  10372. if (cm.options.moveInputWithCursor) {
  10373. var headPos = cursorCoords(cm, doc.sel.primary().head, "div");
  10374. var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect();
  10375. result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10,
  10376. headPos.top + lineOff.top - wrapOff.top));
  10377. result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10,
  10378. headPos.left + lineOff.left - wrapOff.left));
  10379. }
  10380. return result
  10381. };
  10382. TextareaInput.prototype.showSelection = function (drawn) {
  10383. var cm = this.cm, display = cm.display;
  10384. removeChildrenAndAdd(display.cursorDiv, drawn.cursors);
  10385. removeChildrenAndAdd(display.selectionDiv, drawn.selection);
  10386. if (drawn.teTop != null) {
  10387. this.wrapper.style.top = drawn.teTop + "px";
  10388. this.wrapper.style.left = drawn.teLeft + "px";
  10389. }
  10390. };
  10391. // Reset the input to correspond to the selection (or to be empty,
  10392. // when not typing and nothing is selected)
  10393. TextareaInput.prototype.reset = function (typing) {
  10394. if (this.contextMenuPending || this.composing) { return }
  10395. var cm = this.cm;
  10396. if (cm.somethingSelected()) {
  10397. this.prevInput = "";
  10398. var content = cm.getSelection();
  10399. this.textarea.value = content;
  10400. if (cm.state.focused) { selectInput(this.textarea); }
  10401. if (ie && ie_version >= 9) { this.hasSelection = content; }
  10402. } else if (!typing) {
  10403. this.prevInput = this.textarea.value = "";
  10404. if (ie && ie_version >= 9) { this.hasSelection = null; }
  10405. }
  10406. };
  10407. TextareaInput.prototype.getField = function () { return this.textarea };
  10408. TextareaInput.prototype.supportsTouch = function () { return false };
  10409. TextareaInput.prototype.focus = function () {
  10410. if (this.cm.options.readOnly != "nocursor" && (!mobile || activeElt() != this.textarea)) {
  10411. try { this.textarea.focus(); }
  10412. catch (e) {} // IE8 will throw if the textarea is display: none or not in DOM
  10413. }
  10414. };
  10415. TextareaInput.prototype.blur = function () { this.textarea.blur(); };
  10416. TextareaInput.prototype.resetPosition = function () {
  10417. this.wrapper.style.top = this.wrapper.style.left = 0;
  10418. };
  10419. TextareaInput.prototype.receivedFocus = function () { this.slowPoll(); };
  10420. // Poll for input changes, using the normal rate of polling. This
  10421. // runs as long as the editor is focused.
  10422. TextareaInput.prototype.slowPoll = function () {
  10423. var this$1 = this;
  10424. if (this.pollingFast) { return }
  10425. this.polling.set(this.cm.options.pollInterval, function () {
  10426. this$1.poll();
  10427. if (this$1.cm.state.focused) { this$1.slowPoll(); }
  10428. });
  10429. };
  10430. // When an event has just come in that is likely to add or change
  10431. // something in the input textarea, we poll faster, to ensure that
  10432. // the change appears on the screen quickly.
  10433. TextareaInput.prototype.fastPoll = function () {
  10434. var missed = false, input = this;
  10435. input.pollingFast = true;
  10436. function p() {
  10437. var changed = input.poll();
  10438. if (!changed && !missed) {missed = true; input.polling.set(60, p);}
  10439. else {input.pollingFast = false; input.slowPoll();}
  10440. }
  10441. input.polling.set(20, p);
  10442. };
  10443. // Read input from the textarea, and update the document to match.
  10444. // When something is selected, it is present in the textarea, and
  10445. // selected (unless it is huge, in which case a placeholder is
  10446. // used). When nothing is selected, the cursor sits after previously
  10447. // seen text (can be empty), which is stored in prevInput (we must
  10448. // not reset the textarea when typing, because that breaks IME).
  10449. TextareaInput.prototype.poll = function () {
  10450. var this$1 = this;
  10451. var cm = this.cm, input = this.textarea, prevInput = this.prevInput;
  10452. // Since this is called a *lot*, try to bail out as cheaply as
  10453. // possible when it is clear that nothing happened. hasSelection
  10454. // will be the case when there is a lot of text in the textarea,
  10455. // in which case reading its value would be expensive.
  10456. if (this.contextMenuPending || !cm.state.focused ||
  10457. (hasSelection(input) && !prevInput && !this.composing) ||
  10458. cm.isReadOnly() || cm.options.disableInput || cm.state.keySeq)
  10459. { return false }
  10460. var text = input.value;
  10461. // If nothing changed, bail.
  10462. if (text == prevInput && !cm.somethingSelected()) { return false }
  10463. // Work around nonsensical selection resetting in IE9/10, and
  10464. // inexplicable appearance of private area unicode characters on
  10465. // some key combos in Mac (#2689).
  10466. if (ie && ie_version >= 9 && this.hasSelection === text ||
  10467. mac && /[\uf700-\uf7ff]/.test(text)) {
  10468. cm.display.input.reset();
  10469. return false
  10470. }
  10471. if (cm.doc.sel == cm.display.selForContextMenu) {
  10472. var first = text.charCodeAt(0);
  10473. if (first == 0x200b && !prevInput) { prevInput = "\u200b"; }
  10474. if (first == 0x21da) { this.reset(); return this.cm.execCommand("undo") }
  10475. }
  10476. // Find the part of the input that is actually new
  10477. var same = 0, l = Math.min(prevInput.length, text.length);
  10478. while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) { ++same; }
  10479. runInOp(cm, function () {
  10480. applyTextInput(cm, text.slice(same), prevInput.length - same,
  10481. null, this$1.composing ? "*compose" : null);
  10482. // Don't leave long text in the textarea, since it makes further polling slow
  10483. if (text.length > 1000 || text.indexOf("\n") > -1) { input.value = this$1.prevInput = ""; }
  10484. else { this$1.prevInput = text; }
  10485. if (this$1.composing) {
  10486. this$1.composing.range.clear();
  10487. this$1.composing.range = cm.markText(this$1.composing.start, cm.getCursor("to"),
  10488. {className: "CodeMirror-composing"});
  10489. }
  10490. });
  10491. return true
  10492. };
  10493. TextareaInput.prototype.ensurePolled = function () {
  10494. if (this.pollingFast && this.poll()) { this.pollingFast = false; }
  10495. };
  10496. TextareaInput.prototype.onKeyPress = function () {
  10497. if (ie && ie_version >= 9) { this.hasSelection = null; }
  10498. this.fastPoll();
  10499. };
  10500. TextareaInput.prototype.onContextMenu = function (e) {
  10501. var input = this, cm = input.cm, display = cm.display, te = input.textarea;
  10502. var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop;
  10503. if (!pos || presto) { return } // Opera is difficult.
  10504. // Reset the current text selection only if the click is done outside of the selection
  10505. // and 'resetSelectionOnContextMenu' option is true.
  10506. var reset = cm.options.resetSelectionOnContextMenu;
  10507. if (reset && cm.doc.sel.contains(pos) == -1)
  10508. { operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll); }
  10509. var oldCSS = te.style.cssText, oldWrapperCSS = input.wrapper.style.cssText;
  10510. input.wrapper.style.cssText = "position: absolute";
  10511. var wrapperBox = input.wrapper.getBoundingClientRect();
  10512. 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);";
  10513. var oldScrollY;
  10514. if (webkit) { oldScrollY = window.scrollY; } // Work around Chrome issue (#2712)
  10515. display.input.focus();
  10516. if (webkit) { window.scrollTo(null, oldScrollY); }
  10517. display.input.reset();
  10518. // Adds "Select all" to context menu in FF
  10519. if (!cm.somethingSelected()) { te.value = input.prevInput = " "; }
  10520. input.contextMenuPending = true;
  10521. display.selForContextMenu = cm.doc.sel;
  10522. clearTimeout(display.detectingSelectAll);
  10523. // Select-all will be greyed out if there's nothing to select, so
  10524. // this adds a zero-width space so that we can later check whether
  10525. // it got selected.
  10526. function prepareSelectAllHack() {
  10527. if (te.selectionStart != null) {
  10528. var selected = cm.somethingSelected();
  10529. var extval = "\u200b" + (selected ? te.value : "");
  10530. te.value = "\u21da"; // Used to catch context-menu undo
  10531. te.value = extval;
  10532. input.prevInput = selected ? "" : "\u200b";
  10533. te.selectionStart = 1; te.selectionEnd = extval.length;
  10534. // Re-set this, in case some other handler touched the
  10535. // selection in the meantime.
  10536. display.selForContextMenu = cm.doc.sel;
  10537. }
  10538. }
  10539. function rehide() {
  10540. input.contextMenuPending = false;
  10541. input.wrapper.style.cssText = oldWrapperCSS;
  10542. te.style.cssText = oldCSS;
  10543. if (ie && ie_version < 9) { display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos); }
  10544. // Try to detect the user choosing select-all
  10545. if (te.selectionStart != null) {
  10546. if (!ie || (ie && ie_version < 9)) { prepareSelectAllHack(); }
  10547. var i = 0, poll = function () {
  10548. if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0 &&
  10549. te.selectionEnd > 0 && input.prevInput == "\u200b") {
  10550. operation(cm, selectAll)(cm);
  10551. } else if (i++ < 10) {
  10552. display.detectingSelectAll = setTimeout(poll, 500);
  10553. } else {
  10554. display.selForContextMenu = null;
  10555. display.input.reset();
  10556. }
  10557. };
  10558. display.detectingSelectAll = setTimeout(poll, 200);
  10559. }
  10560. }
  10561. if (ie && ie_version >= 9) { prepareSelectAllHack(); }
  10562. if (captureRightClick) {
  10563. e_stop(e);
  10564. var mouseup = function () {
  10565. off(window, "mouseup", mouseup);
  10566. setTimeout(rehide, 20);
  10567. };
  10568. on(window, "mouseup", mouseup);
  10569. } else {
  10570. setTimeout(rehide, 50);
  10571. }
  10572. };
  10573. TextareaInput.prototype.readOnlyChanged = function (val) {
  10574. if (!val) { this.reset(); }
  10575. this.textarea.disabled = val == "nocursor";
  10576. };
  10577. TextareaInput.prototype.setUneditable = function () {};
  10578. TextareaInput.prototype.needsContentAttribute = false;
  10579. function fromTextArea(textarea, options) {
  10580. options = options ? copyObj(options) : {};
  10581. options.value = textarea.value;
  10582. if (!options.tabindex && textarea.tabIndex)
  10583. { options.tabindex = textarea.tabIndex; }
  10584. if (!options.placeholder && textarea.placeholder)
  10585. { options.placeholder = textarea.placeholder; }
  10586. // Set autofocus to true if this textarea is focused, or if it has
  10587. // autofocus and no other element is focused.
  10588. if (options.autofocus == null) {
  10589. var hasFocus = activeElt();
  10590. options.autofocus = hasFocus == textarea ||
  10591. textarea.getAttribute("autofocus") != null && hasFocus == document.body;
  10592. }
  10593. function save() {textarea.value = cm.getValue();}
  10594. var realSubmit;
  10595. if (textarea.form) {
  10596. on(textarea.form, "submit", save);
  10597. // Deplorable hack to make the submit method do the right thing.
  10598. if (!options.leaveSubmitMethodAlone) {
  10599. var form = textarea.form;
  10600. realSubmit = form.submit;
  10601. try {
  10602. var wrappedSubmit = form.submit = function () {
  10603. save();
  10604. form.submit = realSubmit;
  10605. form.submit();
  10606. form.submit = wrappedSubmit;
  10607. };
  10608. } catch(e) {}
  10609. }
  10610. }
  10611. options.finishInit = function (cm) {
  10612. cm.save = save;
  10613. cm.getTextArea = function () { return textarea; };
  10614. cm.toTextArea = function () {
  10615. cm.toTextArea = isNaN; // Prevent this from being ran twice
  10616. save();
  10617. textarea.parentNode.removeChild(cm.getWrapperElement());
  10618. textarea.style.display = "";
  10619. if (textarea.form) {
  10620. off(textarea.form, "submit", save);
  10621. if (typeof textarea.form.submit == "function")
  10622. { textarea.form.submit = realSubmit; }
  10623. }
  10624. };
  10625. };
  10626. textarea.style.display = "none";
  10627. var cm = CodeMirror$1(function (node) { return textarea.parentNode.insertBefore(node, textarea.nextSibling); },
  10628. options);
  10629. return cm
  10630. }
  10631. function addLegacyProps(CodeMirror) {
  10632. CodeMirror.off = off;
  10633. CodeMirror.on = on;
  10634. CodeMirror.wheelEventPixels = wheelEventPixels;
  10635. CodeMirror.Doc = Doc;
  10636. CodeMirror.splitLines = splitLinesAuto;
  10637. CodeMirror.countColumn = countColumn;
  10638. CodeMirror.findColumn = findColumn;
  10639. CodeMirror.isWordChar = isWordCharBasic;
  10640. CodeMirror.Pass = Pass;
  10641. CodeMirror.signal = signal;
  10642. CodeMirror.Line = Line;
  10643. CodeMirror.changeEnd = changeEnd;
  10644. CodeMirror.scrollbarModel = scrollbarModel;
  10645. CodeMirror.Pos = Pos;
  10646. CodeMirror.cmpPos = cmp;
  10647. CodeMirror.modes = modes;
  10648. CodeMirror.mimeModes = mimeModes;
  10649. CodeMirror.resolveMode = resolveMode;
  10650. CodeMirror.getMode = getMode;
  10651. CodeMirror.modeExtensions = modeExtensions;
  10652. CodeMirror.extendMode = extendMode;
  10653. CodeMirror.copyState = copyState;
  10654. CodeMirror.startState = startState;
  10655. CodeMirror.innerMode = innerMode;
  10656. CodeMirror.commands = commands;
  10657. CodeMirror.keyMap = keyMap;
  10658. CodeMirror.keyName = keyName;
  10659. CodeMirror.isModifierKey = isModifierKey;
  10660. CodeMirror.lookupKey = lookupKey;
  10661. CodeMirror.normalizeKeyMap = normalizeKeyMap;
  10662. CodeMirror.StringStream = StringStream;
  10663. CodeMirror.SharedTextMarker = SharedTextMarker;
  10664. CodeMirror.TextMarker = TextMarker;
  10665. CodeMirror.LineWidget = LineWidget;
  10666. CodeMirror.e_preventDefault = e_preventDefault;
  10667. CodeMirror.e_stopPropagation = e_stopPropagation;
  10668. CodeMirror.e_stop = e_stop;
  10669. CodeMirror.addClass = addClass;
  10670. CodeMirror.contains = contains;
  10671. CodeMirror.rmClass = rmClass;
  10672. CodeMirror.keyNames = keyNames;
  10673. }
  10674. // EDITOR CONSTRUCTOR
  10675. defineOptions(CodeMirror$1);
  10676. addEditorMethods(CodeMirror$1);
  10677. // Set up methods on CodeMirror's prototype to redirect to the editor's document.
  10678. var dontDelegate = "iter insert remove copy getEditor constructor".split(" ");
  10679. for (var prop in Doc.prototype) { if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0)
  10680. { CodeMirror$1.prototype[prop] = (function(method) {
  10681. return function() {return method.apply(this.doc, arguments)}
  10682. })(Doc.prototype[prop]); } }
  10683. eventMixin(Doc);
  10684. // INPUT HANDLING
  10685. CodeMirror$1.inputStyles = {"textarea": TextareaInput, "contenteditable": ContentEditableInput};
  10686. // MODE DEFINITION AND QUERYING
  10687. // Extra arguments are stored as the mode's dependencies, which is
  10688. // used by (legacy) mechanisms like loadmode.js to automatically
  10689. // load a mode. (Preferred mechanism is the require/define calls.)
  10690. CodeMirror$1.defineMode = function(name/*, mode, …*/) {
  10691. if (!CodeMirror$1.defaults.mode && name != "null") { CodeMirror$1.defaults.mode = name; }
  10692. defineMode.apply(this, arguments);
  10693. };
  10694. CodeMirror$1.defineMIME = defineMIME;
  10695. // Minimal default mode.
  10696. CodeMirror$1.defineMode("null", function () { return ({token: function (stream) { return stream.skipToEnd(); }}); });
  10697. CodeMirror$1.defineMIME("text/plain", "null");
  10698. // EXTENSIONS
  10699. CodeMirror$1.defineExtension = function (name, func) {
  10700. CodeMirror$1.prototype[name] = func;
  10701. };
  10702. CodeMirror$1.defineDocExtension = function (name, func) {
  10703. Doc.prototype[name] = func;
  10704. };
  10705. CodeMirror$1.fromTextArea = fromTextArea;
  10706. addLegacyProps(CodeMirror$1);
  10707. CodeMirror$1.version = "5.32.0";
  10708. return CodeMirror$1;
  10709. })));
  10710. },{}],11:[function(require,module,exports){
  10711. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  10712. // Distributed under an MIT license: http://codemirror.net/LICENSE
  10713. (function(mod) {
  10714. if (typeof exports == "object" && typeof module == "object") // CommonJS
  10715. mod(require("../../lib/codemirror"), require("../markdown/markdown"), require("../../addon/mode/overlay"));
  10716. else if (typeof define == "function" && define.amd) // AMD
  10717. define(["../../lib/codemirror", "../markdown/markdown", "../../addon/mode/overlay"], mod);
  10718. else // Plain browser env
  10719. mod(CodeMirror);
  10720. })(function(CodeMirror) {
  10721. "use strict";
  10722. 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
  10723. CodeMirror.defineMode("gfm", function(config, modeConfig) {
  10724. var codeDepth = 0;
  10725. function blankLine(state) {
  10726. state.code = false;
  10727. return null;
  10728. }
  10729. var gfmOverlay = {
  10730. startState: function() {
  10731. return {
  10732. code: false,
  10733. codeBlock: false,
  10734. ateSpace: false
  10735. };
  10736. },
  10737. copyState: function(s) {
  10738. return {
  10739. code: s.code,
  10740. codeBlock: s.codeBlock,
  10741. ateSpace: s.ateSpace
  10742. };
  10743. },
  10744. token: function(stream, state) {
  10745. state.combineTokens = null;
  10746. // Hack to prevent formatting override inside code blocks (block and inline)
  10747. if (state.codeBlock) {
  10748. if (stream.match(/^```+/)) {
  10749. state.codeBlock = false;
  10750. return null;
  10751. }
  10752. stream.skipToEnd();
  10753. return null;
  10754. }
  10755. if (stream.sol()) {
  10756. state.code = false;
  10757. }
  10758. if (stream.sol() && stream.match(/^```+/)) {
  10759. stream.skipToEnd();
  10760. state.codeBlock = true;
  10761. return null;
  10762. }
  10763. // If this block is changed, it may need to be updated in Markdown mode
  10764. if (stream.peek() === '`') {
  10765. stream.next();
  10766. var before = stream.pos;
  10767. stream.eatWhile('`');
  10768. var difference = 1 + stream.pos - before;
  10769. if (!state.code) {
  10770. codeDepth = difference;
  10771. state.code = true;
  10772. } else {
  10773. if (difference === codeDepth) { // Must be exact
  10774. state.code = false;
  10775. }
  10776. }
  10777. return null;
  10778. } else if (state.code) {
  10779. stream.next();
  10780. return null;
  10781. }
  10782. // Check if space. If so, links can be formatted later on
  10783. if (stream.eatSpace()) {
  10784. state.ateSpace = true;
  10785. return null;
  10786. }
  10787. if (stream.sol() || state.ateSpace) {
  10788. state.ateSpace = false;
  10789. if (modeConfig.gitHubSpice !== false) {
  10790. if(stream.match(/^(?:[a-zA-Z0-9\-_]+\/)?(?:[a-zA-Z0-9\-_]+@)?(?=.{0,6}\d)(?:[a-f0-9]{7,40}\b)/)) {
  10791. // User/Project@SHA
  10792. // User@SHA
  10793. // SHA
  10794. state.combineTokens = true;
  10795. return "link";
  10796. } else if (stream.match(/^(?:[a-zA-Z0-9\-_]+\/)?(?:[a-zA-Z0-9\-_]+)?#[0-9]+\b/)) {
  10797. // User/Project#Num
  10798. // User#Num
  10799. // #Num
  10800. state.combineTokens = true;
  10801. return "link";
  10802. }
  10803. }
  10804. }
  10805. if (stream.match(urlRE) &&
  10806. stream.string.slice(stream.start - 2, stream.start) != "](" &&
  10807. (stream.start == 0 || /\W/.test(stream.string.charAt(stream.start - 1)))) {
  10808. // URLs
  10809. // Taken from http://daringfireball.net/2010/07/improved_regex_for_matching_urls
  10810. // And then (issue #1160) simplified to make it not crash the Chrome Regexp engine
  10811. // And then limited url schemes to the CommonMark list, so foo:bar isn't matched as a URL
  10812. state.combineTokens = true;
  10813. return "link";
  10814. }
  10815. stream.next();
  10816. return null;
  10817. },
  10818. blankLine: blankLine
  10819. };
  10820. var markdownConfig = {
  10821. taskLists: true,
  10822. strikethrough: true,
  10823. emoji: true
  10824. };
  10825. for (var attr in modeConfig) {
  10826. markdownConfig[attr] = modeConfig[attr];
  10827. }
  10828. markdownConfig.name = "markdown";
  10829. return CodeMirror.overlayMode(CodeMirror.getMode(config, markdownConfig), gfmOverlay);
  10830. }, "markdown");
  10831. CodeMirror.defineMIME("text/x-gfm", "gfm");
  10832. });
  10833. },{"../../addon/mode/overlay":8,"../../lib/codemirror":10,"../markdown/markdown":12}],12:[function(require,module,exports){
  10834. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  10835. // Distributed under an MIT license: http://codemirror.net/LICENSE
  10836. (function(mod) {
  10837. if (typeof exports == "object" && typeof module == "object") // CommonJS
  10838. mod(require("../../lib/codemirror"), require("../xml/xml"), require("../meta"));
  10839. else if (typeof define == "function" && define.amd) // AMD
  10840. define(["../../lib/codemirror", "../xml/xml", "../meta"], mod);
  10841. else // Plain browser env
  10842. mod(CodeMirror);
  10843. })(function(CodeMirror) {
  10844. "use strict";
  10845. CodeMirror.defineMode("markdown", function(cmCfg, modeCfg) {
  10846. var htmlMode = CodeMirror.getMode(cmCfg, "text/html");
  10847. var htmlModeMissing = htmlMode.name == "null"
  10848. function getMode(name) {
  10849. if (CodeMirror.findModeByName) {
  10850. var found = CodeMirror.findModeByName(name);
  10851. if (found) name = found.mime || found.mimes[0];
  10852. }
  10853. var mode = CodeMirror.getMode(cmCfg, name);
  10854. return mode.name == "null" ? null : mode;
  10855. }
  10856. // Should characters that affect highlighting be highlighted separate?
  10857. // Does not include characters that will be output (such as `1.` and `-` for lists)
  10858. if (modeCfg.highlightFormatting === undefined)
  10859. modeCfg.highlightFormatting = false;
  10860. // Maximum number of nested blockquotes. Set to 0 for infinite nesting.
  10861. // Excess `>` will emit `error` token.
  10862. if (modeCfg.maxBlockquoteDepth === undefined)
  10863. modeCfg.maxBlockquoteDepth = 0;
  10864. // Turn on task lists? ("- [ ] " and "- [x] ")
  10865. if (modeCfg.taskLists === undefined) modeCfg.taskLists = false;
  10866. // Turn on strikethrough syntax
  10867. if (modeCfg.strikethrough === undefined)
  10868. modeCfg.strikethrough = false;
  10869. if (modeCfg.emoji === undefined)
  10870. modeCfg.emoji = false;
  10871. if (modeCfg.fencedCodeBlockHighlighting === undefined)
  10872. modeCfg.fencedCodeBlockHighlighting = true;
  10873. if (modeCfg.xml === undefined)
  10874. modeCfg.xml = true;
  10875. // Allow token types to be overridden by user-provided token types.
  10876. if (modeCfg.tokenTypeOverrides === undefined)
  10877. modeCfg.tokenTypeOverrides = {};
  10878. var tokenTypes = {
  10879. header: "header",
  10880. code: "comment",
  10881. quote: "quote",
  10882. list1: "variable-2",
  10883. list2: "variable-3",
  10884. list3: "keyword",
  10885. hr: "hr",
  10886. image: "image",
  10887. imageAltText: "image-alt-text",
  10888. imageMarker: "image-marker",
  10889. formatting: "formatting",
  10890. linkInline: "link",
  10891. linkEmail: "link",
  10892. linkText: "link",
  10893. linkHref: "string",
  10894. em: "em",
  10895. strong: "strong",
  10896. strikethrough: "strikethrough",
  10897. emoji: "builtin"
  10898. };
  10899. for (var tokenType in tokenTypes) {
  10900. if (tokenTypes.hasOwnProperty(tokenType) && modeCfg.tokenTypeOverrides[tokenType]) {
  10901. tokenTypes[tokenType] = modeCfg.tokenTypeOverrides[tokenType];
  10902. }
  10903. }
  10904. var hrRE = /^([*\-_])(?:\s*\1){2,}\s*$/
  10905. , listRE = /^(?:[*\-+]|^[0-9]+([.)]))\s+/
  10906. , taskListRE = /^\[(x| )\](?=\s)/i // Must follow listRE
  10907. , atxHeaderRE = modeCfg.allowAtxHeaderWithoutSpace ? /^(#+)/ : /^(#+)(?: |$)/
  10908. , setextHeaderRE = /^ *(?:\={1,}|-{1,})\s*$/
  10909. , textRE = /^[^#!\[\]*_\\<>` "'(~:]+/
  10910. , fencedCodeRE = /^(~~~+|```+)[ \t]*([\w+#-]*)[^\n`]*$/
  10911. , linkDefRE = /^\s*\[[^\]]+?\]:\s*\S+(\s*\S*\s*)?$/ // naive link-definition
  10912. , punctuation = /[!\"#$%&\'()*+,\-\.\/:;<=>?@\[\\\]^_`{|}~—]/
  10913. , expandedTab = " " // CommonMark specifies tab as 4 spaces
  10914. function switchInline(stream, state, f) {
  10915. state.f = state.inline = f;
  10916. return f(stream, state);
  10917. }
  10918. function switchBlock(stream, state, f) {
  10919. state.f = state.block = f;
  10920. return f(stream, state);
  10921. }
  10922. function lineIsEmpty(line) {
  10923. return !line || !/\S/.test(line.string)
  10924. }
  10925. // Blocks
  10926. function blankLine(state) {
  10927. // Reset linkTitle state
  10928. state.linkTitle = false;
  10929. // Reset EM state
  10930. state.em = false;
  10931. // Reset STRONG state
  10932. state.strong = false;
  10933. // Reset strikethrough state
  10934. state.strikethrough = false;
  10935. // Reset state.quote
  10936. state.quote = 0;
  10937. // Reset state.indentedCode
  10938. state.indentedCode = false;
  10939. if (state.f == htmlBlock) {
  10940. state.f = inlineNormal;
  10941. state.block = blockNormal;
  10942. }
  10943. // Reset state.trailingSpace
  10944. state.trailingSpace = 0;
  10945. state.trailingSpaceNewLine = false;
  10946. // Mark this line as blank
  10947. state.prevLine = state.thisLine
  10948. state.thisLine = {stream: null}
  10949. return null;
  10950. }
  10951. function blockNormal(stream, state) {
  10952. var firstTokenOnLine = stream.column() === state.indentation;
  10953. var prevLineLineIsEmpty = lineIsEmpty(state.prevLine.stream);
  10954. var prevLineIsIndentedCode = state.indentedCode;
  10955. var prevLineIsHr = state.prevLine.hr;
  10956. var prevLineIsList = state.list !== false;
  10957. var maxNonCodeIndentation = (state.listStack[state.listStack.length - 1] || 0) + 3;
  10958. state.indentedCode = false;
  10959. var lineIndentation = state.indentation;
  10960. // compute once per line (on first token)
  10961. if (state.indentationDiff === null) {
  10962. state.indentationDiff = state.indentation;
  10963. if (prevLineIsList) {
  10964. state.list = null;
  10965. // While this list item's marker's indentation is less than the deepest
  10966. // list item's content's indentation,pop the deepest list item
  10967. // indentation off the stack, and update block indentation state
  10968. while (lineIndentation < state.listStack[state.listStack.length - 1]) {
  10969. state.listStack.pop();
  10970. if (state.listStack.length) {
  10971. state.indentation = state.listStack[state.listStack.length - 1];
  10972. // less than the first list's indent -> the line is no longer a list
  10973. } else {
  10974. state.list = false;
  10975. }
  10976. }
  10977. if (state.list !== false) {
  10978. state.indentationDiff = lineIndentation - state.listStack[state.listStack.length - 1]
  10979. }
  10980. }
  10981. }
  10982. // not comprehensive (currently only for setext detection purposes)
  10983. var allowsInlineContinuation = (
  10984. !prevLineLineIsEmpty && !prevLineIsHr && !state.prevLine.header &&
  10985. (!prevLineIsList || !prevLineIsIndentedCode) &&
  10986. !state.prevLine.fencedCodeEnd
  10987. );
  10988. var isHr = (state.list === false || prevLineIsHr || prevLineLineIsEmpty) &&
  10989. state.indentation <= maxNonCodeIndentation && stream.match(hrRE);
  10990. var match = null;
  10991. if (state.indentationDiff >= 4 && (prevLineIsIndentedCode || state.prevLine.fencedCodeEnd ||
  10992. state.prevLine.header || prevLineLineIsEmpty)) {
  10993. stream.skipToEnd();
  10994. state.indentedCode = true;
  10995. return tokenTypes.code;
  10996. } else if (stream.eatSpace()) {
  10997. return null;
  10998. } else if (firstTokenOnLine && state.indentation <= maxNonCodeIndentation && (match = stream.match(atxHeaderRE)) && match[1].length <= 6) {
  10999. state.quote = 0;
  11000. state.header = match[1].length;
  11001. state.thisLine.header = true;
  11002. if (modeCfg.highlightFormatting) state.formatting = "header";
  11003. state.f = state.inline;
  11004. return getType(state);
  11005. } else if (state.indentation <= maxNonCodeIndentation && stream.eat('>')) {
  11006. state.quote = firstTokenOnLine ? 1 : state.quote + 1;
  11007. if (modeCfg.highlightFormatting) state.formatting = "quote";
  11008. stream.eatSpace();
  11009. return getType(state);
  11010. } else if (!isHr && !state.setext && firstTokenOnLine && state.indentation <= maxNonCodeIndentation && (match = stream.match(listRE))) {
  11011. var listType = match[1] ? "ol" : "ul";
  11012. state.indentation = lineIndentation + stream.current().length;
  11013. state.list = true;
  11014. state.quote = 0;
  11015. // Add this list item's content's indentation to the stack
  11016. state.listStack.push(state.indentation);
  11017. if (modeCfg.taskLists && stream.match(taskListRE, false)) {
  11018. state.taskList = true;
  11019. }
  11020. state.f = state.inline;
  11021. if (modeCfg.highlightFormatting) state.formatting = ["list", "list-" + listType];
  11022. return getType(state);
  11023. } else if (firstTokenOnLine && state.indentation <= maxNonCodeIndentation && (match = stream.match(fencedCodeRE, true))) {
  11024. state.quote = 0;
  11025. state.fencedEndRE = new RegExp(match[1] + "+ *$");
  11026. // try switching mode
  11027. state.localMode = modeCfg.fencedCodeBlockHighlighting && getMode(match[2]);
  11028. if (state.localMode) state.localState = CodeMirror.startState(state.localMode);
  11029. state.f = state.block = local;
  11030. if (modeCfg.highlightFormatting) state.formatting = "code-block";
  11031. state.code = -1
  11032. return getType(state);
  11033. // SETEXT has lowest block-scope precedence after HR, so check it after
  11034. // the others (code, blockquote, list...)
  11035. } else if (
  11036. // if setext set, indicates line after ---/===
  11037. state.setext || (
  11038. // line before ---/===
  11039. (!allowsInlineContinuation || !prevLineIsList) && !state.quote && state.list === false &&
  11040. !state.code && !isHr && !linkDefRE.test(stream.string) &&
  11041. (match = stream.lookAhead(1)) && (match = match.match(setextHeaderRE))
  11042. )
  11043. ) {
  11044. if ( !state.setext ) {
  11045. state.header = match[0].charAt(0) == '=' ? 1 : 2;
  11046. state.setext = state.header;
  11047. } else {
  11048. state.header = state.setext;
  11049. // has no effect on type so we can reset it now
  11050. state.setext = 0;
  11051. stream.skipToEnd();
  11052. if (modeCfg.highlightFormatting) state.formatting = "header";
  11053. }
  11054. state.thisLine.header = true;
  11055. state.f = state.inline;
  11056. return getType(state);
  11057. } else if (isHr) {
  11058. stream.skipToEnd();
  11059. state.hr = true;
  11060. state.thisLine.hr = true;
  11061. return tokenTypes.hr;
  11062. } else if (stream.peek() === '[') {
  11063. return switchInline(stream, state, footnoteLink);
  11064. }
  11065. return switchInline(stream, state, state.inline);
  11066. }
  11067. function htmlBlock(stream, state) {
  11068. var style = htmlMode.token(stream, state.htmlState);
  11069. if (!htmlModeMissing) {
  11070. var inner = CodeMirror.innerMode(htmlMode, state.htmlState)
  11071. if ((inner.mode.name == "xml" && inner.state.tagStart === null &&
  11072. (!inner.state.context && inner.state.tokenize.isInText)) ||
  11073. (state.md_inside && stream.current().indexOf(">") > -1)) {
  11074. state.f = inlineNormal;
  11075. state.block = blockNormal;
  11076. state.htmlState = null;
  11077. }
  11078. }
  11079. return style;
  11080. }
  11081. function local(stream, state) {
  11082. var currListInd = state.listStack[state.listStack.length - 1] || 0;
  11083. var hasExitedList = state.indentation < currListInd;
  11084. var maxFencedEndInd = currListInd + 3;
  11085. if (state.fencedEndRE && state.indentation <= maxFencedEndInd && (hasExitedList || stream.match(state.fencedEndRE))) {
  11086. if (modeCfg.highlightFormatting) state.formatting = "code-block";
  11087. var returnType;
  11088. if (!hasExitedList) returnType = getType(state)
  11089. state.localMode = state.localState = null;
  11090. state.block = blockNormal;
  11091. state.f = inlineNormal;
  11092. state.fencedEndRE = null;
  11093. state.code = 0
  11094. state.thisLine.fencedCodeEnd = true;
  11095. if (hasExitedList) return switchBlock(stream, state, state.block);
  11096. return returnType;
  11097. } else if (state.localMode) {
  11098. return state.localMode.token(stream, state.localState);
  11099. } else {
  11100. stream.skipToEnd();
  11101. return tokenTypes.code;
  11102. }
  11103. }
  11104. // Inline
  11105. function getType(state) {
  11106. var styles = [];
  11107. if (state.formatting) {
  11108. styles.push(tokenTypes.formatting);
  11109. if (typeof state.formatting === "string") state.formatting = [state.formatting];
  11110. for (var i = 0; i < state.formatting.length; i++) {
  11111. styles.push(tokenTypes.formatting + "-" + state.formatting[i]);
  11112. if (state.formatting[i] === "header") {
  11113. styles.push(tokenTypes.formatting + "-" + state.formatting[i] + "-" + state.header);
  11114. }
  11115. // Add `formatting-quote` and `formatting-quote-#` for blockquotes
  11116. // Add `error` instead if the maximum blockquote nesting depth is passed
  11117. if (state.formatting[i] === "quote") {
  11118. if (!modeCfg.maxBlockquoteDepth || modeCfg.maxBlockquoteDepth >= state.quote) {
  11119. styles.push(tokenTypes.formatting + "-" + state.formatting[i] + "-" + state.quote);
  11120. } else {
  11121. styles.push("error");
  11122. }
  11123. }
  11124. }
  11125. }
  11126. if (state.taskOpen) {
  11127. styles.push("meta");
  11128. return styles.length ? styles.join(' ') : null;
  11129. }
  11130. if (state.taskClosed) {
  11131. styles.push("property");
  11132. return styles.length ? styles.join(' ') : null;
  11133. }
  11134. if (state.linkHref) {
  11135. styles.push(tokenTypes.linkHref, "url");
  11136. } else { // Only apply inline styles to non-url text
  11137. if (state.strong) { styles.push(tokenTypes.strong); }
  11138. if (state.em) { styles.push(tokenTypes.em); }
  11139. if (state.strikethrough) { styles.push(tokenTypes.strikethrough); }
  11140. if (state.emoji) { styles.push(tokenTypes.emoji); }
  11141. if (state.linkText) { styles.push(tokenTypes.linkText); }
  11142. if (state.code) { styles.push(tokenTypes.code); }
  11143. if (state.image) { styles.push(tokenTypes.image); }
  11144. if (state.imageAltText) { styles.push(tokenTypes.imageAltText, "link"); }
  11145. if (state.imageMarker) { styles.push(tokenTypes.imageMarker); }
  11146. }
  11147. if (state.header) { styles.push(tokenTypes.header, tokenTypes.header + "-" + state.header); }
  11148. if (state.quote) {
  11149. styles.push(tokenTypes.quote);
  11150. // Add `quote-#` where the maximum for `#` is modeCfg.maxBlockquoteDepth
  11151. if (!modeCfg.maxBlockquoteDepth || modeCfg.maxBlockquoteDepth >= state.quote) {
  11152. styles.push(tokenTypes.quote + "-" + state.quote);
  11153. } else {
  11154. styles.push(tokenTypes.quote + "-" + modeCfg.maxBlockquoteDepth);
  11155. }
  11156. }
  11157. if (state.list !== false) {
  11158. var listMod = (state.listStack.length - 1) % 3;
  11159. if (!listMod) {
  11160. styles.push(tokenTypes.list1);
  11161. } else if (listMod === 1) {
  11162. styles.push(tokenTypes.list2);
  11163. } else {
  11164. styles.push(tokenTypes.list3);
  11165. }
  11166. }
  11167. if (state.trailingSpaceNewLine) {
  11168. styles.push("trailing-space-new-line");
  11169. } else if (state.trailingSpace) {
  11170. styles.push("trailing-space-" + (state.trailingSpace % 2 ? "a" : "b"));
  11171. }
  11172. return styles.length ? styles.join(' ') : null;
  11173. }
  11174. function handleText(stream, state) {
  11175. if (stream.match(textRE, true)) {
  11176. return getType(state);
  11177. }
  11178. return undefined;
  11179. }
  11180. function inlineNormal(stream, state) {
  11181. var style = state.text(stream, state);
  11182. if (typeof style !== 'undefined')
  11183. return style;
  11184. if (state.list) { // List marker (*, +, -, 1., etc)
  11185. state.list = null;
  11186. return getType(state);
  11187. }
  11188. if (state.taskList) {
  11189. var taskOpen = stream.match(taskListRE, true)[1] === " ";
  11190. if (taskOpen) state.taskOpen = true;
  11191. else state.taskClosed = true;
  11192. if (modeCfg.highlightFormatting) state.formatting = "task";
  11193. state.taskList = false;
  11194. return getType(state);
  11195. }
  11196. state.taskOpen = false;
  11197. state.taskClosed = false;
  11198. if (state.header && stream.match(/^#+$/, true)) {
  11199. if (modeCfg.highlightFormatting) state.formatting = "header";
  11200. return getType(state);
  11201. }
  11202. var ch = stream.next();
  11203. // Matches link titles present on next line
  11204. if (state.linkTitle) {
  11205. state.linkTitle = false;
  11206. var matchCh = ch;
  11207. if (ch === '(') {
  11208. matchCh = ')';
  11209. }
  11210. matchCh = (matchCh+'').replace(/([.?*+^\[\]\\(){}|-])/g, "\\$1");
  11211. var regex = '^\\s*(?:[^' + matchCh + '\\\\]+|\\\\\\\\|\\\\.)' + matchCh;
  11212. if (stream.match(new RegExp(regex), true)) {
  11213. return tokenTypes.linkHref;
  11214. }
  11215. }
  11216. // If this block is changed, it may need to be updated in GFM mode
  11217. if (ch === '`') {
  11218. var previousFormatting = state.formatting;
  11219. if (modeCfg.highlightFormatting) state.formatting = "code";
  11220. stream.eatWhile('`');
  11221. var count = stream.current().length
  11222. if (state.code == 0 && (!state.quote || count == 1)) {
  11223. state.code = count
  11224. return getType(state)
  11225. } else if (count == state.code) { // Must be exact
  11226. var t = getType(state)
  11227. state.code = 0
  11228. return t
  11229. } else {
  11230. state.formatting = previousFormatting
  11231. return getType(state)
  11232. }
  11233. } else if (state.code) {
  11234. return getType(state);
  11235. }
  11236. if (ch === '\\') {
  11237. stream.next();
  11238. if (modeCfg.highlightFormatting) {
  11239. var type = getType(state);
  11240. var formattingEscape = tokenTypes.formatting + "-escape";
  11241. return type ? type + " " + formattingEscape : formattingEscape;
  11242. }
  11243. }
  11244. if (ch === '!' && stream.match(/\[[^\]]*\] ?(?:\(|\[)/, false)) {
  11245. state.imageMarker = true;
  11246. state.image = true;
  11247. if (modeCfg.highlightFormatting) state.formatting = "image";
  11248. return getType(state);
  11249. }
  11250. if (ch === '[' && state.imageMarker && stream.match(/[^\]]*\](\(.*?\)| ?\[.*?\])/, false)) {
  11251. state.imageMarker = false;
  11252. state.imageAltText = true
  11253. if (modeCfg.highlightFormatting) state.formatting = "image";
  11254. return getType(state);
  11255. }
  11256. if (ch === ']' && state.imageAltText) {
  11257. if (modeCfg.highlightFormatting) state.formatting = "image";
  11258. var type = getType(state);
  11259. state.imageAltText = false;
  11260. state.image = false;
  11261. state.inline = state.f = linkHref;
  11262. return type;
  11263. }
  11264. if (ch === '[' && !state.image) {
  11265. state.linkText = true;
  11266. if (modeCfg.highlightFormatting) state.formatting = "link";
  11267. return getType(state);
  11268. }
  11269. if (ch === ']' && state.linkText) {
  11270. if (modeCfg.highlightFormatting) state.formatting = "link";
  11271. var type = getType(state);
  11272. state.linkText = false;
  11273. state.inline = state.f = stream.match(/\(.*?\)| ?\[.*?\]/, false) ? linkHref : inlineNormal
  11274. return type;
  11275. }
  11276. if (ch === '<' && stream.match(/^(https?|ftps?):\/\/(?:[^\\>]|\\.)+>/, false)) {
  11277. state.f = state.inline = linkInline;
  11278. if (modeCfg.highlightFormatting) state.formatting = "link";
  11279. var type = getType(state);
  11280. if (type){
  11281. type += " ";
  11282. } else {
  11283. type = "";
  11284. }
  11285. return type + tokenTypes.linkInline;
  11286. }
  11287. if (ch === '<' && stream.match(/^[^> \\]+@(?:[^\\>]|\\.)+>/, false)) {
  11288. state.f = state.inline = linkInline;
  11289. if (modeCfg.highlightFormatting) state.formatting = "link";
  11290. var type = getType(state);
  11291. if (type){
  11292. type += " ";
  11293. } else {
  11294. type = "";
  11295. }
  11296. return type + tokenTypes.linkEmail;
  11297. }
  11298. if (modeCfg.xml && ch === '<' && stream.match(/^(!--|[a-z]+(?:\s+[a-z_:.\-]+(?:\s*=\s*[^ >]+)?)*\s*>)/i, false)) {
  11299. var end = stream.string.indexOf(">", stream.pos);
  11300. if (end != -1) {
  11301. var atts = stream.string.substring(stream.start, end);
  11302. if (/markdown\s*=\s*('|"){0,1}1('|"){0,1}/.test(atts)) state.md_inside = true;
  11303. }
  11304. stream.backUp(1);
  11305. state.htmlState = CodeMirror.startState(htmlMode);
  11306. return switchBlock(stream, state, htmlBlock);
  11307. }
  11308. if (modeCfg.xml && ch === '<' && stream.match(/^\/\w*?>/)) {
  11309. state.md_inside = false;
  11310. return "tag";
  11311. } else if (ch === "*" || ch === "_") {
  11312. var len = 1, before = stream.pos == 1 ? " " : stream.string.charAt(stream.pos - 2)
  11313. while (len < 3 && stream.eat(ch)) len++
  11314. var after = stream.peek() || " "
  11315. // See http://spec.commonmark.org/0.27/#emphasis-and-strong-emphasis
  11316. var leftFlanking = !/\s/.test(after) && (!punctuation.test(after) || /\s/.test(before) || punctuation.test(before))
  11317. var rightFlanking = !/\s/.test(before) && (!punctuation.test(before) || /\s/.test(after) || punctuation.test(after))
  11318. var setEm = null, setStrong = null
  11319. if (len % 2) { // Em
  11320. if (!state.em && leftFlanking && (ch === "*" || !rightFlanking || punctuation.test(before)))
  11321. setEm = true
  11322. else if (state.em == ch && rightFlanking && (ch === "*" || !leftFlanking || punctuation.test(after)))
  11323. setEm = false
  11324. }
  11325. if (len > 1) { // Strong
  11326. if (!state.strong && leftFlanking && (ch === "*" || !rightFlanking || punctuation.test(before)))
  11327. setStrong = true
  11328. else if (state.strong == ch && rightFlanking && (ch === "*" || !leftFlanking || punctuation.test(after)))
  11329. setStrong = false
  11330. }
  11331. if (setStrong != null || setEm != null) {
  11332. if (modeCfg.highlightFormatting) state.formatting = setEm == null ? "strong" : setStrong == null ? "em" : "strong em"
  11333. if (setEm === true) state.em = ch
  11334. if (setStrong === true) state.strong = ch
  11335. var t = getType(state)
  11336. if (setEm === false) state.em = false
  11337. if (setStrong === false) state.strong = false
  11338. return t
  11339. }
  11340. } else if (ch === ' ') {
  11341. if (stream.eat('*') || stream.eat('_')) { // Probably surrounded by spaces
  11342. if (stream.peek() === ' ') { // Surrounded by spaces, ignore
  11343. return getType(state);
  11344. } else { // Not surrounded by spaces, back up pointer
  11345. stream.backUp(1);
  11346. }
  11347. }
  11348. }
  11349. if (modeCfg.strikethrough) {
  11350. if (ch === '~' && stream.eatWhile(ch)) {
  11351. if (state.strikethrough) {// Remove strikethrough
  11352. if (modeCfg.highlightFormatting) state.formatting = "strikethrough";
  11353. var t = getType(state);
  11354. state.strikethrough = false;
  11355. return t;
  11356. } else if (stream.match(/^[^\s]/, false)) {// Add strikethrough
  11357. state.strikethrough = true;
  11358. if (modeCfg.highlightFormatting) state.formatting = "strikethrough";
  11359. return getType(state);
  11360. }
  11361. } else if (ch === ' ') {
  11362. if (stream.match(/^~~/, true)) { // Probably surrounded by space
  11363. if (stream.peek() === ' ') { // Surrounded by spaces, ignore
  11364. return getType(state);
  11365. } else { // Not surrounded by spaces, back up pointer
  11366. stream.backUp(2);
  11367. }
  11368. }
  11369. }
  11370. }
  11371. if (modeCfg.emoji && ch === ":" && stream.match(/^[a-z_\d+-]+:/)) {
  11372. state.emoji = true;
  11373. if (modeCfg.highlightFormatting) state.formatting = "emoji";
  11374. var retType = getType(state);
  11375. state.emoji = false;
  11376. return retType;
  11377. }
  11378. if (ch === ' ') {
  11379. if (stream.match(/ +$/, false)) {
  11380. state.trailingSpace++;
  11381. } else if (state.trailingSpace) {
  11382. state.trailingSpaceNewLine = true;
  11383. }
  11384. }
  11385. return getType(state);
  11386. }
  11387. function linkInline(stream, state) {
  11388. var ch = stream.next();
  11389. if (ch === ">") {
  11390. state.f = state.inline = inlineNormal;
  11391. if (modeCfg.highlightFormatting) state.formatting = "link";
  11392. var type = getType(state);
  11393. if (type){
  11394. type += " ";
  11395. } else {
  11396. type = "";
  11397. }
  11398. return type + tokenTypes.linkInline;
  11399. }
  11400. stream.match(/^[^>]+/, true);
  11401. return tokenTypes.linkInline;
  11402. }
  11403. function linkHref(stream, state) {
  11404. // Check if space, and return NULL if so (to avoid marking the space)
  11405. if(stream.eatSpace()){
  11406. return null;
  11407. }
  11408. var ch = stream.next();
  11409. if (ch === '(' || ch === '[') {
  11410. state.f = state.inline = getLinkHrefInside(ch === "(" ? ")" : "]");
  11411. if (modeCfg.highlightFormatting) state.formatting = "link-string";
  11412. state.linkHref = true;
  11413. return getType(state);
  11414. }
  11415. return 'error';
  11416. }
  11417. var linkRE = {
  11418. ")": /^(?:[^\\\(\)]|\\.|\((?:[^\\\(\)]|\\.)*\))*?(?=\))/,
  11419. "]": /^(?:[^\\\[\]]|\\.|\[(?:[^\\\[\]]|\\.)*\])*?(?=\])/
  11420. }
  11421. function getLinkHrefInside(endChar) {
  11422. return function(stream, state) {
  11423. var ch = stream.next();
  11424. if (ch === endChar) {
  11425. state.f = state.inline = inlineNormal;
  11426. if (modeCfg.highlightFormatting) state.formatting = "link-string";
  11427. var returnState = getType(state);
  11428. state.linkHref = false;
  11429. return returnState;
  11430. }
  11431. stream.match(linkRE[endChar])
  11432. state.linkHref = true;
  11433. return getType(state);
  11434. };
  11435. }
  11436. function footnoteLink(stream, state) {
  11437. if (stream.match(/^([^\]\\]|\\.)*\]:/, false)) {
  11438. state.f = footnoteLinkInside;
  11439. stream.next(); // Consume [
  11440. if (modeCfg.highlightFormatting) state.formatting = "link";
  11441. state.linkText = true;
  11442. return getType(state);
  11443. }
  11444. return switchInline(stream, state, inlineNormal);
  11445. }
  11446. function footnoteLinkInside(stream, state) {
  11447. if (stream.match(/^\]:/, true)) {
  11448. state.f = state.inline = footnoteUrl;
  11449. if (modeCfg.highlightFormatting) state.formatting = "link";
  11450. var returnType = getType(state);
  11451. state.linkText = false;
  11452. return returnType;
  11453. }
  11454. stream.match(/^([^\]\\]|\\.)+/, true);
  11455. return tokenTypes.linkText;
  11456. }
  11457. function footnoteUrl(stream, state) {
  11458. // Check if space, and return NULL if so (to avoid marking the space)
  11459. if(stream.eatSpace()){
  11460. return null;
  11461. }
  11462. // Match URL
  11463. stream.match(/^[^\s]+/, true);
  11464. // Check for link title
  11465. if (stream.peek() === undefined) { // End of line, set flag to check next line
  11466. state.linkTitle = true;
  11467. } else { // More content on line, check if link title
  11468. stream.match(/^(?:\s+(?:"(?:[^"\\]|\\\\|\\.)+"|'(?:[^'\\]|\\\\|\\.)+'|\((?:[^)\\]|\\\\|\\.)+\)))?/, true);
  11469. }
  11470. state.f = state.inline = inlineNormal;
  11471. return tokenTypes.linkHref + " url";
  11472. }
  11473. var mode = {
  11474. startState: function() {
  11475. return {
  11476. f: blockNormal,
  11477. prevLine: {stream: null},
  11478. thisLine: {stream: null},
  11479. block: blockNormal,
  11480. htmlState: null,
  11481. indentation: 0,
  11482. inline: inlineNormal,
  11483. text: handleText,
  11484. formatting: false,
  11485. linkText: false,
  11486. linkHref: false,
  11487. linkTitle: false,
  11488. code: 0,
  11489. em: false,
  11490. strong: false,
  11491. header: 0,
  11492. setext: 0,
  11493. hr: false,
  11494. taskList: false,
  11495. list: false,
  11496. listStack: [],
  11497. quote: 0,
  11498. trailingSpace: 0,
  11499. trailingSpaceNewLine: false,
  11500. strikethrough: false,
  11501. emoji: false,
  11502. fencedEndRE: null
  11503. };
  11504. },
  11505. copyState: function(s) {
  11506. return {
  11507. f: s.f,
  11508. prevLine: s.prevLine,
  11509. thisLine: s.thisLine,
  11510. block: s.block,
  11511. htmlState: s.htmlState && CodeMirror.copyState(htmlMode, s.htmlState),
  11512. indentation: s.indentation,
  11513. localMode: s.localMode,
  11514. localState: s.localMode ? CodeMirror.copyState(s.localMode, s.localState) : null,
  11515. inline: s.inline,
  11516. text: s.text,
  11517. formatting: false,
  11518. linkText: s.linkText,
  11519. linkTitle: s.linkTitle,
  11520. code: s.code,
  11521. em: s.em,
  11522. strong: s.strong,
  11523. strikethrough: s.strikethrough,
  11524. emoji: s.emoji,
  11525. header: s.header,
  11526. setext: s.setext,
  11527. hr: s.hr,
  11528. taskList: s.taskList,
  11529. list: s.list,
  11530. listStack: s.listStack.slice(0),
  11531. quote: s.quote,
  11532. indentedCode: s.indentedCode,
  11533. trailingSpace: s.trailingSpace,
  11534. trailingSpaceNewLine: s.trailingSpaceNewLine,
  11535. md_inside: s.md_inside,
  11536. fencedEndRE: s.fencedEndRE
  11537. };
  11538. },
  11539. token: function(stream, state) {
  11540. // Reset state.formatting
  11541. state.formatting = false;
  11542. if (stream != state.thisLine.stream) {
  11543. state.header = 0;
  11544. state.hr = false;
  11545. if (stream.match(/^\s*$/, true)) {
  11546. blankLine(state);
  11547. return null;
  11548. }
  11549. state.prevLine = state.thisLine
  11550. state.thisLine = {stream: stream}
  11551. // Reset state.taskList
  11552. state.taskList = false;
  11553. // Reset state.trailingSpace
  11554. state.trailingSpace = 0;
  11555. state.trailingSpaceNewLine = false;
  11556. if (!state.localState) {
  11557. state.f = state.block;
  11558. if (state.f != htmlBlock) {
  11559. var indentation = stream.match(/^\s*/, true)[0].replace(/\t/g, expandedTab).length;
  11560. state.indentation = indentation;
  11561. state.indentationDiff = null;
  11562. if (indentation > 0) return null;
  11563. }
  11564. }
  11565. }
  11566. return state.f(stream, state);
  11567. },
  11568. innerMode: function(state) {
  11569. if (state.block == htmlBlock) return {state: state.htmlState, mode: htmlMode};
  11570. if (state.localState) return {state: state.localState, mode: state.localMode};
  11571. return {state: state, mode: mode};
  11572. },
  11573. indent: function(state, textAfter, line) {
  11574. if (state.block == htmlBlock && htmlMode.indent) return htmlMode.indent(state.htmlState, textAfter, line)
  11575. if (state.localState && state.localMode.indent) return state.localMode.indent(state.localState, textAfter, line)
  11576. return CodeMirror.Pass
  11577. },
  11578. blankLine: blankLine,
  11579. getType: getType,
  11580. closeBrackets: "()[]{}''\"\"``",
  11581. fold: "markdown"
  11582. };
  11583. return mode;
  11584. }, "xml");
  11585. CodeMirror.defineMIME("text/x-markdown", "markdown");
  11586. });
  11587. },{"../../lib/codemirror":10,"../meta":13,"../xml/xml":14}],13:[function(require,module,exports){
  11588. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  11589. // Distributed under an MIT license: http://codemirror.net/LICENSE
  11590. (function(mod) {
  11591. if (typeof exports == "object" && typeof module == "object") // CommonJS
  11592. mod(require("../lib/codemirror"));
  11593. else if (typeof define == "function" && define.amd) // AMD
  11594. define(["../lib/codemirror"], mod);
  11595. else // Plain browser env
  11596. mod(CodeMirror);
  11597. })(function(CodeMirror) {
  11598. "use strict";
  11599. CodeMirror.modeInfo = [
  11600. {name: "APL", mime: "text/apl", mode: "apl", ext: ["dyalog", "apl"]},
  11601. {name: "PGP", mimes: ["application/pgp", "application/pgp-encrypted", "application/pgp-keys", "application/pgp-signature"], mode: "asciiarmor", ext: ["asc", "pgp", "sig"]},
  11602. {name: "ASN.1", mime: "text/x-ttcn-asn", mode: "asn.1", ext: ["asn", "asn1"]},
  11603. {name: "Asterisk", mime: "text/x-asterisk", mode: "asterisk", file: /^extensions\.conf$/i},
  11604. {name: "Brainfuck", mime: "text/x-brainfuck", mode: "brainfuck", ext: ["b", "bf"]},
  11605. {name: "C", mime: "text/x-csrc", mode: "clike", ext: ["c", "h"]},
  11606. {name: "C++", mime: "text/x-c++src", mode: "clike", ext: ["cpp", "c++", "cc", "cxx", "hpp", "h++", "hh", "hxx"], alias: ["cpp"]},
  11607. {name: "Cobol", mime: "text/x-cobol", mode: "cobol", ext: ["cob", "cpy"]},
  11608. {name: "C#", mime: "text/x-csharp", mode: "clike", ext: ["cs"], alias: ["csharp"]},
  11609. {name: "Clojure", mime: "text/x-clojure", mode: "clojure", ext: ["clj", "cljc", "cljx"]},
  11610. {name: "ClojureScript", mime: "text/x-clojurescript", mode: "clojure", ext: ["cljs"]},
  11611. {name: "Closure Stylesheets (GSS)", mime: "text/x-gss", mode: "css", ext: ["gss"]},
  11612. {name: "CMake", mime: "text/x-cmake", mode: "cmake", ext: ["cmake", "cmake.in"], file: /^CMakeLists.txt$/},
  11613. {name: "CoffeeScript", mimes: ["application/vnd.coffeescript", "text/coffeescript", "text/x-coffeescript"], mode: "coffeescript", ext: ["coffee"], alias: ["coffee", "coffee-script"]},
  11614. {name: "Common Lisp", mime: "text/x-common-lisp", mode: "commonlisp", ext: ["cl", "lisp", "el"], alias: ["lisp"]},
  11615. {name: "Cypher", mime: "application/x-cypher-query", mode: "cypher", ext: ["cyp", "cypher"]},
  11616. {name: "Cython", mime: "text/x-cython", mode: "python", ext: ["pyx", "pxd", "pxi"]},
  11617. {name: "Crystal", mime: "text/x-crystal", mode: "crystal", ext: ["cr"]},
  11618. {name: "CSS", mime: "text/css", mode: "css", ext: ["css"]},
  11619. {name: "CQL", mime: "text/x-cassandra", mode: "sql", ext: ["cql"]},
  11620. {name: "D", mime: "text/x-d", mode: "d", ext: ["d"]},
  11621. {name: "Dart", mimes: ["application/dart", "text/x-dart"], mode: "dart", ext: ["dart"]},
  11622. {name: "diff", mime: "text/x-diff", mode: "diff", ext: ["diff", "patch"]},
  11623. {name: "Django", mime: "text/x-django", mode: "django"},
  11624. {name: "Dockerfile", mime: "text/x-dockerfile", mode: "dockerfile", file: /^Dockerfile$/},
  11625. {name: "DTD", mime: "application/xml-dtd", mode: "dtd", ext: ["dtd"]},
  11626. {name: "Dylan", mime: "text/x-dylan", mode: "dylan", ext: ["dylan", "dyl", "intr"]},
  11627. {name: "EBNF", mime: "text/x-ebnf", mode: "ebnf"},
  11628. {name: "ECL", mime: "text/x-ecl", mode: "ecl", ext: ["ecl"]},
  11629. {name: "edn", mime: "application/edn", mode: "clojure", ext: ["edn"]},
  11630. {name: "Eiffel", mime: "text/x-eiffel", mode: "eiffel", ext: ["e"]},
  11631. {name: "Elm", mime: "text/x-elm", mode: "elm", ext: ["elm"]},
  11632. {name: "Embedded Javascript", mime: "application/x-ejs", mode: "htmlembedded", ext: ["ejs"]},
  11633. {name: "Embedded Ruby", mime: "application/x-erb", mode: "htmlembedded", ext: ["erb"]},
  11634. {name: "Erlang", mime: "text/x-erlang", mode: "erlang", ext: ["erl"]},
  11635. {name: "Esper", mime: "text/x-esper", mode: "sql"},
  11636. {name: "Factor", mime: "text/x-factor", mode: "factor", ext: ["factor"]},
  11637. {name: "FCL", mime: "text/x-fcl", mode: "fcl"},
  11638. {name: "Forth", mime: "text/x-forth", mode: "forth", ext: ["forth", "fth", "4th"]},
  11639. {name: "Fortran", mime: "text/x-fortran", mode: "fortran", ext: ["f", "for", "f77", "f90"]},
  11640. {name: "F#", mime: "text/x-fsharp", mode: "mllike", ext: ["fs"], alias: ["fsharp"]},
  11641. {name: "Gas", mime: "text/x-gas", mode: "gas", ext: ["s"]},
  11642. {name: "Gherkin", mime: "text/x-feature", mode: "gherkin", ext: ["feature"]},
  11643. {name: "GitHub Flavored Markdown", mime: "text/x-gfm", mode: "gfm", file: /^(readme|contributing|history).md$/i},
  11644. {name: "Go", mime: "text/x-go", mode: "go", ext: ["go"]},
  11645. {name: "Groovy", mime: "text/x-groovy", mode: "groovy", ext: ["groovy", "gradle"], file: /^Jenkinsfile$/},
  11646. {name: "HAML", mime: "text/x-haml", mode: "haml", ext: ["haml"]},
  11647. {name: "Haskell", mime: "text/x-haskell", mode: "haskell", ext: ["hs"]},
  11648. {name: "Haskell (Literate)", mime: "text/x-literate-haskell", mode: "haskell-literate", ext: ["lhs"]},
  11649. {name: "Haxe", mime: "text/x-haxe", mode: "haxe", ext: ["hx"]},
  11650. {name: "HXML", mime: "text/x-hxml", mode: "haxe", ext: ["hxml"]},
  11651. {name: "ASP.NET", mime: "application/x-aspx", mode: "htmlembedded", ext: ["aspx"], alias: ["asp", "aspx"]},
  11652. {name: "HTML", mime: "text/html", mode: "htmlmixed", ext: ["html", "htm"], alias: ["xhtml"]},
  11653. {name: "HTTP", mime: "message/http", mode: "http"},
  11654. {name: "IDL", mime: "text/x-idl", mode: "idl", ext: ["pro"]},
  11655. {name: "Pug", mime: "text/x-pug", mode: "pug", ext: ["jade", "pug"], alias: ["jade"]},
  11656. {name: "Java", mime: "text/x-java", mode: "clike", ext: ["java"]},
  11657. {name: "Java Server Pages", mime: "application/x-jsp", mode: "htmlembedded", ext: ["jsp"], alias: ["jsp"]},
  11658. {name: "JavaScript", mimes: ["text/javascript", "text/ecmascript", "application/javascript", "application/x-javascript", "application/ecmascript"],
  11659. mode: "javascript", ext: ["js"], alias: ["ecmascript", "js", "node"]},
  11660. {name: "JSON", mimes: ["application/json", "application/x-json"], mode: "javascript", ext: ["json", "map"], alias: ["json5"]},
  11661. {name: "JSON-LD", mime: "application/ld+json", mode: "javascript", ext: ["jsonld"], alias: ["jsonld"]},
  11662. {name: "JSX", mime: "text/jsx", mode: "jsx", ext: ["jsx"]},
  11663. {name: "Jinja2", mime: "null", mode: "jinja2"},
  11664. {name: "Julia", mime: "text/x-julia", mode: "julia", ext: ["jl"]},
  11665. {name: "Kotlin", mime: "text/x-kotlin", mode: "clike", ext: ["kt"]},
  11666. {name: "LESS", mime: "text/x-less", mode: "css", ext: ["less"]},
  11667. {name: "LiveScript", mime: "text/x-livescript", mode: "livescript", ext: ["ls"], alias: ["ls"]},
  11668. {name: "Lua", mime: "text/x-lua", mode: "lua", ext: ["lua"]},
  11669. {name: "Markdown", mime: "text/x-markdown", mode: "markdown", ext: ["markdown", "md", "mkd"]},
  11670. {name: "mIRC", mime: "text/mirc", mode: "mirc"},
  11671. {name: "MariaDB SQL", mime: "text/x-mariadb", mode: "sql"},
  11672. {name: "Mathematica", mime: "text/x-mathematica", mode: "mathematica", ext: ["m", "nb"]},
  11673. {name: "Modelica", mime: "text/x-modelica", mode: "modelica", ext: ["mo"]},
  11674. {name: "MUMPS", mime: "text/x-mumps", mode: "mumps", ext: ["mps"]},
  11675. {name: "MS SQL", mime: "text/x-mssql", mode: "sql"},
  11676. {name: "mbox", mime: "application/mbox", mode: "mbox", ext: ["mbox"]},
  11677. {name: "MySQL", mime: "text/x-mysql", mode: "sql"},
  11678. {name: "Nginx", mime: "text/x-nginx-conf", mode: "nginx", file: /nginx.*\.conf$/i},
  11679. {name: "NSIS", mime: "text/x-nsis", mode: "nsis", ext: ["nsh", "nsi"]},
  11680. {name: "NTriples", mimes: ["application/n-triples", "application/n-quads", "text/n-triples"],
  11681. mode: "ntriples", ext: ["nt", "nq"]},
  11682. {name: "Objective C", mime: "text/x-objectivec", mode: "clike", ext: ["m", "mm"], alias: ["objective-c", "objc"]},
  11683. {name: "OCaml", mime: "text/x-ocaml", mode: "mllike", ext: ["ml", "mli", "mll", "mly"]},
  11684. {name: "Octave", mime: "text/x-octave", mode: "octave", ext: ["m"]},
  11685. {name: "Oz", mime: "text/x-oz", mode: "oz", ext: ["oz"]},
  11686. {name: "Pascal", mime: "text/x-pascal", mode: "pascal", ext: ["p", "pas"]},
  11687. {name: "PEG.js", mime: "null", mode: "pegjs", ext: ["jsonld"]},
  11688. {name: "Perl", mime: "text/x-perl", mode: "perl", ext: ["pl", "pm"]},
  11689. {name: "PHP", mime: ["application/x-httpd-php", "text/x-php"], mode: "php", ext: ["php", "php3", "php4", "php5", "php7", "phtml"]},
  11690. {name: "Pig", mime: "text/x-pig", mode: "pig", ext: ["pig"]},
  11691. {name: "Plain Text", mime: "text/plain", mode: "null", ext: ["txt", "text", "conf", "def", "list", "log"]},
  11692. {name: "PLSQL", mime: "text/x-plsql", mode: "sql", ext: ["pls"]},
  11693. {name: "PowerShell", mime: "application/x-powershell", mode: "powershell", ext: ["ps1", "psd1", "psm1"]},
  11694. {name: "Properties files", mime: "text/x-properties", mode: "properties", ext: ["properties", "ini", "in"], alias: ["ini", "properties"]},
  11695. {name: "ProtoBuf", mime: "text/x-protobuf", mode: "protobuf", ext: ["proto"]},
  11696. {name: "Python", mime: "text/x-python", mode: "python", ext: ["BUILD", "bzl", "py", "pyw"], file: /^(BUCK|BUILD)$/},
  11697. {name: "Puppet", mime: "text/x-puppet", mode: "puppet", ext: ["pp"]},
  11698. {name: "Q", mime: "text/x-q", mode: "q", ext: ["q"]},
  11699. {name: "R", mime: "text/x-rsrc", mode: "r", ext: ["r", "R"], alias: ["rscript"]},
  11700. {name: "reStructuredText", mime: "text/x-rst", mode: "rst", ext: ["rst"], alias: ["rst"]},
  11701. {name: "RPM Changes", mime: "text/x-rpm-changes", mode: "rpm"},
  11702. {name: "RPM Spec", mime: "text/x-rpm-spec", mode: "rpm", ext: ["spec"]},
  11703. {name: "Ruby", mime: "text/x-ruby", mode: "ruby", ext: ["rb"], alias: ["jruby", "macruby", "rake", "rb", "rbx"]},
  11704. {name: "Rust", mime: "text/x-rustsrc", mode: "rust", ext: ["rs"]},
  11705. {name: "SAS", mime: "text/x-sas", mode: "sas", ext: ["sas"]},
  11706. {name: "Sass", mime: "text/x-sass", mode: "sass", ext: ["sass"]},
  11707. {name: "Scala", mime: "text/x-scala", mode: "clike", ext: ["scala"]},
  11708. {name: "Scheme", mime: "text/x-scheme", mode: "scheme", ext: ["scm", "ss"]},
  11709. {name: "SCSS", mime: "text/x-scss", mode: "css", ext: ["scss"]},
  11710. {name: "Shell", mimes: ["text/x-sh", "application/x-sh"], mode: "shell", ext: ["sh", "ksh", "bash"], alias: ["bash", "sh", "zsh"], file: /^PKGBUILD$/},
  11711. {name: "Sieve", mime: "application/sieve", mode: "sieve", ext: ["siv", "sieve"]},
  11712. {name: "Slim", mimes: ["text/x-slim", "application/x-slim"], mode: "slim", ext: ["slim"]},
  11713. {name: "Smalltalk", mime: "text/x-stsrc", mode: "smalltalk", ext: ["st"]},
  11714. {name: "Smarty", mime: "text/x-smarty", mode: "smarty", ext: ["tpl"]},
  11715. {name: "Solr", mime: "text/x-solr", mode: "solr"},
  11716. {name: "Soy", mime: "text/x-soy", mode: "soy", ext: ["soy"], alias: ["closure template"]},
  11717. {name: "SPARQL", mime: "application/sparql-query", mode: "sparql", ext: ["rq", "sparql"], alias: ["sparul"]},
  11718. {name: "Spreadsheet", mime: "text/x-spreadsheet", mode: "spreadsheet", alias: ["excel", "formula"]},
  11719. {name: "SQL", mime: "text/x-sql", mode: "sql", ext: ["sql"]},
  11720. {name: "SQLite", mime: "text/x-sqlite", mode: "sql"},
  11721. {name: "Squirrel", mime: "text/x-squirrel", mode: "clike", ext: ["nut"]},
  11722. {name: "Stylus", mime: "text/x-styl", mode: "stylus", ext: ["styl"]},
  11723. {name: "Swift", mime: "text/x-swift", mode: "swift", ext: ["swift"]},
  11724. {name: "sTeX", mime: "text/x-stex", mode: "stex"},
  11725. {name: "LaTeX", mime: "text/x-latex", mode: "stex", ext: ["text", "ltx"], alias: ["tex"]},
  11726. {name: "SystemVerilog", mime: "text/x-systemverilog", mode: "verilog", ext: ["v", "sv", "svh"]},
  11727. {name: "Tcl", mime: "text/x-tcl", mode: "tcl", ext: ["tcl"]},
  11728. {name: "Textile", mime: "text/x-textile", mode: "textile", ext: ["textile"]},
  11729. {name: "TiddlyWiki ", mime: "text/x-tiddlywiki", mode: "tiddlywiki"},
  11730. {name: "Tiki wiki", mime: "text/tiki", mode: "tiki"},
  11731. {name: "TOML", mime: "text/x-toml", mode: "toml", ext: ["toml"]},
  11732. {name: "Tornado", mime: "text/x-tornado", mode: "tornado"},
  11733. {name: "troff", mime: "text/troff", mode: "troff", ext: ["1", "2", "3", "4", "5", "6", "7", "8", "9"]},
  11734. {name: "TTCN", mime: "text/x-ttcn", mode: "ttcn", ext: ["ttcn", "ttcn3", "ttcnpp"]},
  11735. {name: "TTCN_CFG", mime: "text/x-ttcn-cfg", mode: "ttcn-cfg", ext: ["cfg"]},
  11736. {name: "Turtle", mime: "text/turtle", mode: "turtle", ext: ["ttl"]},
  11737. {name: "TypeScript", mime: "application/typescript", mode: "javascript", ext: ["ts"], alias: ["ts"]},
  11738. {name: "TypeScript-JSX", mime: "text/typescript-jsx", mode: "jsx", ext: ["tsx"], alias: ["tsx"]},
  11739. {name: "Twig", mime: "text/x-twig", mode: "twig"},
  11740. {name: "Web IDL", mime: "text/x-webidl", mode: "webidl", ext: ["webidl"]},
  11741. {name: "VB.NET", mime: "text/x-vb", mode: "vb", ext: ["vb"]},
  11742. {name: "VBScript", mime: "text/vbscript", mode: "vbscript", ext: ["vbs"]},
  11743. {name: "Velocity", mime: "text/velocity", mode: "velocity", ext: ["vtl"]},
  11744. {name: "Verilog", mime: "text/x-verilog", mode: "verilog", ext: ["v"]},
  11745. {name: "VHDL", mime: "text/x-vhdl", mode: "vhdl", ext: ["vhd", "vhdl"]},
  11746. {name: "Vue.js Component", mimes: ["script/x-vue", "text/x-vue"], mode: "vue", ext: ["vue"]},
  11747. {name: "XML", mimes: ["application/xml", "text/xml"], mode: "xml", ext: ["xml", "xsl", "xsd", "svg"], alias: ["rss", "wsdl", "xsd"]},
  11748. {name: "XQuery", mime: "application/xquery", mode: "xquery", ext: ["xy", "xquery"]},
  11749. {name: "Yacas", mime: "text/x-yacas", mode: "yacas", ext: ["ys"]},
  11750. {name: "YAML", mimes: ["text/x-yaml", "text/yaml"], mode: "yaml", ext: ["yaml", "yml"], alias: ["yml"]},
  11751. {name: "Z80", mime: "text/x-z80", mode: "z80", ext: ["z80"]},
  11752. {name: "mscgen", mime: "text/x-mscgen", mode: "mscgen", ext: ["mscgen", "mscin", "msc"]},
  11753. {name: "xu", mime: "text/x-xu", mode: "mscgen", ext: ["xu"]},
  11754. {name: "msgenny", mime: "text/x-msgenny", mode: "mscgen", ext: ["msgenny"]}
  11755. ];
  11756. // Ensure all modes have a mime property for backwards compatibility
  11757. for (var i = 0; i < CodeMirror.modeInfo.length; i++) {
  11758. var info = CodeMirror.modeInfo[i];
  11759. if (info.mimes) info.mime = info.mimes[0];
  11760. }
  11761. CodeMirror.findModeByMIME = function(mime) {
  11762. mime = mime.toLowerCase();
  11763. for (var i = 0; i < CodeMirror.modeInfo.length; i++) {
  11764. var info = CodeMirror.modeInfo[i];
  11765. if (info.mime == mime) return info;
  11766. if (info.mimes) for (var j = 0; j < info.mimes.length; j++)
  11767. if (info.mimes[j] == mime) return info;
  11768. }
  11769. if (/\+xml$/.test(mime)) return CodeMirror.findModeByMIME("application/xml")
  11770. if (/\+json$/.test(mime)) return CodeMirror.findModeByMIME("application/json")
  11771. };
  11772. CodeMirror.findModeByExtension = function(ext) {
  11773. for (var i = 0; i < CodeMirror.modeInfo.length; i++) {
  11774. var info = CodeMirror.modeInfo[i];
  11775. if (info.ext) for (var j = 0; j < info.ext.length; j++)
  11776. if (info.ext[j] == ext) return info;
  11777. }
  11778. };
  11779. CodeMirror.findModeByFileName = function(filename) {
  11780. for (var i = 0; i < CodeMirror.modeInfo.length; i++) {
  11781. var info = CodeMirror.modeInfo[i];
  11782. if (info.file && info.file.test(filename)) return info;
  11783. }
  11784. var dot = filename.lastIndexOf(".");
  11785. var ext = dot > -1 && filename.substring(dot + 1, filename.length);
  11786. if (ext) return CodeMirror.findModeByExtension(ext);
  11787. };
  11788. CodeMirror.findModeByName = function(name) {
  11789. name = name.toLowerCase();
  11790. for (var i = 0; i < CodeMirror.modeInfo.length; i++) {
  11791. var info = CodeMirror.modeInfo[i];
  11792. if (info.name.toLowerCase() == name) return info;
  11793. if (info.alias) for (var j = 0; j < info.alias.length; j++)
  11794. if (info.alias[j].toLowerCase() == name) return info;
  11795. }
  11796. };
  11797. });
  11798. },{"../lib/codemirror":10}],14:[function(require,module,exports){
  11799. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  11800. // Distributed under an MIT license: http://codemirror.net/LICENSE
  11801. (function(mod) {
  11802. if (typeof exports == "object" && typeof module == "object") // CommonJS
  11803. mod(require("../../lib/codemirror"));
  11804. else if (typeof define == "function" && define.amd) // AMD
  11805. define(["../../lib/codemirror"], mod);
  11806. else // Plain browser env
  11807. mod(CodeMirror);
  11808. })(function(CodeMirror) {
  11809. "use strict";
  11810. var htmlConfig = {
  11811. autoSelfClosers: {'area': true, 'base': true, 'br': true, 'col': true, 'command': true,
  11812. 'embed': true, 'frame': true, 'hr': true, 'img': true, 'input': true,
  11813. 'keygen': true, 'link': true, 'meta': true, 'param': true, 'source': true,
  11814. 'track': true, 'wbr': true, 'menuitem': true},
  11815. implicitlyClosed: {'dd': true, 'li': true, 'optgroup': true, 'option': true, 'p': true,
  11816. 'rp': true, 'rt': true, 'tbody': true, 'td': true, 'tfoot': true,
  11817. 'th': true, 'tr': true},
  11818. contextGrabbers: {
  11819. 'dd': {'dd': true, 'dt': true},
  11820. 'dt': {'dd': true, 'dt': true},
  11821. 'li': {'li': true},
  11822. 'option': {'option': true, 'optgroup': true},
  11823. 'optgroup': {'optgroup': true},
  11824. 'p': {'address': true, 'article': true, 'aside': true, 'blockquote': true, 'dir': true,
  11825. 'div': true, 'dl': true, 'fieldset': true, 'footer': true, 'form': true,
  11826. 'h1': true, 'h2': true, 'h3': true, 'h4': true, 'h5': true, 'h6': true,
  11827. 'header': true, 'hgroup': true, 'hr': true, 'menu': true, 'nav': true, 'ol': true,
  11828. 'p': true, 'pre': true, 'section': true, 'table': true, 'ul': true},
  11829. 'rp': {'rp': true, 'rt': true},
  11830. 'rt': {'rp': true, 'rt': true},
  11831. 'tbody': {'tbody': true, 'tfoot': true},
  11832. 'td': {'td': true, 'th': true},
  11833. 'tfoot': {'tbody': true},
  11834. 'th': {'td': true, 'th': true},
  11835. 'thead': {'tbody': true, 'tfoot': true},
  11836. 'tr': {'tr': true}
  11837. },
  11838. doNotIndent: {"pre": true},
  11839. allowUnquoted: true,
  11840. allowMissing: true,
  11841. caseFold: true
  11842. }
  11843. var xmlConfig = {
  11844. autoSelfClosers: {},
  11845. implicitlyClosed: {},
  11846. contextGrabbers: {},
  11847. doNotIndent: {},
  11848. allowUnquoted: false,
  11849. allowMissing: false,
  11850. caseFold: false
  11851. }
  11852. CodeMirror.defineMode("xml", function(editorConf, config_) {
  11853. var indentUnit = editorConf.indentUnit
  11854. var config = {}
  11855. var defaults = config_.htmlMode ? htmlConfig : xmlConfig
  11856. for (var prop in defaults) config[prop] = defaults[prop]
  11857. for (var prop in config_) config[prop] = config_[prop]
  11858. // Return variables for tokenizers
  11859. var type, setStyle;
  11860. function inText(stream, state) {
  11861. function chain(parser) {
  11862. state.tokenize = parser;
  11863. return parser(stream, state);
  11864. }
  11865. var ch = stream.next();
  11866. if (ch == "<") {
  11867. if (stream.eat("!")) {
  11868. if (stream.eat("[")) {
  11869. if (stream.match("CDATA[")) return chain(inBlock("atom", "]]>"));
  11870. else return null;
  11871. } else if (stream.match("--")) {
  11872. return chain(inBlock("comment", "-->"));
  11873. } else if (stream.match("DOCTYPE", true, true)) {
  11874. stream.eatWhile(/[\w\._\-]/);
  11875. return chain(doctype(1));
  11876. } else {
  11877. return null;
  11878. }
  11879. } else if (stream.eat("?")) {
  11880. stream.eatWhile(/[\w\._\-]/);
  11881. state.tokenize = inBlock("meta", "?>");
  11882. return "meta";
  11883. } else {
  11884. type = stream.eat("/") ? "closeTag" : "openTag";
  11885. state.tokenize = inTag;
  11886. return "tag bracket";
  11887. }
  11888. } else if (ch == "&") {
  11889. var ok;
  11890. if (stream.eat("#")) {
  11891. if (stream.eat("x")) {
  11892. ok = stream.eatWhile(/[a-fA-F\d]/) && stream.eat(";");
  11893. } else {
  11894. ok = stream.eatWhile(/[\d]/) && stream.eat(";");
  11895. }
  11896. } else {
  11897. ok = stream.eatWhile(/[\w\.\-:]/) && stream.eat(";");
  11898. }
  11899. return ok ? "atom" : "error";
  11900. } else {
  11901. stream.eatWhile(/[^&<]/);
  11902. return null;
  11903. }
  11904. }
  11905. inText.isInText = true;
  11906. function inTag(stream, state) {
  11907. var ch = stream.next();
  11908. if (ch == ">" || (ch == "/" && stream.eat(">"))) {
  11909. state.tokenize = inText;
  11910. type = ch == ">" ? "endTag" : "selfcloseTag";
  11911. return "tag bracket";
  11912. } else if (ch == "=") {
  11913. type = "equals";
  11914. return null;
  11915. } else if (ch == "<") {
  11916. state.tokenize = inText;
  11917. state.state = baseState;
  11918. state.tagName = state.tagStart = null;
  11919. var next = state.tokenize(stream, state);
  11920. return next ? next + " tag error" : "tag error";
  11921. } else if (/[\'\"]/.test(ch)) {
  11922. state.tokenize = inAttribute(ch);
  11923. state.stringStartCol = stream.column();
  11924. return state.tokenize(stream, state);
  11925. } else {
  11926. stream.match(/^[^\s\u00a0=<>\"\']*[^\s\u00a0=<>\"\'\/]/);
  11927. return "word";
  11928. }
  11929. }
  11930. function inAttribute(quote) {
  11931. var closure = function(stream, state) {
  11932. while (!stream.eol()) {
  11933. if (stream.next() == quote) {
  11934. state.tokenize = inTag;
  11935. break;
  11936. }
  11937. }
  11938. return "string";
  11939. };
  11940. closure.isInAttribute = true;
  11941. return closure;
  11942. }
  11943. function inBlock(style, terminator) {
  11944. return function(stream, state) {
  11945. while (!stream.eol()) {
  11946. if (stream.match(terminator)) {
  11947. state.tokenize = inText;
  11948. break;
  11949. }
  11950. stream.next();
  11951. }
  11952. return style;
  11953. };
  11954. }
  11955. function doctype(depth) {
  11956. return function(stream, state) {
  11957. var ch;
  11958. while ((ch = stream.next()) != null) {
  11959. if (ch == "<") {
  11960. state.tokenize = doctype(depth + 1);
  11961. return state.tokenize(stream, state);
  11962. } else if (ch == ">") {
  11963. if (depth == 1) {
  11964. state.tokenize = inText;
  11965. break;
  11966. } else {
  11967. state.tokenize = doctype(depth - 1);
  11968. return state.tokenize(stream, state);
  11969. }
  11970. }
  11971. }
  11972. return "meta";
  11973. };
  11974. }
  11975. function Context(state, tagName, startOfLine) {
  11976. this.prev = state.context;
  11977. this.tagName = tagName;
  11978. this.indent = state.indented;
  11979. this.startOfLine = startOfLine;
  11980. if (config.doNotIndent.hasOwnProperty(tagName) || (state.context && state.context.noIndent))
  11981. this.noIndent = true;
  11982. }
  11983. function popContext(state) {
  11984. if (state.context) state.context = state.context.prev;
  11985. }
  11986. function maybePopContext(state, nextTagName) {
  11987. var parentTagName;
  11988. while (true) {
  11989. if (!state.context) {
  11990. return;
  11991. }
  11992. parentTagName = state.context.tagName;
  11993. if (!config.contextGrabbers.hasOwnProperty(parentTagName) ||
  11994. !config.contextGrabbers[parentTagName].hasOwnProperty(nextTagName)) {
  11995. return;
  11996. }
  11997. popContext(state);
  11998. }
  11999. }
  12000. function baseState(type, stream, state) {
  12001. if (type == "openTag") {
  12002. state.tagStart = stream.column();
  12003. return tagNameState;
  12004. } else if (type == "closeTag") {
  12005. return closeTagNameState;
  12006. } else {
  12007. return baseState;
  12008. }
  12009. }
  12010. function tagNameState(type, stream, state) {
  12011. if (type == "word") {
  12012. state.tagName = stream.current();
  12013. setStyle = "tag";
  12014. return attrState;
  12015. } else {
  12016. setStyle = "error";
  12017. return tagNameState;
  12018. }
  12019. }
  12020. function closeTagNameState(type, stream, state) {
  12021. if (type == "word") {
  12022. var tagName = stream.current();
  12023. if (state.context && state.context.tagName != tagName &&
  12024. config.implicitlyClosed.hasOwnProperty(state.context.tagName))
  12025. popContext(state);
  12026. if ((state.context && state.context.tagName == tagName) || config.matchClosing === false) {
  12027. setStyle = "tag";
  12028. return closeState;
  12029. } else {
  12030. setStyle = "tag error";
  12031. return closeStateErr;
  12032. }
  12033. } else {
  12034. setStyle = "error";
  12035. return closeStateErr;
  12036. }
  12037. }
  12038. function closeState(type, _stream, state) {
  12039. if (type != "endTag") {
  12040. setStyle = "error";
  12041. return closeState;
  12042. }
  12043. popContext(state);
  12044. return baseState;
  12045. }
  12046. function closeStateErr(type, stream, state) {
  12047. setStyle = "error";
  12048. return closeState(type, stream, state);
  12049. }
  12050. function attrState(type, _stream, state) {
  12051. if (type == "word") {
  12052. setStyle = "attribute";
  12053. return attrEqState;
  12054. } else if (type == "endTag" || type == "selfcloseTag") {
  12055. var tagName = state.tagName, tagStart = state.tagStart;
  12056. state.tagName = state.tagStart = null;
  12057. if (type == "selfcloseTag" ||
  12058. config.autoSelfClosers.hasOwnProperty(tagName)) {
  12059. maybePopContext(state, tagName);
  12060. } else {
  12061. maybePopContext(state, tagName);
  12062. state.context = new Context(state, tagName, tagStart == state.indented);
  12063. }
  12064. return baseState;
  12065. }
  12066. setStyle = "error";
  12067. return attrState;
  12068. }
  12069. function attrEqState(type, stream, state) {
  12070. if (type == "equals") return attrValueState;
  12071. if (!config.allowMissing) setStyle = "error";
  12072. return attrState(type, stream, state);
  12073. }
  12074. function attrValueState(type, stream, state) {
  12075. if (type == "string") return attrContinuedState;
  12076. if (type == "word" && config.allowUnquoted) {setStyle = "string"; return attrState;}
  12077. setStyle = "error";
  12078. return attrState(type, stream, state);
  12079. }
  12080. function attrContinuedState(type, stream, state) {
  12081. if (type == "string") return attrContinuedState;
  12082. return attrState(type, stream, state);
  12083. }
  12084. return {
  12085. startState: function(baseIndent) {
  12086. var state = {tokenize: inText,
  12087. state: baseState,
  12088. indented: baseIndent || 0,
  12089. tagName: null, tagStart: null,
  12090. context: null}
  12091. if (baseIndent != null) state.baseIndent = baseIndent
  12092. return state
  12093. },
  12094. token: function(stream, state) {
  12095. if (!state.tagName && stream.sol())
  12096. state.indented = stream.indentation();
  12097. if (stream.eatSpace()) return null;
  12098. type = null;
  12099. var style = state.tokenize(stream, state);
  12100. if ((style || type) && style != "comment") {
  12101. setStyle = null;
  12102. state.state = state.state(type || style, stream, state);
  12103. if (setStyle)
  12104. style = setStyle == "error" ? style + " error" : setStyle;
  12105. }
  12106. return style;
  12107. },
  12108. indent: function(state, textAfter, fullLine) {
  12109. var context = state.context;
  12110. // Indent multi-line strings (e.g. css).
  12111. if (state.tokenize.isInAttribute) {
  12112. if (state.tagStart == state.indented)
  12113. return state.stringStartCol + 1;
  12114. else
  12115. return state.indented + indentUnit;
  12116. }
  12117. if (context && context.noIndent) return CodeMirror.Pass;
  12118. if (state.tokenize != inTag && state.tokenize != inText)
  12119. return fullLine ? fullLine.match(/^(\s*)/)[0].length : 0;
  12120. // Indent the starts of attribute names.
  12121. if (state.tagName) {
  12122. if (config.multilineTagIndentPastTag !== false)
  12123. return state.tagStart + state.tagName.length + 2;
  12124. else
  12125. return state.tagStart + indentUnit * (config.multilineTagIndentFactor || 1);
  12126. }
  12127. if (config.alignCDATA && /<!\[CDATA\[/.test(textAfter)) return 0;
  12128. var tagAfter = textAfter && /^<(\/)?([\w_:\.-]*)/.exec(textAfter);
  12129. if (tagAfter && tagAfter[1]) { // Closing tag spotted
  12130. while (context) {
  12131. if (context.tagName == tagAfter[2]) {
  12132. context = context.prev;
  12133. break;
  12134. } else if (config.implicitlyClosed.hasOwnProperty(context.tagName)) {
  12135. context = context.prev;
  12136. } else {
  12137. break;
  12138. }
  12139. }
  12140. } else if (tagAfter) { // Opening tag spotted
  12141. while (context) {
  12142. var grabbers = config.contextGrabbers[context.tagName];
  12143. if (grabbers && grabbers.hasOwnProperty(tagAfter[2]))
  12144. context = context.prev;
  12145. else
  12146. break;
  12147. }
  12148. }
  12149. while (context && context.prev && !context.startOfLine)
  12150. context = context.prev;
  12151. if (context) return context.indent + indentUnit;
  12152. else return state.baseIndent || 0;
  12153. },
  12154. electricInput: /<\/[\s\w:]+>$/,
  12155. blockCommentStart: "<!--",
  12156. blockCommentEnd: "-->",
  12157. configuration: config.htmlMode ? "html" : "xml",
  12158. helperType: config.htmlMode ? "html" : "xml",
  12159. skipAttribute: function(state) {
  12160. if (state.state == attrValueState)
  12161. state.state = attrState
  12162. }
  12163. };
  12164. });
  12165. CodeMirror.defineMIME("text/xml", "xml");
  12166. CodeMirror.defineMIME("application/xml", "xml");
  12167. if (!CodeMirror.mimeModes.hasOwnProperty("text/html"))
  12168. CodeMirror.defineMIME("text/html", {name: "xml", htmlMode: true});
  12169. });
  12170. },{"../../lib/codemirror":10}],15:[function(require,module,exports){
  12171. exports.read = function (buffer, offset, isLE, mLen, nBytes) {
  12172. var e, m
  12173. var eLen = nBytes * 8 - mLen - 1
  12174. var eMax = (1 << eLen) - 1
  12175. var eBias = eMax >> 1
  12176. var nBits = -7
  12177. var i = isLE ? (nBytes - 1) : 0
  12178. var d = isLE ? -1 : 1
  12179. var s = buffer[offset + i]
  12180. i += d
  12181. e = s & ((1 << (-nBits)) - 1)
  12182. s >>= (-nBits)
  12183. nBits += eLen
  12184. for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
  12185. m = e & ((1 << (-nBits)) - 1)
  12186. e >>= (-nBits)
  12187. nBits += mLen
  12188. for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
  12189. if (e === 0) {
  12190. e = 1 - eBias
  12191. } else if (e === eMax) {
  12192. return m ? NaN : ((s ? -1 : 1) * Infinity)
  12193. } else {
  12194. m = m + Math.pow(2, mLen)
  12195. e = e - eBias
  12196. }
  12197. return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
  12198. }
  12199. exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
  12200. var e, m, c
  12201. var eLen = nBytes * 8 - mLen - 1
  12202. var eMax = (1 << eLen) - 1
  12203. var eBias = eMax >> 1
  12204. var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
  12205. var i = isLE ? 0 : (nBytes - 1)
  12206. var d = isLE ? 1 : -1
  12207. var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
  12208. value = Math.abs(value)
  12209. if (isNaN(value) || value === Infinity) {
  12210. m = isNaN(value) ? 1 : 0
  12211. e = eMax
  12212. } else {
  12213. e = Math.floor(Math.log(value) / Math.LN2)
  12214. if (value * (c = Math.pow(2, -e)) < 1) {
  12215. e--
  12216. c *= 2
  12217. }
  12218. if (e + eBias >= 1) {
  12219. value += rt / c
  12220. } else {
  12221. value += rt * Math.pow(2, 1 - eBias)
  12222. }
  12223. if (value * c >= 2) {
  12224. e++
  12225. c /= 2
  12226. }
  12227. if (e + eBias >= eMax) {
  12228. m = 0
  12229. e = eMax
  12230. } else if (e + eBias >= 1) {
  12231. m = (value * c - 1) * Math.pow(2, mLen)
  12232. e = e + eBias
  12233. } else {
  12234. m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
  12235. e = 0
  12236. }
  12237. }
  12238. for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
  12239. e = (e << mLen) | m
  12240. eLen += mLen
  12241. for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
  12242. buffer[offset + i - d] |= s * 128
  12243. }
  12244. },{}],16:[function(require,module,exports){
  12245. (function (global){
  12246. /**
  12247. * marked - a markdown parser
  12248. * Copyright (c) 2011-2014, Christopher Jeffrey. (MIT Licensed)
  12249. * https://github.com/chjj/marked
  12250. */
  12251. ;(function() {
  12252. /**
  12253. * Block-Level Grammar
  12254. */
  12255. var block = {
  12256. newline: /^\n+/,
  12257. code: /^( {4}[^\n]+\n*)+/,
  12258. fences: noop,
  12259. hr: /^( *[-*_]){3,} *(?:\n+|$)/,
  12260. heading: /^ *(#{1,6}) *([^\n]+?) *#* *(?:\n+|$)/,
  12261. nptable: noop,
  12262. lheading: /^([^\n]+)\n *(=|-){2,} *(?:\n+|$)/,
  12263. blockquote: /^( *>[^\n]+(\n(?!def)[^\n]+)*\n*)+/,
  12264. list: /^( *)(bull) [\s\S]+?(?:hr|def|\n{2,}(?! )(?!\1bull )\n*|\s*$)/,
  12265. html: /^ *(?:comment *(?:\n|\s*$)|closed *(?:\n{2,}|\s*$)|closing *(?:\n{2,}|\s*$))/,
  12266. def: /^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +["(]([^\n]+)[")])? *(?:\n+|$)/,
  12267. table: noop,
  12268. paragraph: /^((?:[^\n]+\n?(?!hr|heading|lheading|blockquote|tag|def))+)\n*/,
  12269. text: /^[^\n]+/
  12270. };
  12271. block.bullet = /(?:[*+-]|\d+\.)/;
  12272. block.item = /^( *)(bull) [^\n]*(?:\n(?!\1bull )[^\n]*)*/;
  12273. block.item = replace(block.item, 'gm')
  12274. (/bull/g, block.bullet)
  12275. ();
  12276. block.list = replace(block.list)
  12277. (/bull/g, block.bullet)
  12278. ('hr', '\\n+(?=\\1?(?:[-*_] *){3,}(?:\\n+|$))')
  12279. ('def', '\\n+(?=' + block.def.source + ')')
  12280. ();
  12281. block.blockquote = replace(block.blockquote)
  12282. ('def', block.def)
  12283. ();
  12284. block._tag = '(?!(?:'
  12285. + 'a|em|strong|small|s|cite|q|dfn|abbr|data|time|code'
  12286. + '|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo'
  12287. + '|span|br|wbr|ins|del|img)\\b)\\w+(?!:/|[^\\w\\s@]*@)\\b';
  12288. block.html = replace(block.html)
  12289. ('comment', /<!--[\s\S]*?-->/)
  12290. ('closed', /<(tag)[\s\S]+?<\/\1>/)
  12291. ('closing', /<tag(?:"[^"]*"|'[^']*'|[^'">])*?>/)
  12292. (/tag/g, block._tag)
  12293. ();
  12294. block.paragraph = replace(block.paragraph)
  12295. ('hr', block.hr)
  12296. ('heading', block.heading)
  12297. ('lheading', block.lheading)
  12298. ('blockquote', block.blockquote)
  12299. ('tag', '<' + block._tag)
  12300. ('def', block.def)
  12301. ();
  12302. /**
  12303. * Normal Block Grammar
  12304. */
  12305. block.normal = merge({}, block);
  12306. /**
  12307. * GFM Block Grammar
  12308. */
  12309. block.gfm = merge({}, block.normal, {
  12310. fences: /^ *(`{3,}|~{3,})[ \.]*(\S+)? *\n([\s\S]*?)\s*\1 *(?:\n+|$)/,
  12311. paragraph: /^/,
  12312. heading: /^ *(#{1,6}) +([^\n]+?) *#* *(?:\n+|$)/
  12313. });
  12314. block.gfm.paragraph = replace(block.paragraph)
  12315. ('(?!', '(?!'
  12316. + block.gfm.fences.source.replace('\\1', '\\2') + '|'
  12317. + block.list.source.replace('\\1', '\\3') + '|')
  12318. ();
  12319. /**
  12320. * GFM + Tables Block Grammar
  12321. */
  12322. block.tables = merge({}, block.gfm, {
  12323. nptable: /^ *(\S.*\|.*)\n *([-:]+ *\|[-| :]*)\n((?:.*\|.*(?:\n|$))*)\n*/,
  12324. table: /^ *\|(.+)\n *\|( *[-:]+[-| :]*)\n((?: *\|.*(?:\n|$))*)\n*/
  12325. });
  12326. /**
  12327. * Block Lexer
  12328. */
  12329. function Lexer(options) {
  12330. this.tokens = [];
  12331. this.tokens.links = {};
  12332. this.options = options || marked.defaults;
  12333. this.rules = block.normal;
  12334. if (this.options.gfm) {
  12335. if (this.options.tables) {
  12336. this.rules = block.tables;
  12337. } else {
  12338. this.rules = block.gfm;
  12339. }
  12340. }
  12341. }
  12342. /**
  12343. * Expose Block Rules
  12344. */
  12345. Lexer.rules = block;
  12346. /**
  12347. * Static Lex Method
  12348. */
  12349. Lexer.lex = function(src, options) {
  12350. var lexer = new Lexer(options);
  12351. return lexer.lex(src);
  12352. };
  12353. /**
  12354. * Preprocessing
  12355. */
  12356. Lexer.prototype.lex = function(src) {
  12357. src = src
  12358. .replace(/\r\n|\r/g, '\n')
  12359. .replace(/\t/g, ' ')
  12360. .replace(/\u00a0/g, ' ')
  12361. .replace(/\u2424/g, '\n');
  12362. return this.token(src, true);
  12363. };
  12364. /**
  12365. * Lexing
  12366. */
  12367. Lexer.prototype.token = function(src, top, bq) {
  12368. var src = src.replace(/^ +$/gm, '')
  12369. , next
  12370. , loose
  12371. , cap
  12372. , bull
  12373. , b
  12374. , item
  12375. , space
  12376. , i
  12377. , l;
  12378. while (src) {
  12379. // newline
  12380. if (cap = this.rules.newline.exec(src)) {
  12381. src = src.substring(cap[0].length);
  12382. if (cap[0].length > 1) {
  12383. this.tokens.push({
  12384. type: 'space'
  12385. });
  12386. }
  12387. }
  12388. // code
  12389. if (cap = this.rules.code.exec(src)) {
  12390. src = src.substring(cap[0].length);
  12391. cap = cap[0].replace(/^ {4}/gm, '');
  12392. this.tokens.push({
  12393. type: 'code',
  12394. text: !this.options.pedantic
  12395. ? cap.replace(/\n+$/, '')
  12396. : cap
  12397. });
  12398. continue;
  12399. }
  12400. // fences (gfm)
  12401. if (cap = this.rules.fences.exec(src)) {
  12402. src = src.substring(cap[0].length);
  12403. this.tokens.push({
  12404. type: 'code',
  12405. lang: cap[2],
  12406. text: cap[3] || ''
  12407. });
  12408. continue;
  12409. }
  12410. // heading
  12411. if (cap = this.rules.heading.exec(src)) {
  12412. src = src.substring(cap[0].length);
  12413. this.tokens.push({
  12414. type: 'heading',
  12415. depth: cap[1].length,
  12416. text: cap[2]
  12417. });
  12418. continue;
  12419. }
  12420. // table no leading pipe (gfm)
  12421. if (top && (cap = this.rules.nptable.exec(src))) {
  12422. src = src.substring(cap[0].length);
  12423. item = {
  12424. type: 'table',
  12425. header: cap[1].replace(/^ *| *\| *$/g, '').split(/ *\| */),
  12426. align: cap[2].replace(/^ *|\| *$/g, '').split(/ *\| */),
  12427. cells: cap[3].replace(/\n$/, '').split('\n')
  12428. };
  12429. for (i = 0; i < item.align.length; i++) {
  12430. if (/^ *-+: *$/.test(item.align[i])) {
  12431. item.align[i] = 'right';
  12432. } else if (/^ *:-+: *$/.test(item.align[i])) {
  12433. item.align[i] = 'center';
  12434. } else if (/^ *:-+ *$/.test(item.align[i])) {
  12435. item.align[i] = 'left';
  12436. } else {
  12437. item.align[i] = null;
  12438. }
  12439. }
  12440. for (i = 0; i < item.cells.length; i++) {
  12441. item.cells[i] = item.cells[i].split(/ *\| */);
  12442. }
  12443. this.tokens.push(item);
  12444. continue;
  12445. }
  12446. // lheading
  12447. if (cap = this.rules.lheading.exec(src)) {
  12448. src = src.substring(cap[0].length);
  12449. this.tokens.push({
  12450. type: 'heading',
  12451. depth: cap[2] === '=' ? 1 : 2,
  12452. text: cap[1]
  12453. });
  12454. continue;
  12455. }
  12456. // hr
  12457. if (cap = this.rules.hr.exec(src)) {
  12458. src = src.substring(cap[0].length);
  12459. this.tokens.push({
  12460. type: 'hr'
  12461. });
  12462. continue;
  12463. }
  12464. // blockquote
  12465. if (cap = this.rules.blockquote.exec(src)) {
  12466. src = src.substring(cap[0].length);
  12467. this.tokens.push({
  12468. type: 'blockquote_start'
  12469. });
  12470. cap = cap[0].replace(/^ *> ?/gm, '');
  12471. // Pass `top` to keep the current
  12472. // "toplevel" state. This is exactly
  12473. // how markdown.pl works.
  12474. this.token(cap, top, true);
  12475. this.tokens.push({
  12476. type: 'blockquote_end'
  12477. });
  12478. continue;
  12479. }
  12480. // list
  12481. if (cap = this.rules.list.exec(src)) {
  12482. src = src.substring(cap[0].length);
  12483. bull = cap[2];
  12484. this.tokens.push({
  12485. type: 'list_start',
  12486. ordered: bull.length > 1
  12487. });
  12488. // Get each top-level item.
  12489. cap = cap[0].match(this.rules.item);
  12490. next = false;
  12491. l = cap.length;
  12492. i = 0;
  12493. for (; i < l; i++) {
  12494. item = cap[i];
  12495. // Remove the list item's bullet
  12496. // so it is seen as the next token.
  12497. space = item.length;
  12498. item = item.replace(/^ *([*+-]|\d+\.) +/, '');
  12499. // Outdent whatever the
  12500. // list item contains. Hacky.
  12501. if (~item.indexOf('\n ')) {
  12502. space -= item.length;
  12503. item = !this.options.pedantic
  12504. ? item.replace(new RegExp('^ {1,' + space + '}', 'gm'), '')
  12505. : item.replace(/^ {1,4}/gm, '');
  12506. }
  12507. // Determine whether the next list item belongs here.
  12508. // Backpedal if it does not belong in this list.
  12509. if (this.options.smartLists && i !== l - 1) {
  12510. b = block.bullet.exec(cap[i + 1])[0];
  12511. if (bull !== b && !(bull.length > 1 && b.length > 1)) {
  12512. src = cap.slice(i + 1).join('\n') + src;
  12513. i = l - 1;
  12514. }
  12515. }
  12516. // Determine whether item is loose or not.
  12517. // Use: /(^|\n)(?! )[^\n]+\n\n(?!\s*$)/
  12518. // for discount behavior.
  12519. loose = next || /\n\n(?!\s*$)/.test(item);
  12520. if (i !== l - 1) {
  12521. next = item.charAt(item.length - 1) === '\n';
  12522. if (!loose) loose = next;
  12523. }
  12524. this.tokens.push({
  12525. type: loose
  12526. ? 'loose_item_start'
  12527. : 'list_item_start'
  12528. });
  12529. // Recurse.
  12530. this.token(item, false, bq);
  12531. this.tokens.push({
  12532. type: 'list_item_end'
  12533. });
  12534. }
  12535. this.tokens.push({
  12536. type: 'list_end'
  12537. });
  12538. continue;
  12539. }
  12540. // html
  12541. if (cap = this.rules.html.exec(src)) {
  12542. src = src.substring(cap[0].length);
  12543. this.tokens.push({
  12544. type: this.options.sanitize
  12545. ? 'paragraph'
  12546. : 'html',
  12547. pre: !this.options.sanitizer
  12548. && (cap[1] === 'pre' || cap[1] === 'script' || cap[1] === 'style'),
  12549. text: cap[0]
  12550. });
  12551. continue;
  12552. }
  12553. // def
  12554. if ((!bq && top) && (cap = this.rules.def.exec(src))) {
  12555. src = src.substring(cap[0].length);
  12556. this.tokens.links[cap[1].toLowerCase()] = {
  12557. href: cap[2],
  12558. title: cap[3]
  12559. };
  12560. continue;
  12561. }
  12562. // table (gfm)
  12563. if (top && (cap = this.rules.table.exec(src))) {
  12564. src = src.substring(cap[0].length);
  12565. item = {
  12566. type: 'table',
  12567. header: cap[1].replace(/^ *| *\| *$/g, '').split(/ *\| */),
  12568. align: cap[2].replace(/^ *|\| *$/g, '').split(/ *\| */),
  12569. cells: cap[3].replace(/(?: *\| *)?\n$/, '').split('\n')
  12570. };
  12571. for (i = 0; i < item.align.length; i++) {
  12572. if (/^ *-+: *$/.test(item.align[i])) {
  12573. item.align[i] = 'right';
  12574. } else if (/^ *:-+: *$/.test(item.align[i])) {
  12575. item.align[i] = 'center';
  12576. } else if (/^ *:-+ *$/.test(item.align[i])) {
  12577. item.align[i] = 'left';
  12578. } else {
  12579. item.align[i] = null;
  12580. }
  12581. }
  12582. for (i = 0; i < item.cells.length; i++) {
  12583. item.cells[i] = item.cells[i]
  12584. .replace(/^ *\| *| *\| *$/g, '')
  12585. .split(/ *\| */);
  12586. }
  12587. this.tokens.push(item);
  12588. continue;
  12589. }
  12590. // top-level paragraph
  12591. if (top && (cap = this.rules.paragraph.exec(src))) {
  12592. src = src.substring(cap[0].length);
  12593. this.tokens.push({
  12594. type: 'paragraph',
  12595. text: cap[1].charAt(cap[1].length - 1) === '\n'
  12596. ? cap[1].slice(0, -1)
  12597. : cap[1]
  12598. });
  12599. continue;
  12600. }
  12601. // text
  12602. if (cap = this.rules.text.exec(src)) {
  12603. // Top-level should never reach here.
  12604. src = src.substring(cap[0].length);
  12605. this.tokens.push({
  12606. type: 'text',
  12607. text: cap[0]
  12608. });
  12609. continue;
  12610. }
  12611. if (src) {
  12612. throw new
  12613. Error('Infinite loop on byte: ' + src.charCodeAt(0));
  12614. }
  12615. }
  12616. return this.tokens;
  12617. };
  12618. /**
  12619. * Inline-Level Grammar
  12620. */
  12621. var inline = {
  12622. escape: /^\\([\\`*{}\[\]()#+\-.!_>])/,
  12623. autolink: /^<([^ >]+(@|:\/)[^ >]+)>/,
  12624. url: noop,
  12625. tag: /^<!--[\s\S]*?-->|^<\/?\w+(?:"[^"]*"|'[^']*'|[^'">])*?>/,
  12626. link: /^!?\[(inside)\]\(href\)/,
  12627. reflink: /^!?\[(inside)\]\s*\[([^\]]*)\]/,
  12628. nolink: /^!?\[((?:\[[^\]]*\]|[^\[\]])*)\]/,
  12629. strong: /^__([\s\S]+?)__(?!_)|^\*\*([\s\S]+?)\*\*(?!\*)/,
  12630. em: /^\b_((?:[^_]|__)+?)_\b|^\*((?:\*\*|[\s\S])+?)\*(?!\*)/,
  12631. code: /^(`+)\s*([\s\S]*?[^`])\s*\1(?!`)/,
  12632. br: /^ {2,}\n(?!\s*$)/,
  12633. del: noop,
  12634. text: /^[\s\S]+?(?=[\\<!\[_*`]| {2,}\n|$)/
  12635. };
  12636. inline._inside = /(?:\[[^\]]*\]|[^\[\]]|\](?=[^\[]*\]))*/;
  12637. inline._href = /\s*<?([\s\S]*?)>?(?:\s+['"]([\s\S]*?)['"])?\s*/;
  12638. inline.link = replace(inline.link)
  12639. ('inside', inline._inside)
  12640. ('href', inline._href)
  12641. ();
  12642. inline.reflink = replace(inline.reflink)
  12643. ('inside', inline._inside)
  12644. ();
  12645. /**
  12646. * Normal Inline Grammar
  12647. */
  12648. inline.normal = merge({}, inline);
  12649. /**
  12650. * Pedantic Inline Grammar
  12651. */
  12652. inline.pedantic = merge({}, inline.normal, {
  12653. strong: /^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/,
  12654. em: /^_(?=\S)([\s\S]*?\S)_(?!_)|^\*(?=\S)([\s\S]*?\S)\*(?!\*)/
  12655. });
  12656. /**
  12657. * GFM Inline Grammar
  12658. */
  12659. inline.gfm = merge({}, inline.normal, {
  12660. escape: replace(inline.escape)('])', '~|])')(),
  12661. url: /^(https?:\/\/[^\s<]+[^<.,:;"')\]\s])/,
  12662. del: /^~~(?=\S)([\s\S]*?\S)~~/,
  12663. text: replace(inline.text)
  12664. (']|', '~]|')
  12665. ('|', '|https?://|')
  12666. ()
  12667. });
  12668. /**
  12669. * GFM + Line Breaks Inline Grammar
  12670. */
  12671. inline.breaks = merge({}, inline.gfm, {
  12672. br: replace(inline.br)('{2,}', '*')(),
  12673. text: replace(inline.gfm.text)('{2,}', '*')()
  12674. });
  12675. /**
  12676. * Inline Lexer & Compiler
  12677. */
  12678. function InlineLexer(links, options) {
  12679. this.options = options || marked.defaults;
  12680. this.links = links;
  12681. this.rules = inline.normal;
  12682. this.renderer = this.options.renderer || new Renderer;
  12683. this.renderer.options = this.options;
  12684. if (!this.links) {
  12685. throw new
  12686. Error('Tokens array requires a `links` property.');
  12687. }
  12688. if (this.options.gfm) {
  12689. if (this.options.breaks) {
  12690. this.rules = inline.breaks;
  12691. } else {
  12692. this.rules = inline.gfm;
  12693. }
  12694. } else if (this.options.pedantic) {
  12695. this.rules = inline.pedantic;
  12696. }
  12697. }
  12698. /**
  12699. * Expose Inline Rules
  12700. */
  12701. InlineLexer.rules = inline;
  12702. /**
  12703. * Static Lexing/Compiling Method
  12704. */
  12705. InlineLexer.output = function(src, links, options) {
  12706. var inline = new InlineLexer(links, options);
  12707. return inline.output(src);
  12708. };
  12709. /**
  12710. * Lexing/Compiling
  12711. */
  12712. InlineLexer.prototype.output = function(src) {
  12713. var out = ''
  12714. , link
  12715. , text
  12716. , href
  12717. , cap;
  12718. while (src) {
  12719. // escape
  12720. if (cap = this.rules.escape.exec(src)) {
  12721. src = src.substring(cap[0].length);
  12722. out += cap[1];
  12723. continue;
  12724. }
  12725. // autolink
  12726. if (cap = this.rules.autolink.exec(src)) {
  12727. src = src.substring(cap[0].length);
  12728. if (cap[2] === '@') {
  12729. text = cap[1].charAt(6) === ':'
  12730. ? this.mangle(cap[1].substring(7))
  12731. : this.mangle(cap[1]);
  12732. href = this.mangle('mailto:') + text;
  12733. } else {
  12734. text = escape(cap[1]);
  12735. href = text;
  12736. }
  12737. out += this.renderer.link(href, null, text);
  12738. continue;
  12739. }
  12740. // url (gfm)
  12741. if (!this.inLink && (cap = this.rules.url.exec(src))) {
  12742. src = src.substring(cap[0].length);
  12743. text = escape(cap[1]);
  12744. href = text;
  12745. out += this.renderer.link(href, null, text);
  12746. continue;
  12747. }
  12748. // tag
  12749. if (cap = this.rules.tag.exec(src)) {
  12750. if (!this.inLink && /^<a /i.test(cap[0])) {
  12751. this.inLink = true;
  12752. } else if (this.inLink && /^<\/a>/i.test(cap[0])) {
  12753. this.inLink = false;
  12754. }
  12755. src = src.substring(cap[0].length);
  12756. out += this.options.sanitize
  12757. ? this.options.sanitizer
  12758. ? this.options.sanitizer(cap[0])
  12759. : escape(cap[0])
  12760. : cap[0]
  12761. continue;
  12762. }
  12763. // link
  12764. if (cap = this.rules.link.exec(src)) {
  12765. src = src.substring(cap[0].length);
  12766. this.inLink = true;
  12767. out += this.outputLink(cap, {
  12768. href: cap[2],
  12769. title: cap[3]
  12770. });
  12771. this.inLink = false;
  12772. continue;
  12773. }
  12774. // reflink, nolink
  12775. if ((cap = this.rules.reflink.exec(src))
  12776. || (cap = this.rules.nolink.exec(src))) {
  12777. src = src.substring(cap[0].length);
  12778. link = (cap[2] || cap[1]).replace(/\s+/g, ' ');
  12779. link = this.links[link.toLowerCase()];
  12780. if (!link || !link.href) {
  12781. out += cap[0].charAt(0);
  12782. src = cap[0].substring(1) + src;
  12783. continue;
  12784. }
  12785. this.inLink = true;
  12786. out += this.outputLink(cap, link);
  12787. this.inLink = false;
  12788. continue;
  12789. }
  12790. // strong
  12791. if (cap = this.rules.strong.exec(src)) {
  12792. src = src.substring(cap[0].length);
  12793. out += this.renderer.strong(this.output(cap[2] || cap[1]));
  12794. continue;
  12795. }
  12796. // em
  12797. if (cap = this.rules.em.exec(src)) {
  12798. src = src.substring(cap[0].length);
  12799. out += this.renderer.em(this.output(cap[2] || cap[1]));
  12800. continue;
  12801. }
  12802. // code
  12803. if (cap = this.rules.code.exec(src)) {
  12804. src = src.substring(cap[0].length);
  12805. out += this.renderer.codespan(escape(cap[2], true));
  12806. continue;
  12807. }
  12808. // br
  12809. if (cap = this.rules.br.exec(src)) {
  12810. src = src.substring(cap[0].length);
  12811. out += this.renderer.br();
  12812. continue;
  12813. }
  12814. // del (gfm)
  12815. if (cap = this.rules.del.exec(src)) {
  12816. src = src.substring(cap[0].length);
  12817. out += this.renderer.del(this.output(cap[1]));
  12818. continue;
  12819. }
  12820. // text
  12821. if (cap = this.rules.text.exec(src)) {
  12822. src = src.substring(cap[0].length);
  12823. out += this.renderer.text(escape(this.smartypants(cap[0])));
  12824. continue;
  12825. }
  12826. if (src) {
  12827. throw new
  12828. Error('Infinite loop on byte: ' + src.charCodeAt(0));
  12829. }
  12830. }
  12831. return out;
  12832. };
  12833. /**
  12834. * Compile Link
  12835. */
  12836. InlineLexer.prototype.outputLink = function(cap, link) {
  12837. var href = escape(link.href)
  12838. , title = link.title ? escape(link.title) : null;
  12839. return cap[0].charAt(0) !== '!'
  12840. ? this.renderer.link(href, title, this.output(cap[1]))
  12841. : this.renderer.image(href, title, escape(cap[1]));
  12842. };
  12843. /**
  12844. * Smartypants Transformations
  12845. */
  12846. InlineLexer.prototype.smartypants = function(text) {
  12847. if (!this.options.smartypants) return text;
  12848. return text
  12849. // em-dashes
  12850. .replace(/---/g, '\u2014')
  12851. // en-dashes
  12852. .replace(/--/g, '\u2013')
  12853. // opening singles
  12854. .replace(/(^|[-\u2014/(\[{"\s])'/g, '$1\u2018')
  12855. // closing singles & apostrophes
  12856. .replace(/'/g, '\u2019')
  12857. // opening doubles
  12858. .replace(/(^|[-\u2014/(\[{\u2018\s])"/g, '$1\u201c')
  12859. // closing doubles
  12860. .replace(/"/g, '\u201d')
  12861. // ellipses
  12862. .replace(/\.{3}/g, '\u2026');
  12863. };
  12864. /**
  12865. * Mangle Links
  12866. */
  12867. InlineLexer.prototype.mangle = function(text) {
  12868. if (!this.options.mangle) return text;
  12869. var out = ''
  12870. , l = text.length
  12871. , i = 0
  12872. , ch;
  12873. for (; i < l; i++) {
  12874. ch = text.charCodeAt(i);
  12875. if (Math.random() > 0.5) {
  12876. ch = 'x' + ch.toString(16);
  12877. }
  12878. out += '&#' + ch + ';';
  12879. }
  12880. return out;
  12881. };
  12882. /**
  12883. * Renderer
  12884. */
  12885. function Renderer(options) {
  12886. this.options = options || {};
  12887. }
  12888. Renderer.prototype.code = function(code, lang, escaped) {
  12889. if (this.options.highlight) {
  12890. var out = this.options.highlight(code, lang);
  12891. if (out != null && out !== code) {
  12892. escaped = true;
  12893. code = out;
  12894. }
  12895. }
  12896. if (!lang) {
  12897. return '<pre><code>'
  12898. + (escaped ? code : escape(code, true))
  12899. + '\n</code></pre>';
  12900. }
  12901. return '<pre><code class="'
  12902. + this.options.langPrefix
  12903. + escape(lang, true)
  12904. + '">'
  12905. + (escaped ? code : escape(code, true))
  12906. + '\n</code></pre>\n';
  12907. };
  12908. Renderer.prototype.blockquote = function(quote) {
  12909. return '<blockquote>\n' + quote + '</blockquote>\n';
  12910. };
  12911. Renderer.prototype.html = function(html) {
  12912. return html;
  12913. };
  12914. Renderer.prototype.heading = function(text, level, raw) {
  12915. return '<h'
  12916. + level
  12917. + ' id="'
  12918. + this.options.headerPrefix
  12919. + raw.toLowerCase().replace(/[^\w]+/g, '-')
  12920. + '">'
  12921. + text
  12922. + '</h'
  12923. + level
  12924. + '>\n';
  12925. };
  12926. Renderer.prototype.hr = function() {
  12927. return this.options.xhtml ? '<hr/>\n' : '<hr>\n';
  12928. };
  12929. Renderer.prototype.list = function(body, ordered) {
  12930. var type = ordered ? 'ol' : 'ul';
  12931. return '<' + type + '>\n' + body + '</' + type + '>\n';
  12932. };
  12933. Renderer.prototype.listitem = function(text) {
  12934. return '<li>' + text + '</li>\n';
  12935. };
  12936. Renderer.prototype.paragraph = function(text) {
  12937. return '<p>' + text + '</p>\n';
  12938. };
  12939. Renderer.prototype.table = function(header, body) {
  12940. return '<table>\n'
  12941. + '<thead>\n'
  12942. + header
  12943. + '</thead>\n'
  12944. + '<tbody>\n'
  12945. + body
  12946. + '</tbody>\n'
  12947. + '</table>\n';
  12948. };
  12949. Renderer.prototype.tablerow = function(content) {
  12950. return '<tr>\n' + content + '</tr>\n';
  12951. };
  12952. Renderer.prototype.tablecell = function(content, flags) {
  12953. var type = flags.header ? 'th' : 'td';
  12954. var tag = flags.align
  12955. ? '<' + type + ' style="text-align:' + flags.align + '">'
  12956. : '<' + type + '>';
  12957. return tag + content + '</' + type + '>\n';
  12958. };
  12959. // span level renderer
  12960. Renderer.prototype.strong = function(text) {
  12961. return '<strong>' + text + '</strong>';
  12962. };
  12963. Renderer.prototype.em = function(text) {
  12964. return '<em>' + text + '</em>';
  12965. };
  12966. Renderer.prototype.codespan = function(text) {
  12967. return '<code>' + text + '</code>';
  12968. };
  12969. Renderer.prototype.br = function() {
  12970. return this.options.xhtml ? '<br/>' : '<br>';
  12971. };
  12972. Renderer.prototype.del = function(text) {
  12973. return '<del>' + text + '</del>';
  12974. };
  12975. Renderer.prototype.link = function(href, title, text) {
  12976. if (this.options.sanitize) {
  12977. try {
  12978. var prot = decodeURIComponent(unescape(href))
  12979. .replace(/[^\w:]/g, '')
  12980. .toLowerCase();
  12981. } catch (e) {
  12982. return '';
  12983. }
  12984. if (prot.indexOf('javascript:') === 0 || prot.indexOf('vbscript:') === 0 || prot.indexOf('data:') === 0) {
  12985. return '';
  12986. }
  12987. }
  12988. var out = '<a href="' + href + '"';
  12989. if (title) {
  12990. out += ' title="' + title + '"';
  12991. }
  12992. out += '>' + text + '</a>';
  12993. return out;
  12994. };
  12995. Renderer.prototype.image = function(href, title, text) {
  12996. var out = '<img src="' + href + '" alt="' + text + '"';
  12997. if (title) {
  12998. out += ' title="' + title + '"';
  12999. }
  13000. out += this.options.xhtml ? '/>' : '>';
  13001. return out;
  13002. };
  13003. Renderer.prototype.text = function(text) {
  13004. return text;
  13005. };
  13006. /**
  13007. * Parsing & Compiling
  13008. */
  13009. function Parser(options) {
  13010. this.tokens = [];
  13011. this.token = null;
  13012. this.options = options || marked.defaults;
  13013. this.options.renderer = this.options.renderer || new Renderer;
  13014. this.renderer = this.options.renderer;
  13015. this.renderer.options = this.options;
  13016. }
  13017. /**
  13018. * Static Parse Method
  13019. */
  13020. Parser.parse = function(src, options, renderer) {
  13021. var parser = new Parser(options, renderer);
  13022. return parser.parse(src);
  13023. };
  13024. /**
  13025. * Parse Loop
  13026. */
  13027. Parser.prototype.parse = function(src) {
  13028. this.inline = new InlineLexer(src.links, this.options, this.renderer);
  13029. this.tokens = src.reverse();
  13030. var out = '';
  13031. while (this.next()) {
  13032. out += this.tok();
  13033. }
  13034. return out;
  13035. };
  13036. /**
  13037. * Next Token
  13038. */
  13039. Parser.prototype.next = function() {
  13040. return this.token = this.tokens.pop();
  13041. };
  13042. /**
  13043. * Preview Next Token
  13044. */
  13045. Parser.prototype.peek = function() {
  13046. return this.tokens[this.tokens.length - 1] || 0;
  13047. };
  13048. /**
  13049. * Parse Text Tokens
  13050. */
  13051. Parser.prototype.parseText = function() {
  13052. var body = this.token.text;
  13053. while (this.peek().type === 'text') {
  13054. body += '\n' + this.next().text;
  13055. }
  13056. return this.inline.output(body);
  13057. };
  13058. /**
  13059. * Parse Current Token
  13060. */
  13061. Parser.prototype.tok = function() {
  13062. switch (this.token.type) {
  13063. case 'space': {
  13064. return '';
  13065. }
  13066. case 'hr': {
  13067. return this.renderer.hr();
  13068. }
  13069. case 'heading': {
  13070. return this.renderer.heading(
  13071. this.inline.output(this.token.text),
  13072. this.token.depth,
  13073. this.token.text);
  13074. }
  13075. case 'code': {
  13076. return this.renderer.code(this.token.text,
  13077. this.token.lang,
  13078. this.token.escaped);
  13079. }
  13080. case 'table': {
  13081. var header = ''
  13082. , body = ''
  13083. , i
  13084. , row
  13085. , cell
  13086. , flags
  13087. , j;
  13088. // header
  13089. cell = '';
  13090. for (i = 0; i < this.token.header.length; i++) {
  13091. flags = { header: true, align: this.token.align[i] };
  13092. cell += this.renderer.tablecell(
  13093. this.inline.output(this.token.header[i]),
  13094. { header: true, align: this.token.align[i] }
  13095. );
  13096. }
  13097. header += this.renderer.tablerow(cell);
  13098. for (i = 0; i < this.token.cells.length; i++) {
  13099. row = this.token.cells[i];
  13100. cell = '';
  13101. for (j = 0; j < row.length; j++) {
  13102. cell += this.renderer.tablecell(
  13103. this.inline.output(row[j]),
  13104. { header: false, align: this.token.align[j] }
  13105. );
  13106. }
  13107. body += this.renderer.tablerow(cell);
  13108. }
  13109. return this.renderer.table(header, body);
  13110. }
  13111. case 'blockquote_start': {
  13112. var body = '';
  13113. while (this.next().type !== 'blockquote_end') {
  13114. body += this.tok();
  13115. }
  13116. return this.renderer.blockquote(body);
  13117. }
  13118. case 'list_start': {
  13119. var body = ''
  13120. , ordered = this.token.ordered;
  13121. while (this.next().type !== 'list_end') {
  13122. body += this.tok();
  13123. }
  13124. return this.renderer.list(body, ordered);
  13125. }
  13126. case 'list_item_start': {
  13127. var body = '';
  13128. while (this.next().type !== 'list_item_end') {
  13129. body += this.token.type === 'text'
  13130. ? this.parseText()
  13131. : this.tok();
  13132. }
  13133. return this.renderer.listitem(body);
  13134. }
  13135. case 'loose_item_start': {
  13136. var body = '';
  13137. while (this.next().type !== 'list_item_end') {
  13138. body += this.tok();
  13139. }
  13140. return this.renderer.listitem(body);
  13141. }
  13142. case 'html': {
  13143. var html = !this.token.pre && !this.options.pedantic
  13144. ? this.inline.output(this.token.text)
  13145. : this.token.text;
  13146. return this.renderer.html(html);
  13147. }
  13148. case 'paragraph': {
  13149. return this.renderer.paragraph(this.inline.output(this.token.text));
  13150. }
  13151. case 'text': {
  13152. return this.renderer.paragraph(this.parseText());
  13153. }
  13154. }
  13155. };
  13156. /**
  13157. * Helpers
  13158. */
  13159. function escape(html, encode) {
  13160. return html
  13161. .replace(!encode ? /&(?!#?\w+;)/g : /&/g, '&amp;')
  13162. .replace(/</g, '&lt;')
  13163. .replace(/>/g, '&gt;')
  13164. .replace(/"/g, '&quot;')
  13165. .replace(/'/g, '&#39;');
  13166. }
  13167. function unescape(html) {
  13168. // explicitly match decimal, hex, and named HTML entities
  13169. return html.replace(/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/g, function(_, n) {
  13170. n = n.toLowerCase();
  13171. if (n === 'colon') return ':';
  13172. if (n.charAt(0) === '#') {
  13173. return n.charAt(1) === 'x'
  13174. ? String.fromCharCode(parseInt(n.substring(2), 16))
  13175. : String.fromCharCode(+n.substring(1));
  13176. }
  13177. return '';
  13178. });
  13179. }
  13180. function replace(regex, opt) {
  13181. regex = regex.source;
  13182. opt = opt || '';
  13183. return function self(name, val) {
  13184. if (!name) return new RegExp(regex, opt);
  13185. val = val.source || val;
  13186. val = val.replace(/(^|[^\[])\^/g, '$1');
  13187. regex = regex.replace(name, val);
  13188. return self;
  13189. };
  13190. }
  13191. function noop() {}
  13192. noop.exec = noop;
  13193. function merge(obj) {
  13194. var i = 1
  13195. , target
  13196. , key;
  13197. for (; i < arguments.length; i++) {
  13198. target = arguments[i];
  13199. for (key in target) {
  13200. if (Object.prototype.hasOwnProperty.call(target, key)) {
  13201. obj[key] = target[key];
  13202. }
  13203. }
  13204. }
  13205. return obj;
  13206. }
  13207. /**
  13208. * Marked
  13209. */
  13210. function marked(src, opt, callback) {
  13211. if (callback || typeof opt === 'function') {
  13212. if (!callback) {
  13213. callback = opt;
  13214. opt = null;
  13215. }
  13216. opt = merge({}, marked.defaults, opt || {});
  13217. var highlight = opt.highlight
  13218. , tokens
  13219. , pending
  13220. , i = 0;
  13221. try {
  13222. tokens = Lexer.lex(src, opt)
  13223. } catch (e) {
  13224. return callback(e);
  13225. }
  13226. pending = tokens.length;
  13227. var done = function(err) {
  13228. if (err) {
  13229. opt.highlight = highlight;
  13230. return callback(err);
  13231. }
  13232. var out;
  13233. try {
  13234. out = Parser.parse(tokens, opt);
  13235. } catch (e) {
  13236. err = e;
  13237. }
  13238. opt.highlight = highlight;
  13239. return err
  13240. ? callback(err)
  13241. : callback(null, out);
  13242. };
  13243. if (!highlight || highlight.length < 3) {
  13244. return done();
  13245. }
  13246. delete opt.highlight;
  13247. if (!pending) return done();
  13248. for (; i < tokens.length; i++) {
  13249. (function(token) {
  13250. if (token.type !== 'code') {
  13251. return --pending || done();
  13252. }
  13253. return highlight(token.text, token.lang, function(err, code) {
  13254. if (err) return done(err);
  13255. if (code == null || code === token.text) {
  13256. return --pending || done();
  13257. }
  13258. token.text = code;
  13259. token.escaped = true;
  13260. --pending || done();
  13261. });
  13262. })(tokens[i]);
  13263. }
  13264. return;
  13265. }
  13266. try {
  13267. if (opt) opt = merge({}, marked.defaults, opt);
  13268. return Parser.parse(Lexer.lex(src, opt), opt);
  13269. } catch (e) {
  13270. e.message += '\nPlease report this to https://github.com/chjj/marked.';
  13271. if ((opt || marked.defaults).silent) {
  13272. return '<p>An error occured:</p><pre>'
  13273. + escape(e.message + '', true)
  13274. + '</pre>';
  13275. }
  13276. throw e;
  13277. }
  13278. }
  13279. /**
  13280. * Options
  13281. */
  13282. marked.options =
  13283. marked.setOptions = function(opt) {
  13284. merge(marked.defaults, opt);
  13285. return marked;
  13286. };
  13287. marked.defaults = {
  13288. gfm: true,
  13289. tables: true,
  13290. breaks: false,
  13291. pedantic: false,
  13292. sanitize: false,
  13293. sanitizer: null,
  13294. mangle: true,
  13295. smartLists: false,
  13296. silent: false,
  13297. highlight: null,
  13298. langPrefix: 'lang-',
  13299. smartypants: false,
  13300. headerPrefix: '',
  13301. renderer: new Renderer,
  13302. xhtml: false
  13303. };
  13304. /**
  13305. * Expose
  13306. */
  13307. marked.Parser = Parser;
  13308. marked.parser = Parser.parse;
  13309. marked.Renderer = Renderer;
  13310. marked.Lexer = Lexer;
  13311. marked.lexer = Lexer.lex;
  13312. marked.InlineLexer = InlineLexer;
  13313. marked.inlineLexer = InlineLexer.output;
  13314. marked.parse = marked;
  13315. if (typeof module !== 'undefined' && typeof exports === 'object') {
  13316. module.exports = marked;
  13317. } else if (typeof define === 'function' && define.amd) {
  13318. define(function() { return marked; });
  13319. } else {
  13320. this.marked = marked;
  13321. }
  13322. }).call(function() {
  13323. return this || (typeof window !== 'undefined' ? window : global);
  13324. }());
  13325. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  13326. },{}],17:[function(require,module,exports){
  13327. (function (Buffer,__dirname){
  13328. /* globals chrome: false */
  13329. /* globals __dirname: false */
  13330. /* globals require: false */
  13331. /* globals Buffer: false */
  13332. /* globals module: false */
  13333. /**
  13334. * Typo is a JavaScript implementation of a spellchecker using hunspell-style
  13335. * dictionaries.
  13336. */
  13337. var Typo;
  13338. (function () {
  13339. "use strict";
  13340. /**
  13341. * Typo constructor.
  13342. *
  13343. * @param {String} [dictionary] The locale code of the dictionary being used. e.g.,
  13344. * "en_US". This is only used to auto-load dictionaries.
  13345. * @param {String} [affData] The data from the dictionary's .aff file. If omitted
  13346. * and Typo.js is being used in a Chrome extension, the .aff
  13347. * file will be loaded automatically from
  13348. * lib/typo/dictionaries/[dictionary]/[dictionary].aff
  13349. * In other environments, it will be loaded from
  13350. * [settings.dictionaryPath]/dictionaries/[dictionary]/[dictionary].aff
  13351. * @param {String} [wordsData] The data from the dictionary's .dic file. If omitted
  13352. * and Typo.js is being used in a Chrome extension, the .dic
  13353. * file will be loaded automatically from
  13354. * lib/typo/dictionaries/[dictionary]/[dictionary].dic
  13355. * In other environments, it will be loaded from
  13356. * [settings.dictionaryPath]/dictionaries/[dictionary]/[dictionary].dic
  13357. * @param {Object} [settings] Constructor settings. Available properties are:
  13358. * {String} [dictionaryPath]: path to load dictionary from in non-chrome
  13359. * environment.
  13360. * {Object} [flags]: flag information.
  13361. * {Boolean} [asyncLoad]: If true, affData and wordsData will be loaded
  13362. * asynchronously.
  13363. * {Function} [loadedCallback]: Called when both affData and wordsData
  13364. * have been loaded. Only used if asyncLoad is set to true. The parameter
  13365. * is the instantiated Typo object.
  13366. *
  13367. * @returns {Typo} A Typo object.
  13368. */
  13369. Typo = function (dictionary, affData, wordsData, settings) {
  13370. settings = settings || {};
  13371. this.dictionary = null;
  13372. this.rules = {};
  13373. this.dictionaryTable = {};
  13374. this.compoundRules = [];
  13375. this.compoundRuleCodes = {};
  13376. this.replacementTable = [];
  13377. this.flags = settings.flags || {};
  13378. this.memoized = {};
  13379. this.loaded = false;
  13380. var self = this;
  13381. var path;
  13382. // Loop-control variables.
  13383. var i, j, _len, _jlen;
  13384. if (dictionary) {
  13385. self.dictionary = dictionary;
  13386. // If the data is preloaded, just setup the Typo object.
  13387. if (affData && wordsData) {
  13388. setup();
  13389. }
  13390. // Loading data for Chrome extentions.
  13391. else if (typeof window !== 'undefined' && 'chrome' in window && 'extension' in window.chrome && 'getURL' in window.chrome.extension) {
  13392. if (settings.dictionaryPath) {
  13393. path = settings.dictionaryPath;
  13394. }
  13395. else {
  13396. path = "typo/dictionaries";
  13397. }
  13398. if (!affData) readDataFile(chrome.extension.getURL(path + "/" + dictionary + "/" + dictionary + ".aff"), setAffData);
  13399. if (!wordsData) readDataFile(chrome.extension.getURL(path + "/" + dictionary + "/" + dictionary + ".dic"), setWordsData);
  13400. }
  13401. else {
  13402. if (settings.dictionaryPath) {
  13403. path = settings.dictionaryPath;
  13404. }
  13405. else if (typeof __dirname !== 'undefined') {
  13406. path = __dirname + '/dictionaries';
  13407. }
  13408. else {
  13409. path = './dictionaries';
  13410. }
  13411. if (!affData) readDataFile(path + "/" + dictionary + "/" + dictionary + ".aff", setAffData);
  13412. if (!wordsData) readDataFile(path + "/" + dictionary + "/" + dictionary + ".dic", setWordsData);
  13413. }
  13414. }
  13415. function readDataFile(url, setFunc) {
  13416. var response = self._readFile(url, null, settings.asyncLoad);
  13417. if (settings.asyncLoad) {
  13418. response.then(function(data) {
  13419. setFunc(data);
  13420. });
  13421. }
  13422. else {
  13423. setFunc(response);
  13424. }
  13425. }
  13426. function setAffData(data) {
  13427. affData = data;
  13428. if (wordsData) {
  13429. setup();
  13430. }
  13431. }
  13432. function setWordsData(data) {
  13433. wordsData = data;
  13434. if (affData) {
  13435. setup();
  13436. }
  13437. }
  13438. function setup() {
  13439. self.rules = self._parseAFF(affData);
  13440. // Save the rule codes that are used in compound rules.
  13441. self.compoundRuleCodes = {};
  13442. for (i = 0, _len = self.compoundRules.length; i < _len; i++) {
  13443. var rule = self.compoundRules[i];
  13444. for (j = 0, _jlen = rule.length; j < _jlen; j++) {
  13445. self.compoundRuleCodes[rule[j]] = [];
  13446. }
  13447. }
  13448. // If we add this ONLYINCOMPOUND flag to self.compoundRuleCodes, then _parseDIC
  13449. // will do the work of saving the list of words that are compound-only.
  13450. if ("ONLYINCOMPOUND" in self.flags) {
  13451. self.compoundRuleCodes[self.flags.ONLYINCOMPOUND] = [];
  13452. }
  13453. self.dictionaryTable = self._parseDIC(wordsData);
  13454. // Get rid of any codes from the compound rule codes that are never used
  13455. // (or that were special regex characters). Not especially necessary...
  13456. for (i in self.compoundRuleCodes) {
  13457. if (self.compoundRuleCodes[i].length === 0) {
  13458. delete self.compoundRuleCodes[i];
  13459. }
  13460. }
  13461. // Build the full regular expressions for each compound rule.
  13462. // I have a feeling (but no confirmation yet) that this method of
  13463. // testing for compound words is probably slow.
  13464. for (i = 0, _len = self.compoundRules.length; i < _len; i++) {
  13465. var ruleText = self.compoundRules[i];
  13466. var expressionText = "";
  13467. for (j = 0, _jlen = ruleText.length; j < _jlen; j++) {
  13468. var character = ruleText[j];
  13469. if (character in self.compoundRuleCodes) {
  13470. expressionText += "(" + self.compoundRuleCodes[character].join("|") + ")";
  13471. }
  13472. else {
  13473. expressionText += character;
  13474. }
  13475. }
  13476. self.compoundRules[i] = new RegExp(expressionText, "i");
  13477. }
  13478. self.loaded = true;
  13479. if (settings.asyncLoad && settings.loadedCallback) {
  13480. settings.loadedCallback(self);
  13481. }
  13482. }
  13483. return this;
  13484. };
  13485. Typo.prototype = {
  13486. /**
  13487. * Loads a Typo instance from a hash of all of the Typo properties.
  13488. *
  13489. * @param object obj A hash of Typo properties, probably gotten from a JSON.parse(JSON.stringify(typo_instance)).
  13490. */
  13491. load : function (obj) {
  13492. for (var i in obj) {
  13493. if (obj.hasOwnProperty(i)) {
  13494. this[i] = obj[i];
  13495. }
  13496. }
  13497. return this;
  13498. },
  13499. /**
  13500. * Read the contents of a file.
  13501. *
  13502. * @param {String} path The path (relative) to the file.
  13503. * @param {String} [charset="ISO8859-1"] The expected charset of the file
  13504. * @param {Boolean} async If true, the file will be read asynchronously. For node.js this does nothing, all
  13505. * files are read synchronously.
  13506. * @returns {String} The file data if async is false, otherwise a promise object. If running node.js, the data is
  13507. * always returned.
  13508. */
  13509. _readFile : function (path, charset, async) {
  13510. charset = charset || "utf8";
  13511. if (typeof XMLHttpRequest !== 'undefined') {
  13512. var promise;
  13513. var req = new XMLHttpRequest();
  13514. req.open("GET", path, async);
  13515. if (async) {
  13516. promise = new Promise(function(resolve, reject) {
  13517. req.onload = function() {
  13518. if (req.status === 200) {
  13519. resolve(req.responseText);
  13520. }
  13521. else {
  13522. reject(req.statusText);
  13523. }
  13524. };
  13525. req.onerror = function() {
  13526. reject(req.statusText);
  13527. }
  13528. });
  13529. }
  13530. if (req.overrideMimeType)
  13531. req.overrideMimeType("text/plain; charset=" + charset);
  13532. req.send(null);
  13533. return async ? promise : req.responseText;
  13534. }
  13535. else if (typeof require !== 'undefined') {
  13536. // Node.js
  13537. var fs = require("fs");
  13538. try {
  13539. if (fs.existsSync(path)) {
  13540. var stats = fs.statSync(path);
  13541. var fileDescriptor = fs.openSync(path, 'r');
  13542. var buffer = new Buffer(stats.size);
  13543. fs.readSync(fileDescriptor, buffer, 0, buffer.length, null);
  13544. return buffer.toString(charset, 0, buffer.length);
  13545. }
  13546. else {
  13547. console.log("Path " + path + " does not exist.");
  13548. }
  13549. } catch (e) {
  13550. console.log(e);
  13551. return '';
  13552. }
  13553. }
  13554. },
  13555. /**
  13556. * Parse the rules out from a .aff file.
  13557. *
  13558. * @param {String} data The contents of the affix file.
  13559. * @returns object The rules from the file.
  13560. */
  13561. _parseAFF : function (data) {
  13562. var rules = {};
  13563. var line, subline, numEntries, lineParts;
  13564. var i, j, _len, _jlen;
  13565. // Remove comment lines
  13566. data = this._removeAffixComments(data);
  13567. var lines = data.split("\n");
  13568. for (i = 0, _len = lines.length; i < _len; i++) {
  13569. line = lines[i];
  13570. var definitionParts = line.split(/\s+/);
  13571. var ruleType = definitionParts[0];
  13572. if (ruleType == "PFX" || ruleType == "SFX") {
  13573. var ruleCode = definitionParts[1];
  13574. var combineable = definitionParts[2];
  13575. numEntries = parseInt(definitionParts[3], 10);
  13576. var entries = [];
  13577. for (j = i + 1, _jlen = i + 1 + numEntries; j < _jlen; j++) {
  13578. subline = lines[j];
  13579. lineParts = subline.split(/\s+/);
  13580. var charactersToRemove = lineParts[2];
  13581. var additionParts = lineParts[3].split("/");
  13582. var charactersToAdd = additionParts[0];
  13583. if (charactersToAdd === "0") charactersToAdd = "";
  13584. var continuationClasses = this.parseRuleCodes(additionParts[1]);
  13585. var regexToMatch = lineParts[4];
  13586. var entry = {};
  13587. entry.add = charactersToAdd;
  13588. if (continuationClasses.length > 0) entry.continuationClasses = continuationClasses;
  13589. if (regexToMatch !== ".") {
  13590. if (ruleType === "SFX") {
  13591. entry.match = new RegExp(regexToMatch + "$");
  13592. }
  13593. else {
  13594. entry.match = new RegExp("^" + regexToMatch);
  13595. }
  13596. }
  13597. if (charactersToRemove != "0") {
  13598. if (ruleType === "SFX") {
  13599. entry.remove = new RegExp(charactersToRemove + "$");
  13600. }
  13601. else {
  13602. entry.remove = charactersToRemove;
  13603. }
  13604. }
  13605. entries.push(entry);
  13606. }
  13607. rules[ruleCode] = { "type" : ruleType, "combineable" : (combineable == "Y"), "entries" : entries };
  13608. i += numEntries;
  13609. }
  13610. else if (ruleType === "COMPOUNDRULE") {
  13611. numEntries = parseInt(definitionParts[1], 10);
  13612. for (j = i + 1, _jlen = i + 1 + numEntries; j < _jlen; j++) {
  13613. line = lines[j];
  13614. lineParts = line.split(/\s+/);
  13615. this.compoundRules.push(lineParts[1]);
  13616. }
  13617. i += numEntries;
  13618. }
  13619. else if (ruleType === "REP") {
  13620. lineParts = line.split(/\s+/);
  13621. if (lineParts.length === 3) {
  13622. this.replacementTable.push([ lineParts[1], lineParts[2] ]);
  13623. }
  13624. }
  13625. else {
  13626. // ONLYINCOMPOUND
  13627. // COMPOUNDMIN
  13628. // FLAG
  13629. // KEEPCASE
  13630. // NEEDAFFIX
  13631. this.flags[ruleType] = definitionParts[1];
  13632. }
  13633. }
  13634. return rules;
  13635. },
  13636. /**
  13637. * Removes comment lines and then cleans up blank lines and trailing whitespace.
  13638. *
  13639. * @param {String} data The data from an affix file.
  13640. * @return {String} The cleaned-up data.
  13641. */
  13642. _removeAffixComments : function (data) {
  13643. // Remove comments
  13644. // This used to remove any string starting with '#' up to the end of the line,
  13645. // but some COMPOUNDRULE definitions include '#' as part of the rule.
  13646. // I haven't seen any affix files that use comments on the same line as real data,
  13647. // so I don't think this will break anything.
  13648. data = data.replace(/^\s*#.*$/mg, "");
  13649. // Trim each line
  13650. data = data.replace(/^\s\s*/m, '').replace(/\s\s*$/m, '');
  13651. // Remove blank lines.
  13652. data = data.replace(/\n{2,}/g, "\n");
  13653. // Trim the entire string
  13654. data = data.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
  13655. return data;
  13656. },
  13657. /**
  13658. * Parses the words out from the .dic file.
  13659. *
  13660. * @param {String} data The data from the dictionary file.
  13661. * @returns object The lookup table containing all of the words and
  13662. * word forms from the dictionary.
  13663. */
  13664. _parseDIC : function (data) {
  13665. data = this._removeDicComments(data);
  13666. var lines = data.split("\n");
  13667. var dictionaryTable = {};
  13668. function addWord(word, rules) {
  13669. // Some dictionaries will list the same word multiple times with different rule sets.
  13670. if (!dictionaryTable.hasOwnProperty(word)) {
  13671. dictionaryTable[word] = null;
  13672. }
  13673. if (rules.length > 0) {
  13674. if (dictionaryTable[word] === null) {
  13675. dictionaryTable[word] = [];
  13676. }
  13677. dictionaryTable[word].push(rules);
  13678. }
  13679. }
  13680. // The first line is the number of words in the dictionary.
  13681. for (var i = 1, _len = lines.length; i < _len; i++) {
  13682. var line = lines[i];
  13683. var parts = line.split("/", 2);
  13684. var word = parts[0];
  13685. // Now for each affix rule, generate that form of the word.
  13686. if (parts.length > 1) {
  13687. var ruleCodesArray = this.parseRuleCodes(parts[1]);
  13688. // Save the ruleCodes for compound word situations.
  13689. if (!("NEEDAFFIX" in this.flags) || ruleCodesArray.indexOf(this.flags.NEEDAFFIX) == -1) {
  13690. addWord(word, ruleCodesArray);
  13691. }
  13692. for (var j = 0, _jlen = ruleCodesArray.length; j < _jlen; j++) {
  13693. var code = ruleCodesArray[j];
  13694. var rule = this.rules[code];
  13695. if (rule) {
  13696. var newWords = this._applyRule(word, rule);
  13697. for (var ii = 0, _iilen = newWords.length; ii < _iilen; ii++) {
  13698. var newWord = newWords[ii];
  13699. addWord(newWord, []);
  13700. if (rule.combineable) {
  13701. for (var k = j + 1; k < _jlen; k++) {
  13702. var combineCode = ruleCodesArray[k];
  13703. var combineRule = this.rules[combineCode];
  13704. if (combineRule) {
  13705. if (combineRule.combineable && (rule.type != combineRule.type)) {
  13706. var otherNewWords = this._applyRule(newWord, combineRule);
  13707. for (var iii = 0, _iiilen = otherNewWords.length; iii < _iiilen; iii++) {
  13708. var otherNewWord = otherNewWords[iii];
  13709. addWord(otherNewWord, []);
  13710. }
  13711. }
  13712. }
  13713. }
  13714. }
  13715. }
  13716. }
  13717. if (code in this.compoundRuleCodes) {
  13718. this.compoundRuleCodes[code].push(word);
  13719. }
  13720. }
  13721. }
  13722. else {
  13723. addWord(word.trim(), []);
  13724. }
  13725. }
  13726. return dictionaryTable;
  13727. },
  13728. /**
  13729. * Removes comment lines and then cleans up blank lines and trailing whitespace.
  13730. *
  13731. * @param {String} data The data from a .dic file.
  13732. * @return {String} The cleaned-up data.
  13733. */
  13734. _removeDicComments : function (data) {
  13735. // I can't find any official documentation on it, but at least the de_DE
  13736. // dictionary uses tab-indented lines as comments.
  13737. // Remove comments
  13738. data = data.replace(/^\t.*$/mg, "");
  13739. return data;
  13740. },
  13741. parseRuleCodes : function (textCodes) {
  13742. if (!textCodes) {
  13743. return [];
  13744. }
  13745. else if (!("FLAG" in this.flags)) {
  13746. return textCodes.split("");
  13747. }
  13748. else if (this.flags.FLAG === "long") {
  13749. var flags = [];
  13750. for (var i = 0, _len = textCodes.length; i < _len; i += 2) {
  13751. flags.push(textCodes.substr(i, 2));
  13752. }
  13753. return flags;
  13754. }
  13755. else if (this.flags.FLAG === "num") {
  13756. return textCodes.split(",");
  13757. }
  13758. },
  13759. /**
  13760. * Applies an affix rule to a word.
  13761. *
  13762. * @param {String} word The base word.
  13763. * @param {Object} rule The affix rule.
  13764. * @returns {String[]} The new words generated by the rule.
  13765. */
  13766. _applyRule : function (word, rule) {
  13767. var entries = rule.entries;
  13768. var newWords = [];
  13769. for (var i = 0, _len = entries.length; i < _len; i++) {
  13770. var entry = entries[i];
  13771. if (!entry.match || word.match(entry.match)) {
  13772. var newWord = word;
  13773. if (entry.remove) {
  13774. newWord = newWord.replace(entry.remove, "");
  13775. }
  13776. if (rule.type === "SFX") {
  13777. newWord = newWord + entry.add;
  13778. }
  13779. else {
  13780. newWord = entry.add + newWord;
  13781. }
  13782. newWords.push(newWord);
  13783. if ("continuationClasses" in entry) {
  13784. for (var j = 0, _jlen = entry.continuationClasses.length; j < _jlen; j++) {
  13785. var continuationRule = this.rules[entry.continuationClasses[j]];
  13786. if (continuationRule) {
  13787. newWords = newWords.concat(this._applyRule(newWord, continuationRule));
  13788. }
  13789. /*
  13790. else {
  13791. // This shouldn't happen, but it does, at least in the de_DE dictionary.
  13792. // I think the author mistakenly supplied lower-case rule codes instead
  13793. // of upper-case.
  13794. }
  13795. */
  13796. }
  13797. }
  13798. }
  13799. }
  13800. return newWords;
  13801. },
  13802. /**
  13803. * Checks whether a word or a capitalization variant exists in the current dictionary.
  13804. * The word is trimmed and several variations of capitalizations are checked.
  13805. * If you want to check a word without any changes made to it, call checkExact()
  13806. *
  13807. * @see http://blog.stevenlevithan.com/archives/faster-trim-javascript re:trimming function
  13808. *
  13809. * @param {String} aWord The word to check.
  13810. * @returns {Boolean}
  13811. */
  13812. check : function (aWord) {
  13813. if (!this.loaded) {
  13814. throw "Dictionary not loaded.";
  13815. }
  13816. // Remove leading and trailing whitespace
  13817. var trimmedWord = aWord.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
  13818. if (this.checkExact(trimmedWord)) {
  13819. return true;
  13820. }
  13821. // The exact word is not in the dictionary.
  13822. if (trimmedWord.toUpperCase() === trimmedWord) {
  13823. // The word was supplied in all uppercase.
  13824. // Check for a capitalized form of the word.
  13825. var capitalizedWord = trimmedWord[0] + trimmedWord.substring(1).toLowerCase();
  13826. if (this.hasFlag(capitalizedWord, "KEEPCASE")) {
  13827. // Capitalization variants are not allowed for this word.
  13828. return false;
  13829. }
  13830. if (this.checkExact(capitalizedWord)) {
  13831. return true;
  13832. }
  13833. }
  13834. var lowercaseWord = trimmedWord.toLowerCase();
  13835. if (lowercaseWord !== trimmedWord) {
  13836. if (this.hasFlag(lowercaseWord, "KEEPCASE")) {
  13837. // Capitalization variants are not allowed for this word.
  13838. return false;
  13839. }
  13840. // Check for a lowercase form
  13841. if (this.checkExact(lowercaseWord)) {
  13842. return true;
  13843. }
  13844. }
  13845. return false;
  13846. },
  13847. /**
  13848. * Checks whether a word exists in the current dictionary.
  13849. *
  13850. * @param {String} word The word to check.
  13851. * @returns {Boolean}
  13852. */
  13853. checkExact : function (word) {
  13854. if (!this.loaded) {
  13855. throw "Dictionary not loaded.";
  13856. }
  13857. var ruleCodes = this.dictionaryTable[word];
  13858. var i, _len;
  13859. if (typeof ruleCodes === 'undefined') {
  13860. // Check if this might be a compound word.
  13861. if ("COMPOUNDMIN" in this.flags && word.length >= this.flags.COMPOUNDMIN) {
  13862. for (i = 0, _len = this.compoundRules.length; i < _len; i++) {
  13863. if (word.match(this.compoundRules[i])) {
  13864. return true;
  13865. }
  13866. }
  13867. }
  13868. }
  13869. else if (ruleCodes === null) {
  13870. // a null (but not undefined) value for an entry in the dictionary table
  13871. // means that the word is in the dictionary but has no flags.
  13872. return true;
  13873. }
  13874. else if (typeof ruleCodes === 'object') { // this.dictionary['hasOwnProperty'] will be a function.
  13875. for (i = 0, _len = ruleCodes.length; i < _len; i++) {
  13876. if (!this.hasFlag(word, "ONLYINCOMPOUND", ruleCodes[i])) {
  13877. return true;
  13878. }
  13879. }
  13880. }
  13881. return false;
  13882. },
  13883. /**
  13884. * Looks up whether a given word is flagged with a given flag.
  13885. *
  13886. * @param {String} word The word in question.
  13887. * @param {String} flag The flag in question.
  13888. * @return {Boolean}
  13889. */
  13890. hasFlag : function (word, flag, wordFlags) {
  13891. if (!this.loaded) {
  13892. throw "Dictionary not loaded.";
  13893. }
  13894. if (flag in this.flags) {
  13895. if (typeof wordFlags === 'undefined') {
  13896. wordFlags = Array.prototype.concat.apply([], this.dictionaryTable[word]);
  13897. }
  13898. if (wordFlags && wordFlags.indexOf(this.flags[flag]) !== -1) {
  13899. return true;
  13900. }
  13901. }
  13902. return false;
  13903. },
  13904. /**
  13905. * Returns a list of suggestions for a misspelled word.
  13906. *
  13907. * @see http://www.norvig.com/spell-correct.html for the basis of this suggestor.
  13908. * This suggestor is primitive, but it works.
  13909. *
  13910. * @param {String} word The misspelling.
  13911. * @param {Number} [limit=5] The maximum number of suggestions to return.
  13912. * @returns {String[]} The array of suggestions.
  13913. */
  13914. alphabet : "",
  13915. suggest : function (word, limit) {
  13916. if (!this.loaded) {
  13917. throw "Dictionary not loaded.";
  13918. }
  13919. limit = limit || 5;
  13920. if (this.memoized.hasOwnProperty(word)) {
  13921. var memoizedLimit = this.memoized[word]['limit'];
  13922. // Only return the cached list if it's big enough or if there weren't enough suggestions
  13923. // to fill a smaller limit.
  13924. if (limit <= memoizedLimit || this.memoized[word]['suggestions'].length < memoizedLimit) {
  13925. return this.memoized[word]['suggestions'].slice(0, limit);
  13926. }
  13927. }
  13928. if (this.check(word)) return [];
  13929. // Check the replacement table.
  13930. for (var i = 0, _len = this.replacementTable.length; i < _len; i++) {
  13931. var replacementEntry = this.replacementTable[i];
  13932. if (word.indexOf(replacementEntry[0]) !== -1) {
  13933. var correctedWord = word.replace(replacementEntry[0], replacementEntry[1]);
  13934. if (this.check(correctedWord)) {
  13935. return [ correctedWord ];
  13936. }
  13937. }
  13938. }
  13939. var self = this;
  13940. self.alphabet = "abcdefghijklmnopqrstuvwxyz";
  13941. /*
  13942. if (!self.alphabet) {
  13943. // Use the alphabet as implicitly defined by the words in the dictionary.
  13944. var alphaHash = {};
  13945. for (var i in self.dictionaryTable) {
  13946. for (var j = 0, _len = i.length; j < _len; j++) {
  13947. alphaHash[i[j]] = true;
  13948. }
  13949. }
  13950. for (var i in alphaHash) {
  13951. self.alphabet += i;
  13952. }
  13953. var alphaArray = self.alphabet.split("");
  13954. alphaArray.sort();
  13955. self.alphabet = alphaArray.join("");
  13956. }
  13957. */
  13958. function edits1(words) {
  13959. var rv = [];
  13960. var ii, i, j, _iilen, _len, _jlen;
  13961. for (ii = 0, _iilen = words.length; ii < _iilen; ii++) {
  13962. var word = words[ii];
  13963. for (i = 0, _len = word.length + 1; i < _len; i++) {
  13964. var s = [ word.substring(0, i), word.substring(i) ];
  13965. if (s[1]) {
  13966. rv.push(s[0] + s[1].substring(1));
  13967. }
  13968. // Eliminate transpositions of identical letters
  13969. if (s[1].length > 1 && s[1][1] !== s[1][0]) {
  13970. rv.push(s[0] + s[1][1] + s[1][0] + s[1].substring(2));
  13971. }
  13972. if (s[1]) {
  13973. for (j = 0, _jlen = self.alphabet.length; j < _jlen; j++) {
  13974. // Eliminate replacement of a letter by itself
  13975. if (self.alphabet[j] != s[1].substring(0,1)){
  13976. rv.push(s[0] + self.alphabet[j] + s[1].substring(1));
  13977. }
  13978. }
  13979. }
  13980. if (s[1]) {
  13981. for (j = 0, _jlen = self.alphabet.length; j < _jlen; j++) {
  13982. rv.push(s[0] + self.alphabet[j] + s[1]);
  13983. }
  13984. }
  13985. }
  13986. }
  13987. return rv;
  13988. }
  13989. function known(words) {
  13990. var rv = [];
  13991. for (var i = 0, _len = words.length; i < _len; i++) {
  13992. if (self.check(words[i])) {
  13993. rv.push(words[i]);
  13994. }
  13995. }
  13996. return rv;
  13997. }
  13998. function correct(word) {
  13999. // Get the edit-distance-1 and edit-distance-2 forms of this word.
  14000. var ed1 = edits1([word]);
  14001. var ed2 = edits1(ed1);
  14002. var corrections = known(ed1.concat(ed2));
  14003. var i, _len;
  14004. // Sort the edits based on how many different ways they were created.
  14005. var weighted_corrections = {};
  14006. for (i = 0, _len = corrections.length; i < _len; i++) {
  14007. if (!(corrections[i] in weighted_corrections)) {
  14008. weighted_corrections[corrections[i]] = 1;
  14009. }
  14010. else {
  14011. weighted_corrections[corrections[i]] += 1;
  14012. }
  14013. }
  14014. var sorted_corrections = [];
  14015. for (i in weighted_corrections) {
  14016. if (weighted_corrections.hasOwnProperty(i)) {
  14017. sorted_corrections.push([ i, weighted_corrections[i] ]);
  14018. }
  14019. }
  14020. function sorter(a, b) {
  14021. if (a[1] < b[1]) {
  14022. return -1;
  14023. }
  14024. return 1;
  14025. }
  14026. sorted_corrections.sort(sorter).reverse();
  14027. var rv = [];
  14028. var capitalization_scheme = "lowercase";
  14029. if (word.toUpperCase() === word) {
  14030. capitalization_scheme = "uppercase";
  14031. }
  14032. else if (word.substr(0, 1).toUpperCase() + word.substr(1).toLowerCase() === word) {
  14033. capitalization_scheme = "capitalized";
  14034. }
  14035. for (i = 0, _len = Math.min(limit, sorted_corrections.length); i < _len; i++) {
  14036. if ("uppercase" === capitalization_scheme) {
  14037. sorted_corrections[i][0] = sorted_corrections[i][0].toUpperCase();
  14038. }
  14039. else if ("capitalized" === capitalization_scheme) {
  14040. sorted_corrections[i][0] = sorted_corrections[i][0].substr(0, 1).toUpperCase() + sorted_corrections[i][0].substr(1);
  14041. }
  14042. if (!self.hasFlag(sorted_corrections[i][0], "NOSUGGEST")) {
  14043. rv.push(sorted_corrections[i][0]);
  14044. }
  14045. }
  14046. return rv;
  14047. }
  14048. this.memoized[word] = {
  14049. 'suggestions': correct(word),
  14050. 'limit': limit
  14051. };
  14052. return this.memoized[word]['suggestions'];
  14053. }
  14054. };
  14055. })();
  14056. // Support for use as a node.js module.
  14057. if (typeof module !== 'undefined') {
  14058. module.exports = Typo;
  14059. }
  14060. }).call(this,require("buffer").Buffer,"/node_modules/typo-js")
  14061. },{"buffer":3,"fs":2}],18:[function(require,module,exports){
  14062. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  14063. // Distributed under an MIT license: http://codemirror.net/LICENSE
  14064. var CodeMirror = require("codemirror");
  14065. CodeMirror.commands.tabAndIndentMarkdownList = function (cm) {
  14066. var ranges = cm.listSelections();
  14067. var pos = ranges[0].head;
  14068. var eolState = cm.getStateAfter(pos.line);
  14069. var inList = eolState.list !== false;
  14070. if (inList) {
  14071. cm.execCommand("indentMore");
  14072. return;
  14073. }
  14074. if (cm.options.indentWithTabs) {
  14075. cm.execCommand("insertTab");
  14076. }
  14077. else {
  14078. var spaces = Array(cm.options.tabSize + 1).join(" ");
  14079. cm.replaceSelection(spaces);
  14080. }
  14081. };
  14082. CodeMirror.commands.shiftTabAndUnindentMarkdownList = function (cm) {
  14083. var ranges = cm.listSelections();
  14084. var pos = ranges[0].head;
  14085. var eolState = cm.getStateAfter(pos.line);
  14086. var inList = eolState.list !== false;
  14087. if (inList) {
  14088. cm.execCommand("indentLess");
  14089. return;
  14090. }
  14091. if (cm.options.indentWithTabs) {
  14092. cm.execCommand("insertTab");
  14093. }
  14094. else {
  14095. var spaces = Array(cm.options.tabSize + 1).join(" ");
  14096. cm.replaceSelection(spaces);
  14097. }
  14098. };
  14099. },{"codemirror":10}],19:[function(require,module,exports){
  14100. /*global require,module*/
  14101. "use strict";
  14102. var CodeMirror = require("codemirror");
  14103. require("codemirror/addon/edit/continuelist.js");
  14104. require("./codemirror/tablist");
  14105. require("codemirror/addon/display/fullscreen.js");
  14106. require("codemirror/mode/markdown/markdown.js");
  14107. require("codemirror/addon/mode/overlay.js");
  14108. require("codemirror/addon/display/placeholder.js");
  14109. require("codemirror/addon/selection/mark-selection.js");
  14110. require("codemirror/mode/gfm/gfm.js");
  14111. require("codemirror/mode/xml/xml.js");
  14112. var CodeMirrorSpellChecker = require("codemirror-spell-checker");
  14113. var marked = require("marked");
  14114. // Some variables
  14115. var isMac = /Mac/.test(navigator.platform);
  14116. // Mapping of actions that can be bound to keyboard shortcuts or toolbar buttons
  14117. var bindings = {
  14118. "toggleBold": toggleBold,
  14119. "toggleItalic": toggleItalic,
  14120. "drawLink": drawLink,
  14121. "toggleHeadingSmaller": toggleHeadingSmaller,
  14122. "toggleHeadingBigger": toggleHeadingBigger,
  14123. "drawImage": drawImage,
  14124. "toggleBlockquote": toggleBlockquote,
  14125. "toggleOrderedList": toggleOrderedList,
  14126. "toggleUnorderedList": toggleUnorderedList,
  14127. "toggleCodeBlock": toggleCodeBlock,
  14128. "togglePreview": togglePreview,
  14129. "toggleStrikethrough": toggleStrikethrough,
  14130. "toggleHeading1": toggleHeading1,
  14131. "toggleHeading2": toggleHeading2,
  14132. "toggleHeading3": toggleHeading3,
  14133. "cleanBlock": cleanBlock,
  14134. "drawTable": drawTable,
  14135. "drawHorizontalRule": drawHorizontalRule,
  14136. "undo": undo,
  14137. "redo": redo,
  14138. "toggleSideBySide": toggleSideBySide,
  14139. "toggleFullScreen": toggleFullScreen
  14140. };
  14141. var shortcuts = {
  14142. "toggleBold": "Cmd-B",
  14143. "toggleItalic": "Cmd-I",
  14144. "drawLink": "Cmd-K",
  14145. "toggleHeadingSmaller": "Cmd-H",
  14146. "toggleHeadingBigger": "Shift-Cmd-H",
  14147. "cleanBlock": "Cmd-E",
  14148. "drawImage": "Cmd-Alt-I",
  14149. "toggleBlockquote": "Cmd-'",
  14150. "toggleOrderedList": "Cmd-Alt-L",
  14151. "toggleUnorderedList": "Cmd-L",
  14152. "toggleCodeBlock": "Cmd-Alt-C",
  14153. "togglePreview": "Cmd-P",
  14154. "toggleSideBySide": "F9",
  14155. "toggleFullScreen": "F11"
  14156. };
  14157. var getBindingName = function(f) {
  14158. for(var key in bindings) {
  14159. if(bindings[key] === f) {
  14160. return key;
  14161. }
  14162. }
  14163. return null;
  14164. };
  14165. var isMobile = function() {
  14166. var check = false;
  14167. (function(a) {
  14168. 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;
  14169. })(navigator.userAgent || navigator.vendor || window.opera);
  14170. return check;
  14171. };
  14172. /**
  14173. * Fix shortcut. Mac use Command, others use Ctrl.
  14174. */
  14175. function fixShortcut(name) {
  14176. if(isMac) {
  14177. name = name.replace("Ctrl", "Cmd");
  14178. } else {
  14179. name = name.replace("Cmd", "Ctrl");
  14180. }
  14181. return name;
  14182. }
  14183. /**
  14184. * Create icon element for toolbar.
  14185. */
  14186. function createIcon(options, enableTooltips, shortcuts) {
  14187. options = options || {};
  14188. var el = document.createElement("a");
  14189. enableTooltips = (enableTooltips == undefined) ? true : enableTooltips;
  14190. if(options.title && enableTooltips) {
  14191. el.title = createTootlip(options.title, options.action, shortcuts);
  14192. if(isMac) {
  14193. el.title = el.title.replace("Ctrl", "⌘");
  14194. el.title = el.title.replace("Alt", "⌥");
  14195. }
  14196. }
  14197. el.tabIndex = -1;
  14198. el.className = options.className;
  14199. return el;
  14200. }
  14201. function createSep() {
  14202. var el = document.createElement("i");
  14203. el.className = "separator";
  14204. el.innerHTML = "|";
  14205. return el;
  14206. }
  14207. function createTootlip(title, action, shortcuts) {
  14208. var actionName;
  14209. var tooltip = title;
  14210. if(action) {
  14211. actionName = getBindingName(action);
  14212. if(shortcuts[actionName]) {
  14213. tooltip += " (" + fixShortcut(shortcuts[actionName]) + ")";
  14214. }
  14215. }
  14216. return tooltip;
  14217. }
  14218. /**
  14219. * The state of CodeMirror at the given position.
  14220. */
  14221. function getState(cm, pos) {
  14222. pos = pos || cm.getCursor("start");
  14223. var stat = cm.getTokenAt(pos);
  14224. if(!stat.type) return {};
  14225. var types = stat.type.split(" ");
  14226. var ret = {},
  14227. data, text;
  14228. for(var i = 0; i < types.length; i++) {
  14229. data = types[i];
  14230. if(data === "strong") {
  14231. ret.bold = true;
  14232. } else if(data === "variable-2") {
  14233. text = cm.getLine(pos.line);
  14234. if(/^\s*\d+\.\s/.test(text)) {
  14235. ret["ordered-list"] = true;
  14236. } else {
  14237. ret["unordered-list"] = true;
  14238. }
  14239. } else if(data === "atom") {
  14240. ret.quote = true;
  14241. } else if(data === "em") {
  14242. ret.italic = true;
  14243. } else if(data === "quote") {
  14244. ret.quote = true;
  14245. } else if(data === "strikethrough") {
  14246. ret.strikethrough = true;
  14247. } else if(data === "comment") {
  14248. ret.code = true;
  14249. } else if(data === "link") {
  14250. ret.link = true;
  14251. } else if(data === "tag") {
  14252. ret.image = true;
  14253. } else if(data.match(/^header(\-[1-6])?$/)) {
  14254. ret[data.replace("header", "heading")] = true;
  14255. }
  14256. }
  14257. return ret;
  14258. }
  14259. // Saved overflow setting
  14260. var saved_overflow = "";
  14261. /**
  14262. * Toggle full screen of the editor.
  14263. */
  14264. function toggleFullScreen(editor) {
  14265. // Set fullscreen
  14266. var cm = editor.codemirror;
  14267. cm.setOption("fullScreen", !cm.getOption("fullScreen"));
  14268. // Prevent scrolling on body during fullscreen active
  14269. if(cm.getOption("fullScreen")) {
  14270. saved_overflow = document.body.style.overflow;
  14271. document.body.style.overflow = "hidden";
  14272. } else {
  14273. document.body.style.overflow = saved_overflow;
  14274. }
  14275. // Update toolbar class
  14276. var wrap = cm.getWrapperElement();
  14277. if(!/fullscreen/.test(wrap.previousSibling.className)) {
  14278. wrap.previousSibling.className += " fullscreen";
  14279. } else {
  14280. wrap.previousSibling.className = wrap.previousSibling.className.replace(/\s*fullscreen\b/, "");
  14281. }
  14282. // Update toolbar button
  14283. var toolbarButton = editor.toolbarElements.fullscreen;
  14284. if(!/active/.test(toolbarButton.className)) {
  14285. toolbarButton.className += " active";
  14286. } else {
  14287. toolbarButton.className = toolbarButton.className.replace(/\s*active\s*/g, "");
  14288. }
  14289. // Hide side by side if needed
  14290. var sidebyside = cm.getWrapperElement().nextSibling;
  14291. if(/editor-preview-active-side/.test(sidebyside.className))
  14292. toggleSideBySide(editor);
  14293. }
  14294. /**
  14295. * Action for toggling bold.
  14296. */
  14297. function toggleBold(editor) {
  14298. _toggleBlock(editor, "bold", editor.options.blockStyles.bold);
  14299. }
  14300. /**
  14301. * Action for toggling italic.
  14302. */
  14303. function toggleItalic(editor) {
  14304. _toggleBlock(editor, "italic", editor.options.blockStyles.italic);
  14305. }
  14306. /**
  14307. * Action for toggling strikethrough.
  14308. */
  14309. function toggleStrikethrough(editor) {
  14310. _toggleBlock(editor, "strikethrough", "~~");
  14311. }
  14312. /**
  14313. * Action for toggling code block.
  14314. */
  14315. function toggleCodeBlock(editor) {
  14316. var fenceCharsToInsert = editor.options.blockStyles.code;
  14317. function fencing_line(line) {
  14318. /* return true, if this is a ``` or ~~~ line */
  14319. if(typeof line !== "object") {
  14320. throw "fencing_line() takes a 'line' object (not a line number, or line text). Got: " + typeof line + ": " + line;
  14321. }
  14322. return line.styles && line.styles[2] && line.styles[2].indexOf("formatting-code-block") !== -1;
  14323. }
  14324. function token_state(token) {
  14325. // base goes an extra level deep when mode backdrops are used, e.g. spellchecker on
  14326. return token.state.base.base || token.state.base;
  14327. }
  14328. function code_type(cm, line_num, line, firstTok, lastTok) {
  14329. /*
  14330. * Return "single", "indented", "fenced" or false
  14331. *
  14332. * cm and line_num are required. Others are optional for efficiency
  14333. * To check in the middle of a line, pass in firstTok yourself.
  14334. */
  14335. line = line || cm.getLineHandle(line_num);
  14336. firstTok = firstTok || cm.getTokenAt({
  14337. line: line_num,
  14338. ch: 1
  14339. });
  14340. lastTok = lastTok || (!!line.text && cm.getTokenAt({
  14341. line: line_num,
  14342. ch: line.text.length - 1
  14343. }));
  14344. var types = firstTok.type ? firstTok.type.split(" ") : [];
  14345. if(lastTok && token_state(lastTok).indentedCode) {
  14346. // have to check last char, since first chars of first line aren"t marked as indented
  14347. return "indented";
  14348. } else if(types.indexOf("comment") === -1) {
  14349. // has to be after "indented" check, since first chars of first indented line aren"t marked as such
  14350. return false;
  14351. } else if(token_state(firstTok).fencedChars || token_state(lastTok).fencedChars || fencing_line(line)) {
  14352. return "fenced";
  14353. } else {
  14354. return "single";
  14355. }
  14356. }
  14357. function insertFencingAtSelection(cm, cur_start, cur_end, fenceCharsToInsert) {
  14358. var start_line_sel = cur_start.line + 1,
  14359. end_line_sel = cur_end.line + 1,
  14360. sel_multi = cur_start.line !== cur_end.line,
  14361. repl_start = fenceCharsToInsert + "\n",
  14362. repl_end = "\n" + fenceCharsToInsert;
  14363. if(sel_multi) {
  14364. end_line_sel++;
  14365. }
  14366. // handle last char including \n or not
  14367. if(sel_multi && cur_end.ch === 0) {
  14368. repl_end = fenceCharsToInsert + "\n";
  14369. end_line_sel--;
  14370. }
  14371. _replaceSelection(cm, false, [repl_start, repl_end]);
  14372. cm.setSelection({
  14373. line: start_line_sel,
  14374. ch: 0
  14375. }, {
  14376. line: end_line_sel,
  14377. ch: 0
  14378. });
  14379. }
  14380. var cm = editor.codemirror,
  14381. cur_start = cm.getCursor("start"),
  14382. cur_end = cm.getCursor("end"),
  14383. tok = cm.getTokenAt({
  14384. line: cur_start.line,
  14385. ch: cur_start.ch || 1
  14386. }), // avoid ch 0 which is a cursor pos but not token
  14387. line = cm.getLineHandle(cur_start.line),
  14388. is_code = code_type(cm, cur_start.line, line, tok);
  14389. var block_start, block_end, lineCount;
  14390. if(is_code === "single") {
  14391. // similar to some SimpleMDE _toggleBlock logic
  14392. var start = line.text.slice(0, cur_start.ch).replace("`", ""),
  14393. end = line.text.slice(cur_start.ch).replace("`", "");
  14394. cm.replaceRange(start + end, {
  14395. line: cur_start.line,
  14396. ch: 0
  14397. }, {
  14398. line: cur_start.line,
  14399. ch: 99999999999999
  14400. });
  14401. cur_start.ch--;
  14402. if(cur_start !== cur_end) {
  14403. cur_end.ch--;
  14404. }
  14405. cm.setSelection(cur_start, cur_end);
  14406. cm.focus();
  14407. } else if(is_code === "fenced") {
  14408. if(cur_start.line !== cur_end.line || cur_start.ch !== cur_end.ch) {
  14409. // use selection
  14410. // find the fenced line so we know what type it is (tilde, backticks, number of them)
  14411. for(block_start = cur_start.line; block_start >= 0; block_start--) {
  14412. line = cm.getLineHandle(block_start);
  14413. if(fencing_line(line)) {
  14414. break;
  14415. }
  14416. }
  14417. var fencedTok = cm.getTokenAt({
  14418. line: block_start,
  14419. ch: 1
  14420. });
  14421. var fence_chars = token_state(fencedTok).fencedChars;
  14422. var start_text, start_line;
  14423. var end_text, end_line;
  14424. // check for selection going up against fenced lines, in which case we don't want to add more fencing
  14425. if(fencing_line(cm.getLineHandle(cur_start.line))) {
  14426. start_text = "";
  14427. start_line = cur_start.line;
  14428. } else if(fencing_line(cm.getLineHandle(cur_start.line - 1))) {
  14429. start_text = "";
  14430. start_line = cur_start.line - 1;
  14431. } else {
  14432. start_text = fence_chars + "\n";
  14433. start_line = cur_start.line;
  14434. }
  14435. if(fencing_line(cm.getLineHandle(cur_end.line))) {
  14436. end_text = "";
  14437. end_line = cur_end.line;
  14438. if(cur_end.ch === 0) {
  14439. end_line += 1;
  14440. }
  14441. } else if(cur_end.ch !== 0 && fencing_line(cm.getLineHandle(cur_end.line + 1))) {
  14442. end_text = "";
  14443. end_line = cur_end.line + 1;
  14444. } else {
  14445. end_text = fence_chars + "\n";
  14446. end_line = cur_end.line + 1;
  14447. }
  14448. if(cur_end.ch === 0) {
  14449. // full last line selected, putting cursor at beginning of next
  14450. end_line -= 1;
  14451. }
  14452. cm.operation(function() {
  14453. // end line first, so that line numbers don't change
  14454. cm.replaceRange(end_text, {
  14455. line: end_line,
  14456. ch: 0
  14457. }, {
  14458. line: end_line + (end_text ? 0 : 1),
  14459. ch: 0
  14460. });
  14461. cm.replaceRange(start_text, {
  14462. line: start_line,
  14463. ch: 0
  14464. }, {
  14465. line: start_line + (start_text ? 0 : 1),
  14466. ch: 0
  14467. });
  14468. });
  14469. cm.setSelection({
  14470. line: start_line + (start_text ? 1 : 0),
  14471. ch: 0
  14472. }, {
  14473. line: end_line + (start_text ? 1 : -1),
  14474. ch: 0
  14475. });
  14476. cm.focus();
  14477. } else {
  14478. // no selection, search for ends of this fenced block
  14479. var search_from = cur_start.line;
  14480. if(fencing_line(cm.getLineHandle(cur_start.line))) { // gets a little tricky if cursor is right on a fenced line
  14481. if(code_type(cm, cur_start.line + 1) === "fenced") {
  14482. block_start = cur_start.line;
  14483. search_from = cur_start.line + 1; // for searching for "end"
  14484. } else {
  14485. block_end = cur_start.line;
  14486. search_from = cur_start.line - 1; // for searching for "start"
  14487. }
  14488. }
  14489. if(block_start === undefined) {
  14490. for(block_start = search_from; block_start >= 0; block_start--) {
  14491. line = cm.getLineHandle(block_start);
  14492. if(fencing_line(line)) {
  14493. break;
  14494. }
  14495. }
  14496. }
  14497. if(block_end === undefined) {
  14498. lineCount = cm.lineCount();
  14499. for(block_end = search_from; block_end < lineCount; block_end++) {
  14500. line = cm.getLineHandle(block_end);
  14501. if(fencing_line(line)) {
  14502. break;
  14503. }
  14504. }
  14505. }
  14506. cm.operation(function() {
  14507. cm.replaceRange("", {
  14508. line: block_start,
  14509. ch: 0
  14510. }, {
  14511. line: block_start + 1,
  14512. ch: 0
  14513. });
  14514. cm.replaceRange("", {
  14515. line: block_end - 1,
  14516. ch: 0
  14517. }, {
  14518. line: block_end,
  14519. ch: 0
  14520. });
  14521. });
  14522. cm.focus();
  14523. }
  14524. } else if(is_code === "indented") {
  14525. if(cur_start.line !== cur_end.line || cur_start.ch !== cur_end.ch) {
  14526. // use selection
  14527. block_start = cur_start.line;
  14528. block_end = cur_end.line;
  14529. if(cur_end.ch === 0) {
  14530. block_end--;
  14531. }
  14532. } else {
  14533. // no selection, search for ends of this indented block
  14534. for(block_start = cur_start.line; block_start >= 0; block_start--) {
  14535. line = cm.getLineHandle(block_start);
  14536. if(line.text.match(/^\s*$/)) {
  14537. // empty or all whitespace - keep going
  14538. continue;
  14539. } else {
  14540. if(code_type(cm, block_start, line) !== "indented") {
  14541. block_start += 1;
  14542. break;
  14543. }
  14544. }
  14545. }
  14546. lineCount = cm.lineCount();
  14547. for(block_end = cur_start.line; block_end < lineCount; block_end++) {
  14548. line = cm.getLineHandle(block_end);
  14549. if(line.text.match(/^\s*$/)) {
  14550. // empty or all whitespace - keep going
  14551. continue;
  14552. } else {
  14553. if(code_type(cm, block_end, line) !== "indented") {
  14554. block_end -= 1;
  14555. break;
  14556. }
  14557. }
  14558. }
  14559. }
  14560. // if we are going to un-indent based on a selected set of lines, and the next line is indented too, we need to
  14561. // insert a blank line so that the next line(s) continue to be indented code
  14562. var next_line = cm.getLineHandle(block_end + 1),
  14563. next_line_last_tok = next_line && cm.getTokenAt({
  14564. line: block_end + 1,
  14565. ch: next_line.text.length - 1
  14566. }),
  14567. next_line_indented = next_line_last_tok && token_state(next_line_last_tok).indentedCode;
  14568. if(next_line_indented) {
  14569. cm.replaceRange("\n", {
  14570. line: block_end + 1,
  14571. ch: 0
  14572. });
  14573. }
  14574. for(var i = block_start; i <= block_end; i++) {
  14575. cm.indentLine(i, "subtract"); // TODO: this doesn't get tracked in the history, so can't be undone :(
  14576. }
  14577. cm.focus();
  14578. } else {
  14579. // insert code formatting
  14580. var no_sel_and_starting_of_line = (cur_start.line === cur_end.line && cur_start.ch === cur_end.ch && cur_start.ch === 0);
  14581. var sel_multi = cur_start.line !== cur_end.line;
  14582. if(no_sel_and_starting_of_line || sel_multi) {
  14583. insertFencingAtSelection(cm, cur_start, cur_end, fenceCharsToInsert);
  14584. } else {
  14585. _replaceSelection(cm, false, ["`", "`"]);
  14586. }
  14587. }
  14588. }
  14589. /**
  14590. * Action for toggling blockquote.
  14591. */
  14592. function toggleBlockquote(editor) {
  14593. var cm = editor.codemirror;
  14594. _toggleLine(cm, "quote");
  14595. }
  14596. /**
  14597. * Action for toggling heading size: normal -> h1 -> h2 -> h3 -> h4 -> h5 -> h6 -> normal
  14598. */
  14599. function toggleHeadingSmaller(editor) {
  14600. var cm = editor.codemirror;
  14601. _toggleHeading(cm, "smaller");
  14602. }
  14603. /**
  14604. * Action for toggling heading size: normal -> h6 -> h5 -> h4 -> h3 -> h2 -> h1 -> normal
  14605. */
  14606. function toggleHeadingBigger(editor) {
  14607. var cm = editor.codemirror;
  14608. _toggleHeading(cm, "bigger");
  14609. }
  14610. /**
  14611. * Action for toggling heading size 1
  14612. */
  14613. function toggleHeading1(editor) {
  14614. var cm = editor.codemirror;
  14615. _toggleHeading(cm, undefined, 1);
  14616. }
  14617. /**
  14618. * Action for toggling heading size 2
  14619. */
  14620. function toggleHeading2(editor) {
  14621. var cm = editor.codemirror;
  14622. _toggleHeading(cm, undefined, 2);
  14623. }
  14624. /**
  14625. * Action for toggling heading size 3
  14626. */
  14627. function toggleHeading3(editor) {
  14628. var cm = editor.codemirror;
  14629. _toggleHeading(cm, undefined, 3);
  14630. }
  14631. /**
  14632. * Action for toggling ul.
  14633. */
  14634. function toggleUnorderedList(editor) {
  14635. var cm = editor.codemirror;
  14636. _toggleLine(cm, "unordered-list");
  14637. }
  14638. /**
  14639. * Action for toggling ol.
  14640. */
  14641. function toggleOrderedList(editor) {
  14642. var cm = editor.codemirror;
  14643. _toggleLine(cm, "ordered-list");
  14644. }
  14645. /**
  14646. * Action for clean block (remove headline, list, blockquote code, markers)
  14647. */
  14648. function cleanBlock(editor) {
  14649. var cm = editor.codemirror;
  14650. _cleanBlock(cm);
  14651. }
  14652. /**
  14653. * Action for drawing a link.
  14654. */
  14655. function drawLink(editor) {
  14656. var cm = editor.codemirror;
  14657. var stat = getState(cm);
  14658. var options = editor.options;
  14659. var url = "safe://";
  14660. if(options.promptURLs) {
  14661. url = prompt(options.promptTexts.link);
  14662. if(!url) {
  14663. return false;
  14664. }
  14665. }
  14666. _replaceSelection(cm, stat.link, options.insertTexts.link, url);
  14667. }
  14668. /**
  14669. * Action for drawing an img.
  14670. */
  14671. function drawImage(editor) {
  14672. var cm = editor.codemirror;
  14673. var stat = getState(cm);
  14674. var options = editor.options;
  14675. var url = "safe://";
  14676. if(options.promptURLs) {
  14677. url = prompt(options.promptTexts.image);
  14678. if(!url) {
  14679. return false;
  14680. }
  14681. }
  14682. _replaceSelection(cm, stat.image, options.insertTexts.image, url);
  14683. }
  14684. /**
  14685. * Action for drawing a table.
  14686. */
  14687. function drawTable(editor) {
  14688. var cm = editor.codemirror;
  14689. var stat = getState(cm);
  14690. var options = editor.options;
  14691. _replaceSelection(cm, stat.table, options.insertTexts.table);
  14692. }
  14693. /**
  14694. * Action for drawing a horizontal rule.
  14695. */
  14696. function drawHorizontalRule(editor) {
  14697. var cm = editor.codemirror;
  14698. var stat = getState(cm);
  14699. var options = editor.options;
  14700. _replaceSelection(cm, stat.image, options.insertTexts.horizontalRule);
  14701. }
  14702. /**
  14703. * Undo action.
  14704. */
  14705. function undo(editor) {
  14706. var cm = editor.codemirror;
  14707. cm.undo();
  14708. cm.focus();
  14709. }
  14710. /**
  14711. * Redo action.
  14712. */
  14713. function redo(editor) {
  14714. var cm = editor.codemirror;
  14715. cm.redo();
  14716. cm.focus();
  14717. }
  14718. /**
  14719. * Toggle side by side preview
  14720. */
  14721. function toggleSideBySide(editor) {
  14722. var cm = editor.codemirror;
  14723. var wrapper = cm.getWrapperElement();
  14724. var preview = wrapper.nextSibling;
  14725. var toolbarButton = editor.toolbarElements["side-by-side"];
  14726. var useSideBySideListener = false;
  14727. if(/editor-preview-active-side/.test(preview.className)) {
  14728. preview.className = preview.className.replace(
  14729. /\s*editor-preview-active-side\s*/g, ""
  14730. );
  14731. toolbarButton.className = toolbarButton.className.replace(/\s*active\s*/g, "");
  14732. wrapper.className = wrapper.className.replace(/\s*CodeMirror-sided\s*/g, " ");
  14733. } else {
  14734. // When the preview button is clicked for the first time,
  14735. // give some time for the transition from editor.css to fire and the view to slide from right to left,
  14736. // instead of just appearing.
  14737. setTimeout(function() {
  14738. if(!cm.getOption("fullScreen"))
  14739. toggleFullScreen(editor);
  14740. preview.className += " editor-preview-active-side";
  14741. }, 1);
  14742. toolbarButton.className += " active";
  14743. wrapper.className += " CodeMirror-sided";
  14744. useSideBySideListener = true;
  14745. }
  14746. // Hide normal preview if active
  14747. var previewNormal = wrapper.lastChild;
  14748. if(/editor-preview-active/.test(previewNormal.className)) {
  14749. previewNormal.className = previewNormal.className.replace(
  14750. /\s*editor-preview-active\s*/g, ""
  14751. );
  14752. var toolbar = editor.toolbarElements.preview;
  14753. var toolbar_div = wrapper.previousSibling;
  14754. toolbar.className = toolbar.className.replace(/\s*active\s*/g, "");
  14755. toolbar_div.className = toolbar_div.className.replace(/\s*disabled-for-preview*/g, "");
  14756. }
  14757. var sideBySideRenderingFunction = function() {
  14758. preview.innerHTML = editor.options.previewRender(editor.value(), preview);
  14759. };
  14760. if(!cm.sideBySideRenderingFunction) {
  14761. cm.sideBySideRenderingFunction = sideBySideRenderingFunction;
  14762. }
  14763. if(useSideBySideListener) {
  14764. preview.innerHTML = editor.options.previewRender(editor.value(), preview);
  14765. cm.on("update", cm.sideBySideRenderingFunction);
  14766. } else {
  14767. cm.off("update", cm.sideBySideRenderingFunction);
  14768. }
  14769. // Refresh to fix selection being off (#309)
  14770. cm.refresh();
  14771. }
  14772. /**
  14773. * Preview action.
  14774. */
  14775. function togglePreview(editor) {
  14776. var cm = editor.codemirror;
  14777. var wrapper = cm.getWrapperElement();
  14778. var toolbar_div = wrapper.previousSibling;
  14779. var toolbar = editor.options.toolbar ? editor.toolbarElements.preview : false;
  14780. var preview = wrapper.lastChild;
  14781. if(!preview || !/editor-preview/.test(preview.className)) {
  14782. preview = document.createElement("div");
  14783. preview.className = "editor-preview";
  14784. wrapper.appendChild(preview);
  14785. }
  14786. if(/editor-preview-active/.test(preview.className)) {
  14787. preview.className = preview.className.replace(
  14788. /\s*editor-preview-active\s*/g, ""
  14789. );
  14790. if(toolbar) {
  14791. toolbar.className = toolbar.className.replace(/\s*active\s*/g, "");
  14792. toolbar_div.className = toolbar_div.className.replace(/\s*disabled-for-preview*/g, "");
  14793. }
  14794. } else {
  14795. // When the preview button is clicked for the first time,
  14796. // give some time for the transition from editor.css to fire and the view to slide from right to left,
  14797. // instead of just appearing.
  14798. setTimeout(function() {
  14799. preview.className += " editor-preview-active";
  14800. }, 1);
  14801. if(toolbar) {
  14802. toolbar.className += " active";
  14803. toolbar_div.className += " disabled-for-preview";
  14804. }
  14805. }
  14806. preview.innerHTML = editor.options.previewRender(editor.value(), preview);
  14807. // Turn off side by side if needed
  14808. var sidebyside = cm.getWrapperElement().nextSibling;
  14809. if(/editor-preview-active-side/.test(sidebyside.className))
  14810. toggleSideBySide(editor);
  14811. }
  14812. function _replaceSelection(cm, active, startEnd, url) {
  14813. if(/editor-preview-active/.test(cm.getWrapperElement().lastChild.className))
  14814. return;
  14815. var text;
  14816. var start = startEnd[0];
  14817. var end = startEnd[1];
  14818. var startPoint = cm.getCursor("start");
  14819. var endPoint = cm.getCursor("end");
  14820. if(url) {
  14821. end = end.replace("#url#", url);
  14822. }
  14823. if(active) {
  14824. text = cm.getLine(startPoint.line);
  14825. start = text.slice(0, startPoint.ch);
  14826. end = text.slice(startPoint.ch);
  14827. cm.replaceRange(start + end, {
  14828. line: startPoint.line,
  14829. ch: 0
  14830. });
  14831. } else {
  14832. text = cm.getSelection();
  14833. cm.replaceSelection(start + text + end);
  14834. startPoint.ch += start.length;
  14835. if(startPoint !== endPoint) {
  14836. endPoint.ch += start.length;
  14837. }
  14838. }
  14839. cm.setSelection(startPoint, endPoint);
  14840. cm.focus();
  14841. }
  14842. function _toggleHeading(cm, direction, size) {
  14843. if(/editor-preview-active/.test(cm.getWrapperElement().lastChild.className))
  14844. return;
  14845. var startPoint = cm.getCursor("start");
  14846. var endPoint = cm.getCursor("end");
  14847. for(var i = startPoint.line; i <= endPoint.line; i++) {
  14848. (function(i) {
  14849. var text = cm.getLine(i);
  14850. var currHeadingLevel = text.search(/[^#]/);
  14851. if(direction !== undefined) {
  14852. if(currHeadingLevel <= 0) {
  14853. if(direction == "bigger") {
  14854. text = "###### " + text;
  14855. } else {
  14856. text = "# " + text;
  14857. }
  14858. } else if(currHeadingLevel == 6 && direction == "smaller") {
  14859. text = text.substr(7);
  14860. } else if(currHeadingLevel == 1 && direction == "bigger") {
  14861. text = text.substr(2);
  14862. } else {
  14863. if(direction == "bigger") {
  14864. text = text.substr(1);
  14865. } else {
  14866. text = "#" + text;
  14867. }
  14868. }
  14869. } else {
  14870. if(size == 1) {
  14871. if(currHeadingLevel <= 0) {
  14872. text = "# " + text;
  14873. } else if(currHeadingLevel == size) {
  14874. text = text.substr(currHeadingLevel + 1);
  14875. } else {
  14876. text = "# " + text.substr(currHeadingLevel + 1);
  14877. }
  14878. } else if(size == 2) {
  14879. if(currHeadingLevel <= 0) {
  14880. text = "## " + text;
  14881. } else if(currHeadingLevel == size) {
  14882. text = text.substr(currHeadingLevel + 1);
  14883. } else {
  14884. text = "## " + text.substr(currHeadingLevel + 1);
  14885. }
  14886. } else {
  14887. if(currHeadingLevel <= 0) {
  14888. text = "### " + text;
  14889. } else if(currHeadingLevel == size) {
  14890. text = text.substr(currHeadingLevel + 1);
  14891. } else {
  14892. text = "### " + text.substr(currHeadingLevel + 1);
  14893. }
  14894. }
  14895. }
  14896. cm.replaceRange(text, {
  14897. line: i,
  14898. ch: 0
  14899. }, {
  14900. line: i,
  14901. ch: 99999999999999
  14902. });
  14903. })(i);
  14904. }
  14905. cm.focus();
  14906. }
  14907. function _toggleLine(cm, name) {
  14908. if(/editor-preview-active/.test(cm.getWrapperElement().lastChild.className))
  14909. return;
  14910. var stat = getState(cm);
  14911. var startPoint = cm.getCursor("start");
  14912. var endPoint = cm.getCursor("end");
  14913. var repl = {
  14914. "quote": /^(\s*)\>\s+/,
  14915. "unordered-list": /^(\s*)(\*|\-|\+)\s+/,
  14916. "ordered-list": /^(\s*)\d+\.\s+/
  14917. };
  14918. var map = {
  14919. "quote": "> ",
  14920. "unordered-list": "* ",
  14921. "ordered-list": "1. "
  14922. };
  14923. for(var i = startPoint.line; i <= endPoint.line; i++) {
  14924. (function(i) {
  14925. var text = cm.getLine(i);
  14926. if(stat[name]) {
  14927. text = text.replace(repl[name], "$1");
  14928. } else {
  14929. text = map[name] + text;
  14930. }
  14931. cm.replaceRange(text, {
  14932. line: i,
  14933. ch: 0
  14934. }, {
  14935. line: i,
  14936. ch: 99999999999999
  14937. });
  14938. })(i);
  14939. }
  14940. cm.focus();
  14941. }
  14942. function _toggleBlock(editor, type, start_chars, end_chars) {
  14943. if(/editor-preview-active/.test(editor.codemirror.getWrapperElement().lastChild.className))
  14944. return;
  14945. end_chars = (typeof end_chars === "undefined") ? start_chars : end_chars;
  14946. var cm = editor.codemirror;
  14947. var stat = getState(cm);
  14948. var text;
  14949. var start = start_chars;
  14950. var end = end_chars;
  14951. var startPoint = cm.getCursor("start");
  14952. var endPoint = cm.getCursor("end");
  14953. if(stat[type]) {
  14954. text = cm.getLine(startPoint.line);
  14955. start = text.slice(0, startPoint.ch);
  14956. end = text.slice(startPoint.ch);
  14957. if(type == "bold") {
  14958. start = start.replace(/(\*\*|__)(?![\s\S]*(\*\*|__))/, "");
  14959. end = end.replace(/(\*\*|__)/, "");
  14960. } else if(type == "italic") {
  14961. start = start.replace(/(\*|_)(?![\s\S]*(\*|_))/, "");
  14962. end = end.replace(/(\*|_)/, "");
  14963. } else if(type == "strikethrough") {
  14964. start = start.replace(/(\*\*|~~)(?![\s\S]*(\*\*|~~))/, "");
  14965. end = end.replace(/(\*\*|~~)/, "");
  14966. }
  14967. cm.replaceRange(start + end, {
  14968. line: startPoint.line,
  14969. ch: 0
  14970. }, {
  14971. line: startPoint.line,
  14972. ch: 99999999999999
  14973. });
  14974. if(type == "bold" || type == "strikethrough") {
  14975. startPoint.ch -= 2;
  14976. if(startPoint !== endPoint) {
  14977. endPoint.ch -= 2;
  14978. }
  14979. } else if(type == "italic") {
  14980. startPoint.ch -= 1;
  14981. if(startPoint !== endPoint) {
  14982. endPoint.ch -= 1;
  14983. }
  14984. }
  14985. } else {
  14986. text = cm.getSelection();
  14987. if(type == "bold") {
  14988. text = text.split("**").join("");
  14989. text = text.split("__").join("");
  14990. } else if(type == "italic") {
  14991. text = text.split("*").join("");
  14992. text = text.split("_").join("");
  14993. } else if(type == "strikethrough") {
  14994. text = text.split("~~").join("");
  14995. }
  14996. cm.replaceSelection(start + text + end);
  14997. startPoint.ch += start_chars.length;
  14998. endPoint.ch = startPoint.ch + text.length;
  14999. }
  15000. cm.setSelection(startPoint, endPoint);
  15001. cm.focus();
  15002. }
  15003. function _cleanBlock(cm) {
  15004. if(/editor-preview-active/.test(cm.getWrapperElement().lastChild.className))
  15005. return;
  15006. var startPoint = cm.getCursor("start");
  15007. var endPoint = cm.getCursor("end");
  15008. var text;
  15009. for(var line = startPoint.line; line <= endPoint.line; line++) {
  15010. text = cm.getLine(line);
  15011. text = text.replace(/^[ ]*([# ]+|\*|\-|[> ]+|[0-9]+(.|\)))[ ]*/, "");
  15012. cm.replaceRange(text, {
  15013. line: line,
  15014. ch: 0
  15015. }, {
  15016. line: line,
  15017. ch: 99999999999999
  15018. });
  15019. }
  15020. }
  15021. // Merge the properties of one object into another.
  15022. function _mergeProperties(target, source) {
  15023. for(var property in source) {
  15024. if(source.hasOwnProperty(property)) {
  15025. if(source[property] instanceof Array) {
  15026. target[property] = source[property].concat(target[property] instanceof Array ? target[property] : []);
  15027. } else if(
  15028. source[property] !== null &&
  15029. typeof source[property] === "object" &&
  15030. source[property].constructor === Object
  15031. ) {
  15032. target[property] = _mergeProperties(target[property] || {}, source[property]);
  15033. } else {
  15034. target[property] = source[property];
  15035. }
  15036. }
  15037. }
  15038. return target;
  15039. }
  15040. // Merge an arbitrary number of objects into one.
  15041. function extend(target) {
  15042. for(var i = 1; i < arguments.length; i++) {
  15043. target = _mergeProperties(target, arguments[i]);
  15044. }
  15045. return target;
  15046. }
  15047. /* The right word count in respect for CJK. */
  15048. function wordCount(data) {
  15049. var pattern = /[a-zA-Z0-9_\u0392-\u03c9\u0410-\u04F9]+|[\u4E00-\u9FFF\u3400-\u4dbf\uf900-\ufaff\u3040-\u309f\uac00-\ud7af]+/g;
  15050. var m = data.match(pattern);
  15051. var count = 0;
  15052. if(m === null) return count;
  15053. for(var i = 0; i < m.length; i++) {
  15054. if(m[i].charCodeAt(0) >= 0x4E00) {
  15055. count += m[i].length;
  15056. } else {
  15057. count += 1;
  15058. }
  15059. }
  15060. return count;
  15061. }
  15062. var toolbarBuiltInButtons = {
  15063. "bold": {
  15064. name: "bold",
  15065. action: toggleBold,
  15066. className: "fa fa-bold",
  15067. title: "Bold",
  15068. default: true
  15069. },
  15070. "italic": {
  15071. name: "italic",
  15072. action: toggleItalic,
  15073. className: "fa fa-italic",
  15074. title: "Italic",
  15075. default: true
  15076. },
  15077. "strikethrough": {
  15078. name: "strikethrough",
  15079. action: toggleStrikethrough,
  15080. className: "fa fa-strikethrough",
  15081. title: "Strikethrough"
  15082. },
  15083. "heading": {
  15084. name: "heading",
  15085. action: toggleHeadingSmaller,
  15086. className: "fa fa-header",
  15087. title: "Heading",
  15088. default: true
  15089. },
  15090. "heading-smaller": {
  15091. name: "heading-smaller",
  15092. action: toggleHeadingSmaller,
  15093. className: "fa fa-header fa-header-x fa-header-smaller",
  15094. title: "Smaller Heading"
  15095. },
  15096. "heading-bigger": {
  15097. name: "heading-bigger",
  15098. action: toggleHeadingBigger,
  15099. className: "fa fa-header fa-header-x fa-header-bigger",
  15100. title: "Bigger Heading"
  15101. },
  15102. "heading-1": {
  15103. name: "heading-1",
  15104. action: toggleHeading1,
  15105. className: "fa fa-header fa-header-x fa-header-1",
  15106. title: "Big Heading"
  15107. },
  15108. "heading-2": {
  15109. name: "heading-2",
  15110. action: toggleHeading2,
  15111. className: "fa fa-header fa-header-x fa-header-2",
  15112. title: "Medium Heading"
  15113. },
  15114. "heading-3": {
  15115. name: "heading-3",
  15116. action: toggleHeading3,
  15117. className: "fa fa-header fa-header-x fa-header-3",
  15118. title: "Small Heading"
  15119. },
  15120. "separator-1": {
  15121. name: "separator-1"
  15122. },
  15123. "code": {
  15124. name: "code",
  15125. action: toggleCodeBlock,
  15126. className: "fa fa-code",
  15127. title: "Code"
  15128. },
  15129. "quote": {
  15130. name: "quote",
  15131. action: toggleBlockquote,
  15132. className: "fa fa-quote-left",
  15133. title: "Quote",
  15134. default: true
  15135. },
  15136. "unordered-list": {
  15137. name: "unordered-list",
  15138. action: toggleUnorderedList,
  15139. className: "fa fa-list-ul",
  15140. title: "Generic List",
  15141. default: true
  15142. },
  15143. "ordered-list": {
  15144. name: "ordered-list",
  15145. action: toggleOrderedList,
  15146. className: "fa fa-list-ol",
  15147. title: "Numbered List",
  15148. default: true
  15149. },
  15150. "clean-block": {
  15151. name: "clean-block",
  15152. action: cleanBlock,
  15153. className: "fa fa-eraser fa-clean-block",
  15154. title: "Clean block"
  15155. },
  15156. "separator-2": {
  15157. name: "separator-2"
  15158. },
  15159. "link": {
  15160. name: "link",
  15161. action: drawLink,
  15162. className: "fa fa-link",
  15163. title: "Create Link",
  15164. default: true
  15165. },
  15166. "image": {
  15167. name: "image",
  15168. action: drawImage,
  15169. className: "fa fa-picture-o",
  15170. title: "Insert Image",
  15171. default: true
  15172. },
  15173. "table": {
  15174. name: "table",
  15175. action: drawTable,
  15176. className: "fa fa-table",
  15177. title: "Insert Table"
  15178. },
  15179. "horizontal-rule": {
  15180. name: "horizontal-rule",
  15181. action: drawHorizontalRule,
  15182. className: "fa fa-minus",
  15183. title: "Insert Horizontal Line"
  15184. },
  15185. "separator-3": {
  15186. name: "separator-3"
  15187. },
  15188. "preview": {
  15189. name: "preview",
  15190. action: togglePreview,
  15191. className: "fa fa-eye no-disable",
  15192. title: "Toggle Preview",
  15193. default: true
  15194. },
  15195. "side-by-side": {
  15196. name: "side-by-side",
  15197. action: toggleSideBySide,
  15198. className: "fa fa-columns no-disable no-mobile",
  15199. title: "Toggle Side by Side",
  15200. default: true
  15201. },
  15202. "fullscreen": {
  15203. name: "fullscreen",
  15204. action: toggleFullScreen,
  15205. className: "fa fa-arrows-alt no-disable no-mobile",
  15206. title: "Toggle Fullscreen",
  15207. default: true
  15208. },
  15209. "separator-4": {
  15210. name: "separator-4"
  15211. },
  15212. "guide": {
  15213. name: "guide",
  15214. action: "safe://markdown-guide", // maybe one day
  15215. className: "fa fa-question-circle",
  15216. title: "Markdown Guide",
  15217. default: false // disable this for now
  15218. },
  15219. "separator-5": {
  15220. name: "separator-5"
  15221. },
  15222. "undo": {
  15223. name: "undo",
  15224. action: undo,
  15225. className: "fa fa-undo no-disable",
  15226. title: "Undo"
  15227. },
  15228. "redo": {
  15229. name: "redo",
  15230. action: redo,
  15231. className: "fa fa-repeat no-disable",
  15232. title: "Redo"
  15233. }
  15234. };
  15235. var insertTexts = {
  15236. link: ["[", "](#url#)"],
  15237. image: ["![", "](#url#)"],
  15238. table: ["", "\n\n| Column 1 | Column 2 | Column 3 |\n| -------- | -------- | -------- |\n| Text | Text | Text |\n\n"],
  15239. horizontalRule: ["", "\n\n-----\n\n"]
  15240. };
  15241. var promptTexts = {
  15242. link: "URL for the link:",
  15243. image: "URL of the image:"
  15244. };
  15245. var blockStyles = {
  15246. "bold": "**",
  15247. "code": "```",
  15248. "italic": "*"
  15249. };
  15250. /**
  15251. * Interface of SimpleMDE.
  15252. */
  15253. function SimpleMDE(options) {
  15254. // Handle options parameter
  15255. options = options || {};
  15256. // Used later to refer to it"s parent
  15257. options.parent = this;
  15258. // Check if Font Awesome needs to be auto downloaded
  15259. // var autoDownloadFA = true;
  15260. var autoDownloadFA = false; // lets disable this for now
  15261. if(options.autoDownloadFontAwesome === false) {
  15262. autoDownloadFA = false; //
  15263. }
  15264. if(options.autoDownloadFontAwesome !== true) {
  15265. var styleSheets = document.styleSheets;
  15266. for(var i = 0; i < styleSheets.length; i++) {
  15267. if(!styleSheets[i].href)
  15268. continue;
  15269. if(styleSheets[i].href.indexOf("//maxcdn.bootstrapcdn.com/font-awesome/") > -1) {
  15270. autoDownloadFA = false;
  15271. }
  15272. }
  15273. }
  15274. if(autoDownloadFA) {
  15275. var link = document.createElement("link");
  15276. link.rel = "stylesheet";
  15277. // link.href = "https://maxcdn.bootstrapcdn.com/font-awesome/latest/css/font-awesome.min.css"; //we really don't want to make an http request
  15278. link.href = "safe://somepath/font-awesome.min.css"; // one day maybe
  15279. document.getElementsByTagName("head")[0].appendChild(link);
  15280. }
  15281. // Find the textarea to use
  15282. if(options.element) {
  15283. this.element = options.element;
  15284. } else if(options.element === null) {
  15285. // This means that the element option was specified, but no element was found
  15286. console.log("SimpleMDE: Error. No element was found.");
  15287. return;
  15288. }
  15289. // Handle toolbar
  15290. if(options.toolbar === undefined) {
  15291. // Initialize
  15292. options.toolbar = [];
  15293. // Loop over the built in buttons, to get the preferred order
  15294. for(var key in toolbarBuiltInButtons) {
  15295. if(toolbarBuiltInButtons.hasOwnProperty(key)) {
  15296. if(key.indexOf("separator-") != -1) {
  15297. options.toolbar.push("|");
  15298. }
  15299. if(toolbarBuiltInButtons[key].default === true || (options.showIcons && options.showIcons.constructor === Array && options.showIcons.indexOf(key) != -1)) {
  15300. options.toolbar.push(key);
  15301. }
  15302. }
  15303. }
  15304. }
  15305. // Handle status bar
  15306. if(!options.hasOwnProperty("status")) {
  15307. options.status = ["autosave", "lines", "words", "cursor"];
  15308. }
  15309. // Add default preview rendering function
  15310. if(!options.previewRender) {
  15311. options.previewRender = function(plainText) {
  15312. // Note: "this" refers to the options object
  15313. return this.parent.markdown(plainText);
  15314. };
  15315. }
  15316. // Set default options for parsing config
  15317. options.parsingConfig = extend({
  15318. highlightFormatting: true // needed for toggleCodeBlock to detect types of code
  15319. }, options.parsingConfig || {});
  15320. // Merging the insertTexts, with the given options
  15321. options.insertTexts = extend({}, insertTexts, options.insertTexts || {});
  15322. // Merging the promptTexts, with the given options
  15323. options.promptTexts = promptTexts;
  15324. // Merging the blockStyles, with the given options
  15325. options.blockStyles = extend({}, blockStyles, options.blockStyles || {});
  15326. // Merging the shortcuts, with the given options
  15327. options.shortcuts = extend({}, shortcuts, options.shortcuts || {});
  15328. // Change unique_id to uniqueId for backwards compatibility
  15329. if(options.autosave != undefined && options.autosave.unique_id != undefined && options.autosave.unique_id != "")
  15330. options.autosave.uniqueId = options.autosave.unique_id;
  15331. // Update this options
  15332. this.options = options;
  15333. // Auto render
  15334. this.render();
  15335. // The codemirror component is only available after rendering
  15336. // so, the setter for the initialValue can only run after
  15337. // the element has been rendered
  15338. if(options.initialValue && (!this.options.autosave || this.options.autosave.foundSavedValue !== true)) {
  15339. this.value(options.initialValue);
  15340. }
  15341. }
  15342. /**
  15343. * Default markdown render.
  15344. */
  15345. SimpleMDE.prototype.markdown = function(text) {
  15346. if(marked) {
  15347. // Initialize
  15348. var markedOptions = {};
  15349. // Update options
  15350. if(this.options && this.options.renderingConfig && this.options.renderingConfig.singleLineBreaks === false) {
  15351. markedOptions.breaks = false;
  15352. } else {
  15353. markedOptions.breaks = true;
  15354. }
  15355. if(this.options && this.options.renderingConfig && this.options.renderingConfig.codeSyntaxHighlighting === true && window.hljs) {
  15356. markedOptions.highlight = function(code) {
  15357. return window.hljs.highlightAuto(code).value;
  15358. };
  15359. }
  15360. // Set options
  15361. marked.setOptions(markedOptions);
  15362. // Return
  15363. return marked(text);
  15364. }
  15365. };
  15366. /**
  15367. * Render editor to the given element.
  15368. */
  15369. SimpleMDE.prototype.render = function(el) {
  15370. if(!el) {
  15371. el = this.element || document.getElementsByTagName("textarea")[0];
  15372. }
  15373. if(this._rendered && this._rendered === el) {
  15374. // Already rendered.
  15375. return;
  15376. }
  15377. this.element = el;
  15378. var options = this.options;
  15379. var self = this;
  15380. var keyMaps = {};
  15381. for(var key in options.shortcuts) {
  15382. // null stands for "do not bind this command"
  15383. if(options.shortcuts[key] !== null && bindings[key] !== null) {
  15384. (function(key) {
  15385. keyMaps[fixShortcut(options.shortcuts[key])] = function() {
  15386. bindings[key](self);
  15387. };
  15388. })(key);
  15389. }
  15390. }
  15391. keyMaps["Enter"] = "newlineAndIndentContinueMarkdownList";
  15392. keyMaps["Tab"] = "tabAndIndentMarkdownList";
  15393. keyMaps["Shift-Tab"] = "shiftTabAndUnindentMarkdownList";
  15394. keyMaps["Esc"] = function(cm) {
  15395. if(cm.getOption("fullScreen")) toggleFullScreen(self);
  15396. };
  15397. document.addEventListener("keydown", function(e) {
  15398. e = e || window.event;
  15399. if(e.keyCode == 27) {
  15400. if(self.codemirror.getOption("fullScreen")) toggleFullScreen(self);
  15401. }
  15402. }, false);
  15403. var mode, backdrop;
  15404. if(options.spellChecker !== false) {
  15405. mode = "spell-checker";
  15406. backdrop = options.parsingConfig;
  15407. backdrop.name = "gfm";
  15408. backdrop.gitHubSpice = false;
  15409. CodeMirrorSpellChecker({
  15410. codeMirrorInstance: CodeMirror
  15411. });
  15412. } else {
  15413. mode = options.parsingConfig;
  15414. mode.name = "gfm";
  15415. mode.gitHubSpice = false;
  15416. }
  15417. this.codemirror = CodeMirror.fromTextArea(el, {
  15418. mode: mode,
  15419. backdrop: backdrop,
  15420. theme: "paper",
  15421. tabSize: (options.tabSize != undefined) ? options.tabSize : 2,
  15422. indentUnit: (options.tabSize != undefined) ? options.tabSize : 2,
  15423. indentWithTabs: (options.indentWithTabs === false) ? false : true,
  15424. lineNumbers: false,
  15425. autofocus: (options.autofocus === true) ? true : false,
  15426. extraKeys: keyMaps,
  15427. lineWrapping: (options.lineWrapping === false) ? false : true,
  15428. allowDropFileTypes: ["text/plain"],
  15429. placeholder: options.placeholder || el.getAttribute("placeholder") || "",
  15430. styleSelectedText: (options.styleSelectedText != undefined) ? options.styleSelectedText : true
  15431. });
  15432. if(options.forceSync === true) {
  15433. var cm = this.codemirror;
  15434. cm.on("change", function() {
  15435. cm.save();
  15436. });
  15437. }
  15438. this.gui = {};
  15439. if(options.toolbar !== false) {
  15440. this.gui.toolbar = this.createToolbar();
  15441. }
  15442. if(options.status !== false) {
  15443. this.gui.statusbar = this.createStatusbar();
  15444. }
  15445. if(options.autosave != undefined && options.autosave.enabled === true) {
  15446. this.autosave();
  15447. }
  15448. this.gui.sideBySide = this.createSideBySide();
  15449. this._rendered = this.element;
  15450. // Fixes CodeMirror bug (#344)
  15451. var temp_cm = this.codemirror;
  15452. setTimeout(function() {
  15453. temp_cm.refresh();
  15454. }.bind(temp_cm), 0);
  15455. };
  15456. // 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.
  15457. function isLocalStorageAvailable() {
  15458. if(typeof localStorage === "object") {
  15459. try {
  15460. localStorage.setItem("smde_localStorage", 1);
  15461. localStorage.removeItem("smde_localStorage");
  15462. } catch(e) {
  15463. return false;
  15464. }
  15465. } else {
  15466. return false;
  15467. }
  15468. return true;
  15469. }
  15470. SimpleMDE.prototype.autosave = function() {
  15471. if(isLocalStorageAvailable()) {
  15472. var simplemde = this;
  15473. if(this.options.autosave.uniqueId == undefined || this.options.autosave.uniqueId == "") {
  15474. console.log("SimpleMDE: You must set a uniqueId to use the autosave feature");
  15475. return;
  15476. }
  15477. if(simplemde.element.form != null && simplemde.element.form != undefined) {
  15478. simplemde.element.form.addEventListener("submit", function() {
  15479. localStorage.removeItem("smde_" + simplemde.options.autosave.uniqueId);
  15480. });
  15481. }
  15482. if(this.options.autosave.loaded !== true) {
  15483. if(typeof localStorage.getItem("smde_" + this.options.autosave.uniqueId) == "string" && localStorage.getItem("smde_" + this.options.autosave.uniqueId) != "") {
  15484. this.codemirror.setValue(localStorage.getItem("smde_" + this.options.autosave.uniqueId));
  15485. this.options.autosave.foundSavedValue = true;
  15486. }
  15487. this.options.autosave.loaded = true;
  15488. }
  15489. localStorage.setItem("smde_" + this.options.autosave.uniqueId, simplemde.value());
  15490. var el = document.getElementById("autosaved");
  15491. if(el != null && el != undefined && el != "") {
  15492. var d = new Date();
  15493. var hh = d.getHours();
  15494. var m = d.getMinutes();
  15495. var dd = "am";
  15496. var h = hh;
  15497. if(h >= 12) {
  15498. h = hh - 12;
  15499. dd = "pm";
  15500. }
  15501. if(h == 0) {
  15502. h = 12;
  15503. }
  15504. m = m < 10 ? "0" + m : m;
  15505. el.innerHTML = "Autosaved: " + h + ":" + m + " " + dd;
  15506. }
  15507. this.autosaveTimeoutId = setTimeout(function() {
  15508. simplemde.autosave();
  15509. }, this.options.autosave.delay || 10000);
  15510. } else {
  15511. console.log("SimpleMDE: localStorage not available, cannot autosave");
  15512. }
  15513. };
  15514. SimpleMDE.prototype.clearAutosavedValue = function() {
  15515. if(isLocalStorageAvailable()) {
  15516. if(this.options.autosave == undefined || this.options.autosave.uniqueId == undefined || this.options.autosave.uniqueId == "") {
  15517. console.log("SimpleMDE: You must set a uniqueId to clear the autosave value");
  15518. return;
  15519. }
  15520. localStorage.removeItem("smde_" + this.options.autosave.uniqueId);
  15521. } else {
  15522. console.log("SimpleMDE: localStorage not available, cannot autosave");
  15523. }
  15524. };
  15525. SimpleMDE.prototype.createSideBySide = function() {
  15526. var cm = this.codemirror;
  15527. var wrapper = cm.getWrapperElement();
  15528. var preview = wrapper.nextSibling;
  15529. if(!preview || !/editor-preview-side/.test(preview.className)) {
  15530. preview = document.createElement("div");
  15531. preview.className = "editor-preview-side";
  15532. wrapper.parentNode.insertBefore(preview, wrapper.nextSibling);
  15533. }
  15534. // Syncs scroll editor -> preview
  15535. var cScroll = false;
  15536. var pScroll = false;
  15537. cm.on("scroll", function(v) {
  15538. if(cScroll) {
  15539. cScroll = false;
  15540. return;
  15541. }
  15542. pScroll = true;
  15543. var height = v.getScrollInfo().height - v.getScrollInfo().clientHeight;
  15544. var ratio = parseFloat(v.getScrollInfo().top) / height;
  15545. var move = (preview.scrollHeight - preview.clientHeight) * ratio;
  15546. preview.scrollTop = move;
  15547. });
  15548. // Syncs scroll preview -> editor
  15549. preview.onscroll = function() {
  15550. if(pScroll) {
  15551. pScroll = false;
  15552. return;
  15553. }
  15554. cScroll = true;
  15555. var height = preview.scrollHeight - preview.clientHeight;
  15556. var ratio = parseFloat(preview.scrollTop) / height;
  15557. var move = (cm.getScrollInfo().height - cm.getScrollInfo().clientHeight) * ratio;
  15558. cm.scrollTo(0, move);
  15559. };
  15560. return preview;
  15561. };
  15562. SimpleMDE.prototype.createToolbar = function(items) {
  15563. items = items || this.options.toolbar;
  15564. if(!items || items.length === 0) {
  15565. return;
  15566. }
  15567. var i;
  15568. for(i = 0; i < items.length; i++) {
  15569. if(toolbarBuiltInButtons[items[i]] != undefined) {
  15570. items[i] = toolbarBuiltInButtons[items[i]];
  15571. }
  15572. }
  15573. var bar = document.createElement("div");
  15574. bar.className = "editor-toolbar";
  15575. var self = this;
  15576. var toolbarData = {};
  15577. self.toolbar = items;
  15578. for(i = 0; i < items.length; i++) {
  15579. if(items[i].name == "guide" && self.options.toolbarGuideIcon === false)
  15580. continue;
  15581. if(self.options.hideIcons && self.options.hideIcons.indexOf(items[i].name) != -1)
  15582. continue;
  15583. // Fullscreen does not work well on mobile devices (even tablets)
  15584. // In the future, hopefully this can be resolved
  15585. if((items[i].name == "fullscreen" || items[i].name == "side-by-side") && isMobile())
  15586. continue;
  15587. // Don't include trailing separators
  15588. if(items[i] === "|") {
  15589. var nonSeparatorIconsFollow = false;
  15590. for(var x = (i + 1); x < items.length; x++) {
  15591. if(items[x] !== "|" && (!self.options.hideIcons || self.options.hideIcons.indexOf(items[x].name) == -1)) {
  15592. nonSeparatorIconsFollow = true;
  15593. }
  15594. }
  15595. if(!nonSeparatorIconsFollow)
  15596. continue;
  15597. }
  15598. // Create the icon and append to the toolbar
  15599. (function(item) {
  15600. var el;
  15601. if(item === "|") {
  15602. el = createSep();
  15603. } else {
  15604. el = createIcon(item, self.options.toolbarTips, self.options.shortcuts);
  15605. }
  15606. // bind events, special for info
  15607. if(item.action) {
  15608. if(typeof item.action === "function") {
  15609. el.onclick = function(e) {
  15610. e.preventDefault();
  15611. item.action(self);
  15612. };
  15613. } else if(typeof item.action === "string") {
  15614. el.href = item.action;
  15615. el.target = "_blank";
  15616. }
  15617. }
  15618. toolbarData[item.name || item] = el;
  15619. bar.appendChild(el);
  15620. })(items[i]);
  15621. }
  15622. self.toolbarElements = toolbarData;
  15623. var cm = this.codemirror;
  15624. cm.on("cursorActivity", function() {
  15625. var stat = getState(cm);
  15626. for(var key in toolbarData) {
  15627. (function(key) {
  15628. var el = toolbarData[key];
  15629. if(stat[key]) {
  15630. el.className += " active";
  15631. } else if(key != "fullscreen" && key != "side-by-side") {
  15632. el.className = el.className.replace(/\s*active\s*/g, "");
  15633. }
  15634. })(key);
  15635. }
  15636. });
  15637. var cmWrapper = cm.getWrapperElement();
  15638. cmWrapper.parentNode.insertBefore(bar, cmWrapper);
  15639. return bar;
  15640. };
  15641. SimpleMDE.prototype.createStatusbar = function(status) {
  15642. // Initialize
  15643. status = status || this.options.status;
  15644. var options = this.options;
  15645. var cm = this.codemirror;
  15646. // Make sure the status variable is valid
  15647. if(!status || status.length === 0)
  15648. return;
  15649. // Set up the built-in items
  15650. var items = [];
  15651. var i, onUpdate, defaultValue;
  15652. for(i = 0; i < status.length; i++) {
  15653. // Reset some values
  15654. onUpdate = undefined;
  15655. defaultValue = undefined;
  15656. // Handle if custom or not
  15657. if(typeof status[i] === "object") {
  15658. items.push({
  15659. className: status[i].className,
  15660. defaultValue: status[i].defaultValue,
  15661. onUpdate: status[i].onUpdate
  15662. });
  15663. } else {
  15664. var name = status[i];
  15665. if(name === "words") {
  15666. defaultValue = function(el) {
  15667. el.innerHTML = wordCount(cm.getValue());
  15668. };
  15669. onUpdate = function(el) {
  15670. el.innerHTML = wordCount(cm.getValue());
  15671. };
  15672. } else if(name === "lines") {
  15673. defaultValue = function(el) {
  15674. el.innerHTML = cm.lineCount();
  15675. };
  15676. onUpdate = function(el) {
  15677. el.innerHTML = cm.lineCount();
  15678. };
  15679. } else if(name === "cursor") {
  15680. defaultValue = function(el) {
  15681. el.innerHTML = "0:0";
  15682. };
  15683. onUpdate = function(el) {
  15684. var pos = cm.getCursor();
  15685. el.innerHTML = pos.line + ":" + pos.ch;
  15686. };
  15687. } else if(name === "autosave") {
  15688. defaultValue = function(el) {
  15689. if(options.autosave != undefined && options.autosave.enabled === true) {
  15690. el.setAttribute("id", "autosaved");
  15691. }
  15692. };
  15693. }
  15694. items.push({
  15695. className: name,
  15696. defaultValue: defaultValue,
  15697. onUpdate: onUpdate
  15698. });
  15699. }
  15700. }
  15701. // Create element for the status bar
  15702. var bar = document.createElement("div");
  15703. bar.className = "editor-statusbar";
  15704. // Create a new span for each item
  15705. for(i = 0; i < items.length; i++) {
  15706. // Store in temporary variable
  15707. var item = items[i];
  15708. // Create span element
  15709. var el = document.createElement("span");
  15710. el.className = item.className;
  15711. // Ensure the defaultValue is a function
  15712. if(typeof item.defaultValue === "function") {
  15713. item.defaultValue(el);
  15714. }
  15715. // Ensure the onUpdate is a function
  15716. if(typeof item.onUpdate === "function") {
  15717. // Create a closure around the span of the current action, then execute the onUpdate handler
  15718. this.codemirror.on("update", (function(el, item) {
  15719. return function() {
  15720. item.onUpdate(el);
  15721. };
  15722. }(el, item)));
  15723. }
  15724. // Append the item to the status bar
  15725. bar.appendChild(el);
  15726. }
  15727. // Insert the status bar into the DOM
  15728. var cmWrapper = this.codemirror.getWrapperElement();
  15729. cmWrapper.parentNode.insertBefore(bar, cmWrapper.nextSibling);
  15730. return bar;
  15731. };
  15732. /**
  15733. * Get or set the text content.
  15734. */
  15735. SimpleMDE.prototype.value = function(val) {
  15736. if(val === undefined) {
  15737. return this.codemirror.getValue();
  15738. } else {
  15739. this.codemirror.getDoc().setValue(val);
  15740. return this;
  15741. }
  15742. };
  15743. /**
  15744. * Bind static methods for exports.
  15745. */
  15746. SimpleMDE.toggleBold = toggleBold;
  15747. SimpleMDE.toggleItalic = toggleItalic;
  15748. SimpleMDE.toggleStrikethrough = toggleStrikethrough;
  15749. SimpleMDE.toggleBlockquote = toggleBlockquote;
  15750. SimpleMDE.toggleHeadingSmaller = toggleHeadingSmaller;
  15751. SimpleMDE.toggleHeadingBigger = toggleHeadingBigger;
  15752. SimpleMDE.toggleHeading1 = toggleHeading1;
  15753. SimpleMDE.toggleHeading2 = toggleHeading2;
  15754. SimpleMDE.toggleHeading3 = toggleHeading3;
  15755. SimpleMDE.toggleCodeBlock = toggleCodeBlock;
  15756. SimpleMDE.toggleUnorderedList = toggleUnorderedList;
  15757. SimpleMDE.toggleOrderedList = toggleOrderedList;
  15758. SimpleMDE.cleanBlock = cleanBlock;
  15759. SimpleMDE.drawLink = drawLink;
  15760. SimpleMDE.drawImage = drawImage;
  15761. SimpleMDE.drawTable = drawTable;
  15762. SimpleMDE.drawHorizontalRule = drawHorizontalRule;
  15763. SimpleMDE.undo = undo;
  15764. SimpleMDE.redo = redo;
  15765. SimpleMDE.togglePreview = togglePreview;
  15766. SimpleMDE.toggleSideBySide = toggleSideBySide;
  15767. SimpleMDE.toggleFullScreen = toggleFullScreen;
  15768. /**
  15769. * Bind instance methods for exports.
  15770. */
  15771. SimpleMDE.prototype.toggleBold = function() {
  15772. toggleBold(this);
  15773. };
  15774. SimpleMDE.prototype.toggleItalic = function() {
  15775. toggleItalic(this);
  15776. };
  15777. SimpleMDE.prototype.toggleStrikethrough = function() {
  15778. toggleStrikethrough(this);
  15779. };
  15780. SimpleMDE.prototype.toggleBlockquote = function() {
  15781. toggleBlockquote(this);
  15782. };
  15783. SimpleMDE.prototype.toggleHeadingSmaller = function() {
  15784. toggleHeadingSmaller(this);
  15785. };
  15786. SimpleMDE.prototype.toggleHeadingBigger = function() {
  15787. toggleHeadingBigger(this);
  15788. };
  15789. SimpleMDE.prototype.toggleHeading1 = function() {
  15790. toggleHeading1(this);
  15791. };
  15792. SimpleMDE.prototype.toggleHeading2 = function() {
  15793. toggleHeading2(this);
  15794. };
  15795. SimpleMDE.prototype.toggleHeading3 = function() {
  15796. toggleHeading3(this);
  15797. };
  15798. SimpleMDE.prototype.toggleCodeBlock = function() {
  15799. toggleCodeBlock(this);
  15800. };
  15801. SimpleMDE.prototype.toggleUnorderedList = function() {
  15802. toggleUnorderedList(this);
  15803. };
  15804. SimpleMDE.prototype.toggleOrderedList = function() {
  15805. toggleOrderedList(this);
  15806. };
  15807. SimpleMDE.prototype.cleanBlock = function() {
  15808. cleanBlock(this);
  15809. };
  15810. SimpleMDE.prototype.drawLink = function() {
  15811. drawLink(this);
  15812. };
  15813. SimpleMDE.prototype.drawImage = function() {
  15814. drawImage(this);
  15815. };
  15816. SimpleMDE.prototype.drawTable = function() {
  15817. drawTable(this);
  15818. };
  15819. SimpleMDE.prototype.drawHorizontalRule = function() {
  15820. drawHorizontalRule(this);
  15821. };
  15822. SimpleMDE.prototype.undo = function() {
  15823. undo(this);
  15824. };
  15825. SimpleMDE.prototype.redo = function() {
  15826. redo(this);
  15827. };
  15828. SimpleMDE.prototype.togglePreview = function() {
  15829. togglePreview(this);
  15830. };
  15831. SimpleMDE.prototype.toggleSideBySide = function() {
  15832. toggleSideBySide(this);
  15833. };
  15834. SimpleMDE.prototype.toggleFullScreen = function() {
  15835. toggleFullScreen(this);
  15836. };
  15837. SimpleMDE.prototype.isPreviewActive = function() {
  15838. var cm = this.codemirror;
  15839. var wrapper = cm.getWrapperElement();
  15840. var preview = wrapper.lastChild;
  15841. return /editor-preview-active/.test(preview.className);
  15842. };
  15843. SimpleMDE.prototype.isSideBySideActive = function() {
  15844. var cm = this.codemirror;
  15845. var wrapper = cm.getWrapperElement();
  15846. var preview = wrapper.nextSibling;
  15847. return /editor-preview-active-side/.test(preview.className);
  15848. };
  15849. SimpleMDE.prototype.isFullscreenActive = function() {
  15850. var cm = this.codemirror;
  15851. return cm.getOption("fullScreen");
  15852. };
  15853. SimpleMDE.prototype.getState = function() {
  15854. var cm = this.codemirror;
  15855. return getState(cm);
  15856. };
  15857. SimpleMDE.prototype.toTextArea = function() {
  15858. var cm = this.codemirror;
  15859. var wrapper = cm.getWrapperElement();
  15860. if(wrapper.parentNode) {
  15861. if(this.gui.toolbar) {
  15862. wrapper.parentNode.removeChild(this.gui.toolbar);
  15863. }
  15864. if(this.gui.statusbar) {
  15865. wrapper.parentNode.removeChild(this.gui.statusbar);
  15866. }
  15867. if(this.gui.sideBySide) {
  15868. wrapper.parentNode.removeChild(this.gui.sideBySide);
  15869. }
  15870. }
  15871. cm.toTextArea();
  15872. if(this.autosaveTimeoutId) {
  15873. clearTimeout(this.autosaveTimeoutId);
  15874. this.autosaveTimeoutId = undefined;
  15875. this.clearAutosavedValue();
  15876. }
  15877. };
  15878. module.exports = SimpleMDE;
  15879. },{"./codemirror/tablist":18,"codemirror":10,"codemirror-spell-checker":4,"codemirror/addon/display/fullscreen.js":5,"codemirror/addon/display/placeholder.js":6,"codemirror/addon/edit/continuelist.js":7,"codemirror/addon/mode/overlay.js":8,"codemirror/addon/selection/mark-selection.js":9,"codemirror/mode/gfm/gfm.js":11,"codemirror/mode/markdown/markdown.js":12,"codemirror/mode/xml/xml.js":14,"marked":16}]},{},[19])(19)
  15880. });