simplemde.js 575 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099
  1. /**
  2. * simplemde v1.11.2
  3. * Copyright Sparksuite, Inc.
  4. * @link https://github.com/sparksuite/simplemde-markdown-editor
  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.toByteArray = toByteArray
  10. exports.fromByteArray = fromByteArray
  11. var lookup = []
  12. var revLookup = []
  13. var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
  14. function init () {
  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. }
  23. init()
  24. function toByteArray (b64) {
  25. var i, j, l, tmp, placeHolders, arr
  26. var len = b64.length
  27. if (len % 4 > 0) {
  28. throw new Error('Invalid string. Length must be a multiple of 4')
  29. }
  30. // the number of equal signs (place holders)
  31. // if there are two placeholders, than the two characters before it
  32. // represent one byte
  33. // if there is only one, then the three characters before it represent 2 bytes
  34. // this is just a cheap hack to not do indexOf twice
  35. placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0
  36. // base64 is 4/3 + up to two characters of the original data
  37. arr = new Arr(len * 3 / 4 - placeHolders)
  38. // if there are placeholders, only get up to the last complete 4 chars
  39. l = placeHolders > 0 ? len - 4 : len
  40. var L = 0
  41. for (i = 0, j = 0; i < l; i += 4, j += 3) {
  42. tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]
  43. arr[L++] = (tmp >> 16) & 0xFF
  44. arr[L++] = (tmp >> 8) & 0xFF
  45. arr[L++] = tmp & 0xFF
  46. }
  47. if (placeHolders === 2) {
  48. tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4)
  49. arr[L++] = tmp & 0xFF
  50. } else if (placeHolders === 1) {
  51. tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2)
  52. arr[L++] = (tmp >> 8) & 0xFF
  53. arr[L++] = tmp & 0xFF
  54. }
  55. return arr
  56. }
  57. function tripletToBase64 (num) {
  58. return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]
  59. }
  60. function encodeChunk (uint8, start, end) {
  61. var tmp
  62. var output = []
  63. for (var i = start; i < end; i += 3) {
  64. tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2])
  65. output.push(tripletToBase64(tmp))
  66. }
  67. return output.join('')
  68. }
  69. function fromByteArray (uint8) {
  70. var tmp
  71. var len = uint8.length
  72. var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
  73. var output = ''
  74. var parts = []
  75. var maxChunkLength = 16383 // must be multiple of 3
  76. // go through the array every three bytes, we'll deal with trailing stuff later
  77. for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
  78. parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))
  79. }
  80. // pad the end with zeros, but make sure to not forget the extra bytes
  81. if (extraBytes === 1) {
  82. tmp = uint8[len - 1]
  83. output += lookup[tmp >> 2]
  84. output += lookup[(tmp << 4) & 0x3F]
  85. output += '=='
  86. } else if (extraBytes === 2) {
  87. tmp = (uint8[len - 2] << 8) + (uint8[len - 1])
  88. output += lookup[tmp >> 10]
  89. output += lookup[(tmp >> 4) & 0x3F]
  90. output += lookup[(tmp << 2) & 0x3F]
  91. output += '='
  92. }
  93. parts.push(output)
  94. return parts.join('')
  95. }
  96. },{}],2:[function(require,module,exports){
  97. },{}],3:[function(require,module,exports){
  98. (function (global){
  99. /*!
  100. * The buffer module from node.js, for the browser.
  101. *
  102. * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
  103. * @license MIT
  104. */
  105. /* eslint-disable no-proto */
  106. 'use strict'
  107. var base64 = require('base64-js')
  108. var ieee754 = require('ieee754')
  109. var isArray = require('isarray')
  110. exports.Buffer = Buffer
  111. exports.SlowBuffer = SlowBuffer
  112. exports.INSPECT_MAX_BYTES = 50
  113. /**
  114. * If `Buffer.TYPED_ARRAY_SUPPORT`:
  115. * === true Use Uint8Array implementation (fastest)
  116. * === false Use Object implementation (most compatible, even IE6)
  117. *
  118. * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
  119. * Opera 11.6+, iOS 4.2+.
  120. *
  121. * Due to various browser bugs, sometimes the Object implementation will be used even
  122. * when the browser supports typed arrays.
  123. *
  124. * Note:
  125. *
  126. * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,
  127. * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
  128. *
  129. * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
  130. *
  131. * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
  132. * incorrect length in some situations.
  133. * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they
  134. * get the Object implementation, which is slower but behaves correctly.
  135. */
  136. Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined
  137. ? global.TYPED_ARRAY_SUPPORT
  138. : typedArraySupport()
  139. /*
  140. * Export kMaxLength after typed array support is determined.
  141. */
  142. exports.kMaxLength = kMaxLength()
  143. function typedArraySupport () {
  144. try {
  145. var arr = new Uint8Array(1)
  146. arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }}
  147. return arr.foo() === 42 && // typed array instances can be augmented
  148. typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`
  149. arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`
  150. } catch (e) {
  151. return false
  152. }
  153. }
  154. function kMaxLength () {
  155. return Buffer.TYPED_ARRAY_SUPPORT
  156. ? 0x7fffffff
  157. : 0x3fffffff
  158. }
  159. function createBuffer (that, length) {
  160. if (kMaxLength() < length) {
  161. throw new RangeError('Invalid typed array length')
  162. }
  163. if (Buffer.TYPED_ARRAY_SUPPORT) {
  164. // Return an augmented `Uint8Array` instance, for best performance
  165. that = new Uint8Array(length)
  166. that.__proto__ = Buffer.prototype
  167. } else {
  168. // Fallback: Return an object instance of the Buffer class
  169. if (that === null) {
  170. that = new Buffer(length)
  171. }
  172. that.length = length
  173. }
  174. return that
  175. }
  176. /**
  177. * The Buffer constructor returns instances of `Uint8Array` that have their
  178. * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
  179. * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
  180. * and the `Uint8Array` methods. Square bracket notation works as expected -- it
  181. * returns a single octet.
  182. *
  183. * The `Uint8Array` prototype remains unmodified.
  184. */
  185. function Buffer (arg, encodingOrOffset, length) {
  186. if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) {
  187. return new Buffer(arg, encodingOrOffset, length)
  188. }
  189. // Common case.
  190. if (typeof arg === 'number') {
  191. if (typeof encodingOrOffset === 'string') {
  192. throw new Error(
  193. 'If encoding is specified then the first argument must be a string'
  194. )
  195. }
  196. return allocUnsafe(this, arg)
  197. }
  198. return from(this, arg, encodingOrOffset, length)
  199. }
  200. Buffer.poolSize = 8192 // not used by this implementation
  201. // TODO: Legacy, not needed anymore. Remove in next major version.
  202. Buffer._augment = function (arr) {
  203. arr.__proto__ = Buffer.prototype
  204. return arr
  205. }
  206. function from (that, value, encodingOrOffset, length) {
  207. if (typeof value === 'number') {
  208. throw new TypeError('"value" argument must not be a number')
  209. }
  210. if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {
  211. return fromArrayBuffer(that, value, encodingOrOffset, length)
  212. }
  213. if (typeof value === 'string') {
  214. return fromString(that, value, encodingOrOffset)
  215. }
  216. return fromObject(that, value)
  217. }
  218. /**
  219. * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
  220. * if value is a number.
  221. * Buffer.from(str[, encoding])
  222. * Buffer.from(array)
  223. * Buffer.from(buffer)
  224. * Buffer.from(arrayBuffer[, byteOffset[, length]])
  225. **/
  226. Buffer.from = function (value, encodingOrOffset, length) {
  227. return from(null, value, encodingOrOffset, length)
  228. }
  229. if (Buffer.TYPED_ARRAY_SUPPORT) {
  230. Buffer.prototype.__proto__ = Uint8Array.prototype
  231. Buffer.__proto__ = Uint8Array
  232. if (typeof Symbol !== 'undefined' && Symbol.species &&
  233. Buffer[Symbol.species] === Buffer) {
  234. // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
  235. Object.defineProperty(Buffer, Symbol.species, {
  236. value: null,
  237. configurable: true
  238. })
  239. }
  240. }
  241. function assertSize (size) {
  242. if (typeof size !== 'number') {
  243. throw new TypeError('"size" argument must be a number')
  244. }
  245. }
  246. function alloc (that, size, fill, encoding) {
  247. assertSize(size)
  248. if (size <= 0) {
  249. return createBuffer(that, size)
  250. }
  251. if (fill !== undefined) {
  252. // Only pay attention to encoding if it's a string. This
  253. // prevents accidentally sending in a number that would
  254. // be interpretted as a start offset.
  255. return typeof encoding === 'string'
  256. ? createBuffer(that, size).fill(fill, encoding)
  257. : createBuffer(that, size).fill(fill)
  258. }
  259. return createBuffer(that, size)
  260. }
  261. /**
  262. * Creates a new filled Buffer instance.
  263. * alloc(size[, fill[, encoding]])
  264. **/
  265. Buffer.alloc = function (size, fill, encoding) {
  266. return alloc(null, size, fill, encoding)
  267. }
  268. function allocUnsafe (that, size) {
  269. assertSize(size)
  270. that = createBuffer(that, size < 0 ? 0 : checked(size) | 0)
  271. if (!Buffer.TYPED_ARRAY_SUPPORT) {
  272. for (var i = 0; i < size; ++i) {
  273. that[i] = 0
  274. }
  275. }
  276. return that
  277. }
  278. /**
  279. * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
  280. * */
  281. Buffer.allocUnsafe = function (size) {
  282. return allocUnsafe(null, size)
  283. }
  284. /**
  285. * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
  286. */
  287. Buffer.allocUnsafeSlow = function (size) {
  288. return allocUnsafe(null, size)
  289. }
  290. function fromString (that, string, encoding) {
  291. if (typeof encoding !== 'string' || encoding === '') {
  292. encoding = 'utf8'
  293. }
  294. if (!Buffer.isEncoding(encoding)) {
  295. throw new TypeError('"encoding" must be a valid string encoding')
  296. }
  297. var length = byteLength(string, encoding) | 0
  298. that = createBuffer(that, length)
  299. that.write(string, encoding)
  300. return that
  301. }
  302. function fromArrayLike (that, array) {
  303. var length = checked(array.length) | 0
  304. that = createBuffer(that, length)
  305. for (var i = 0; i < length; i += 1) {
  306. that[i] = array[i] & 255
  307. }
  308. return that
  309. }
  310. function fromArrayBuffer (that, array, byteOffset, length) {
  311. array.byteLength // this throws if `array` is not a valid ArrayBuffer
  312. if (byteOffset < 0 || array.byteLength < byteOffset) {
  313. throw new RangeError('\'offset\' is out of bounds')
  314. }
  315. if (array.byteLength < byteOffset + (length || 0)) {
  316. throw new RangeError('\'length\' is out of bounds')
  317. }
  318. if (byteOffset === undefined && length === undefined) {
  319. array = new Uint8Array(array)
  320. } else if (length === undefined) {
  321. array = new Uint8Array(array, byteOffset)
  322. } else {
  323. array = new Uint8Array(array, byteOffset, length)
  324. }
  325. if (Buffer.TYPED_ARRAY_SUPPORT) {
  326. // Return an augmented `Uint8Array` instance, for best performance
  327. that = array
  328. that.__proto__ = Buffer.prototype
  329. } else {
  330. // Fallback: Return an object instance of the Buffer class
  331. that = fromArrayLike(that, array)
  332. }
  333. return that
  334. }
  335. function fromObject (that, obj) {
  336. if (Buffer.isBuffer(obj)) {
  337. var len = checked(obj.length) | 0
  338. that = createBuffer(that, len)
  339. if (that.length === 0) {
  340. return that
  341. }
  342. obj.copy(that, 0, 0, len)
  343. return that
  344. }
  345. if (obj) {
  346. if ((typeof ArrayBuffer !== 'undefined' &&
  347. obj.buffer instanceof ArrayBuffer) || 'length' in obj) {
  348. if (typeof obj.length !== 'number' || isnan(obj.length)) {
  349. return createBuffer(that, 0)
  350. }
  351. return fromArrayLike(that, obj)
  352. }
  353. if (obj.type === 'Buffer' && isArray(obj.data)) {
  354. return fromArrayLike(that, obj.data)
  355. }
  356. }
  357. throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')
  358. }
  359. function checked (length) {
  360. // Note: cannot use `length < kMaxLength` here because that fails when
  361. // length is NaN (which is otherwise coerced to zero.)
  362. if (length >= kMaxLength()) {
  363. throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
  364. 'size: 0x' + kMaxLength().toString(16) + ' bytes')
  365. }
  366. return length | 0
  367. }
  368. function SlowBuffer (length) {
  369. if (+length != length) { // eslint-disable-line eqeqeq
  370. length = 0
  371. }
  372. return Buffer.alloc(+length)
  373. }
  374. Buffer.isBuffer = function isBuffer (b) {
  375. return !!(b != null && b._isBuffer)
  376. }
  377. Buffer.compare = function compare (a, b) {
  378. if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
  379. throw new TypeError('Arguments must be Buffers')
  380. }
  381. if (a === b) return 0
  382. var x = a.length
  383. var y = b.length
  384. for (var i = 0, len = Math.min(x, y); i < len; ++i) {
  385. if (a[i] !== b[i]) {
  386. x = a[i]
  387. y = b[i]
  388. break
  389. }
  390. }
  391. if (x < y) return -1
  392. if (y < x) return 1
  393. return 0
  394. }
  395. Buffer.isEncoding = function isEncoding (encoding) {
  396. switch (String(encoding).toLowerCase()) {
  397. case 'hex':
  398. case 'utf8':
  399. case 'utf-8':
  400. case 'ascii':
  401. case 'binary':
  402. case 'base64':
  403. case 'raw':
  404. case 'ucs2':
  405. case 'ucs-2':
  406. case 'utf16le':
  407. case 'utf-16le':
  408. return true
  409. default:
  410. return false
  411. }
  412. }
  413. Buffer.concat = function concat (list, length) {
  414. if (!isArray(list)) {
  415. throw new TypeError('"list" argument must be an Array of Buffers')
  416. }
  417. if (list.length === 0) {
  418. return Buffer.alloc(0)
  419. }
  420. var i
  421. if (length === undefined) {
  422. length = 0
  423. for (i = 0; i < list.length; ++i) {
  424. length += list[i].length
  425. }
  426. }
  427. var buffer = Buffer.allocUnsafe(length)
  428. var pos = 0
  429. for (i = 0; i < list.length; ++i) {
  430. var buf = list[i]
  431. if (!Buffer.isBuffer(buf)) {
  432. throw new TypeError('"list" argument must be an Array of Buffers')
  433. }
  434. buf.copy(buffer, pos)
  435. pos += buf.length
  436. }
  437. return buffer
  438. }
  439. function byteLength (string, encoding) {
  440. if (Buffer.isBuffer(string)) {
  441. return string.length
  442. }
  443. if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' &&
  444. (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) {
  445. return string.byteLength
  446. }
  447. if (typeof string !== 'string') {
  448. string = '' + string
  449. }
  450. var len = string.length
  451. if (len === 0) return 0
  452. // Use a for loop to avoid recursion
  453. var loweredCase = false
  454. for (;;) {
  455. switch (encoding) {
  456. case 'ascii':
  457. case 'binary':
  458. case 'raw':
  459. case 'raws':
  460. return len
  461. case 'utf8':
  462. case 'utf-8':
  463. case undefined:
  464. return utf8ToBytes(string).length
  465. case 'ucs2':
  466. case 'ucs-2':
  467. case 'utf16le':
  468. case 'utf-16le':
  469. return len * 2
  470. case 'hex':
  471. return len >>> 1
  472. case 'base64':
  473. return base64ToBytes(string).length
  474. default:
  475. if (loweredCase) return utf8ToBytes(string).length // assume utf8
  476. encoding = ('' + encoding).toLowerCase()
  477. loweredCase = true
  478. }
  479. }
  480. }
  481. Buffer.byteLength = byteLength
  482. function slowToString (encoding, start, end) {
  483. var loweredCase = false
  484. // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
  485. // property of a typed array.
  486. // This behaves neither like String nor Uint8Array in that we set start/end
  487. // to their upper/lower bounds if the value passed is out of range.
  488. // undefined is handled specially as per ECMA-262 6th Edition,
  489. // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
  490. if (start === undefined || start < 0) {
  491. start = 0
  492. }
  493. // Return early if start > this.length. Done here to prevent potential uint32
  494. // coercion fail below.
  495. if (start > this.length) {
  496. return ''
  497. }
  498. if (end === undefined || end > this.length) {
  499. end = this.length
  500. }
  501. if (end <= 0) {
  502. return ''
  503. }
  504. // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
  505. end >>>= 0
  506. start >>>= 0
  507. if (end <= start) {
  508. return ''
  509. }
  510. if (!encoding) encoding = 'utf8'
  511. while (true) {
  512. switch (encoding) {
  513. case 'hex':
  514. return hexSlice(this, start, end)
  515. case 'utf8':
  516. case 'utf-8':
  517. return utf8Slice(this, start, end)
  518. case 'ascii':
  519. return asciiSlice(this, start, end)
  520. case 'binary':
  521. return binarySlice(this, start, end)
  522. case 'base64':
  523. return base64Slice(this, start, end)
  524. case 'ucs2':
  525. case 'ucs-2':
  526. case 'utf16le':
  527. case 'utf-16le':
  528. return utf16leSlice(this, start, end)
  529. default:
  530. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  531. encoding = (encoding + '').toLowerCase()
  532. loweredCase = true
  533. }
  534. }
  535. }
  536. // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect
  537. // Buffer instances.
  538. Buffer.prototype._isBuffer = true
  539. function swap (b, n, m) {
  540. var i = b[n]
  541. b[n] = b[m]
  542. b[m] = i
  543. }
  544. Buffer.prototype.swap16 = function swap16 () {
  545. var len = this.length
  546. if (len % 2 !== 0) {
  547. throw new RangeError('Buffer size must be a multiple of 16-bits')
  548. }
  549. for (var i = 0; i < len; i += 2) {
  550. swap(this, i, i + 1)
  551. }
  552. return this
  553. }
  554. Buffer.prototype.swap32 = function swap32 () {
  555. var len = this.length
  556. if (len % 4 !== 0) {
  557. throw new RangeError('Buffer size must be a multiple of 32-bits')
  558. }
  559. for (var i = 0; i < len; i += 4) {
  560. swap(this, i, i + 3)
  561. swap(this, i + 1, i + 2)
  562. }
  563. return this
  564. }
  565. Buffer.prototype.toString = function toString () {
  566. var length = this.length | 0
  567. if (length === 0) return ''
  568. if (arguments.length === 0) return utf8Slice(this, 0, length)
  569. return slowToString.apply(this, arguments)
  570. }
  571. Buffer.prototype.equals = function equals (b) {
  572. if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
  573. if (this === b) return true
  574. return Buffer.compare(this, b) === 0
  575. }
  576. Buffer.prototype.inspect = function inspect () {
  577. var str = ''
  578. var max = exports.INSPECT_MAX_BYTES
  579. if (this.length > 0) {
  580. str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')
  581. if (this.length > max) str += ' ... '
  582. }
  583. return '<Buffer ' + str + '>'
  584. }
  585. Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
  586. if (!Buffer.isBuffer(target)) {
  587. throw new TypeError('Argument must be a Buffer')
  588. }
  589. if (start === undefined) {
  590. start = 0
  591. }
  592. if (end === undefined) {
  593. end = target ? target.length : 0
  594. }
  595. if (thisStart === undefined) {
  596. thisStart = 0
  597. }
  598. if (thisEnd === undefined) {
  599. thisEnd = this.length
  600. }
  601. if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
  602. throw new RangeError('out of range index')
  603. }
  604. if (thisStart >= thisEnd && start >= end) {
  605. return 0
  606. }
  607. if (thisStart >= thisEnd) {
  608. return -1
  609. }
  610. if (start >= end) {
  611. return 1
  612. }
  613. start >>>= 0
  614. end >>>= 0
  615. thisStart >>>= 0
  616. thisEnd >>>= 0
  617. if (this === target) return 0
  618. var x = thisEnd - thisStart
  619. var y = end - start
  620. var len = Math.min(x, y)
  621. var thisCopy = this.slice(thisStart, thisEnd)
  622. var targetCopy = target.slice(start, end)
  623. for (var i = 0; i < len; ++i) {
  624. if (thisCopy[i] !== targetCopy[i]) {
  625. x = thisCopy[i]
  626. y = targetCopy[i]
  627. break
  628. }
  629. }
  630. if (x < y) return -1
  631. if (y < x) return 1
  632. return 0
  633. }
  634. function arrayIndexOf (arr, val, byteOffset, encoding) {
  635. var indexSize = 1
  636. var arrLength = arr.length
  637. var valLength = val.length
  638. if (encoding !== undefined) {
  639. encoding = String(encoding).toLowerCase()
  640. if (encoding === 'ucs2' || encoding === 'ucs-2' ||
  641. encoding === 'utf16le' || encoding === 'utf-16le') {
  642. if (arr.length < 2 || val.length < 2) {
  643. return -1
  644. }
  645. indexSize = 2
  646. arrLength /= 2
  647. valLength /= 2
  648. byteOffset /= 2
  649. }
  650. }
  651. function read (buf, i) {
  652. if (indexSize === 1) {
  653. return buf[i]
  654. } else {
  655. return buf.readUInt16BE(i * indexSize)
  656. }
  657. }
  658. var foundIndex = -1
  659. for (var i = byteOffset; i < arrLength; ++i) {
  660. if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
  661. if (foundIndex === -1) foundIndex = i
  662. if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
  663. } else {
  664. if (foundIndex !== -1) i -= i - foundIndex
  665. foundIndex = -1
  666. }
  667. }
  668. return -1
  669. }
  670. Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
  671. if (typeof byteOffset === 'string') {
  672. encoding = byteOffset
  673. byteOffset = 0
  674. } else if (byteOffset > 0x7fffffff) {
  675. byteOffset = 0x7fffffff
  676. } else if (byteOffset < -0x80000000) {
  677. byteOffset = -0x80000000
  678. }
  679. byteOffset >>= 0
  680. if (this.length === 0) return -1
  681. if (byteOffset >= this.length) return -1
  682. // Negative offsets start from the end of the buffer
  683. if (byteOffset < 0) byteOffset = Math.max(this.length + byteOffset, 0)
  684. if (typeof val === 'string') {
  685. val = Buffer.from(val, encoding)
  686. }
  687. if (Buffer.isBuffer(val)) {
  688. // special case: looking for empty string/buffer always fails
  689. if (val.length === 0) {
  690. return -1
  691. }
  692. return arrayIndexOf(this, val, byteOffset, encoding)
  693. }
  694. if (typeof val === 'number') {
  695. if (Buffer.TYPED_ARRAY_SUPPORT && Uint8Array.prototype.indexOf === 'function') {
  696. return Uint8Array.prototype.indexOf.call(this, val, byteOffset)
  697. }
  698. return arrayIndexOf(this, [ val ], byteOffset, encoding)
  699. }
  700. throw new TypeError('val must be string, number or Buffer')
  701. }
  702. Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
  703. return this.indexOf(val, byteOffset, encoding) !== -1
  704. }
  705. function hexWrite (buf, string, offset, length) {
  706. offset = Number(offset) || 0
  707. var remaining = buf.length - offset
  708. if (!length) {
  709. length = remaining
  710. } else {
  711. length = Number(length)
  712. if (length > remaining) {
  713. length = remaining
  714. }
  715. }
  716. // must be an even number of digits
  717. var strLen = string.length
  718. if (strLen % 2 !== 0) throw new Error('Invalid hex string')
  719. if (length > strLen / 2) {
  720. length = strLen / 2
  721. }
  722. for (var i = 0; i < length; ++i) {
  723. var parsed = parseInt(string.substr(i * 2, 2), 16)
  724. if (isNaN(parsed)) return i
  725. buf[offset + i] = parsed
  726. }
  727. return i
  728. }
  729. function utf8Write (buf, string, offset, length) {
  730. return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
  731. }
  732. function asciiWrite (buf, string, offset, length) {
  733. return blitBuffer(asciiToBytes(string), buf, offset, length)
  734. }
  735. function binaryWrite (buf, string, offset, length) {
  736. return asciiWrite(buf, string, offset, length)
  737. }
  738. function base64Write (buf, string, offset, length) {
  739. return blitBuffer(base64ToBytes(string), buf, offset, length)
  740. }
  741. function ucs2Write (buf, string, offset, length) {
  742. return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
  743. }
  744. Buffer.prototype.write = function write (string, offset, length, encoding) {
  745. // Buffer#write(string)
  746. if (offset === undefined) {
  747. encoding = 'utf8'
  748. length = this.length
  749. offset = 0
  750. // Buffer#write(string, encoding)
  751. } else if (length === undefined && typeof offset === 'string') {
  752. encoding = offset
  753. length = this.length
  754. offset = 0
  755. // Buffer#write(string, offset[, length][, encoding])
  756. } else if (isFinite(offset)) {
  757. offset = offset | 0
  758. if (isFinite(length)) {
  759. length = length | 0
  760. if (encoding === undefined) encoding = 'utf8'
  761. } else {
  762. encoding = length
  763. length = undefined
  764. }
  765. // legacy write(string, encoding, offset, length) - remove in v0.13
  766. } else {
  767. throw new Error(
  768. 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
  769. )
  770. }
  771. var remaining = this.length - offset
  772. if (length === undefined || length > remaining) length = remaining
  773. if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
  774. throw new RangeError('Attempt to write outside buffer bounds')
  775. }
  776. if (!encoding) encoding = 'utf8'
  777. var loweredCase = false
  778. for (;;) {
  779. switch (encoding) {
  780. case 'hex':
  781. return hexWrite(this, string, offset, length)
  782. case 'utf8':
  783. case 'utf-8':
  784. return utf8Write(this, string, offset, length)
  785. case 'ascii':
  786. return asciiWrite(this, string, offset, length)
  787. case 'binary':
  788. return binaryWrite(this, string, offset, length)
  789. case 'base64':
  790. // Warning: maxLength not taken into account in base64Write
  791. return base64Write(this, string, offset, length)
  792. case 'ucs2':
  793. case 'ucs-2':
  794. case 'utf16le':
  795. case 'utf-16le':
  796. return ucs2Write(this, string, offset, length)
  797. default:
  798. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  799. encoding = ('' + encoding).toLowerCase()
  800. loweredCase = true
  801. }
  802. }
  803. }
  804. Buffer.prototype.toJSON = function toJSON () {
  805. return {
  806. type: 'Buffer',
  807. data: Array.prototype.slice.call(this._arr || this, 0)
  808. }
  809. }
  810. function base64Slice (buf, start, end) {
  811. if (start === 0 && end === buf.length) {
  812. return base64.fromByteArray(buf)
  813. } else {
  814. return base64.fromByteArray(buf.slice(start, end))
  815. }
  816. }
  817. function utf8Slice (buf, start, end) {
  818. end = Math.min(buf.length, end)
  819. var res = []
  820. var i = start
  821. while (i < end) {
  822. var firstByte = buf[i]
  823. var codePoint = null
  824. var bytesPerSequence = (firstByte > 0xEF) ? 4
  825. : (firstByte > 0xDF) ? 3
  826. : (firstByte > 0xBF) ? 2
  827. : 1
  828. if (i + bytesPerSequence <= end) {
  829. var secondByte, thirdByte, fourthByte, tempCodePoint
  830. switch (bytesPerSequence) {
  831. case 1:
  832. if (firstByte < 0x80) {
  833. codePoint = firstByte
  834. }
  835. break
  836. case 2:
  837. secondByte = buf[i + 1]
  838. if ((secondByte & 0xC0) === 0x80) {
  839. tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
  840. if (tempCodePoint > 0x7F) {
  841. codePoint = tempCodePoint
  842. }
  843. }
  844. break
  845. case 3:
  846. secondByte = buf[i + 1]
  847. thirdByte = buf[i + 2]
  848. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
  849. tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
  850. if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
  851. codePoint = tempCodePoint
  852. }
  853. }
  854. break
  855. case 4:
  856. secondByte = buf[i + 1]
  857. thirdByte = buf[i + 2]
  858. fourthByte = buf[i + 3]
  859. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
  860. tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
  861. if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
  862. codePoint = tempCodePoint
  863. }
  864. }
  865. }
  866. }
  867. if (codePoint === null) {
  868. // we did not generate a valid codePoint so insert a
  869. // replacement char (U+FFFD) and advance only 1 byte
  870. codePoint = 0xFFFD
  871. bytesPerSequence = 1
  872. } else if (codePoint > 0xFFFF) {
  873. // encode to utf16 (surrogate pair dance)
  874. codePoint -= 0x10000
  875. res.push(codePoint >>> 10 & 0x3FF | 0xD800)
  876. codePoint = 0xDC00 | codePoint & 0x3FF
  877. }
  878. res.push(codePoint)
  879. i += bytesPerSequence
  880. }
  881. return decodeCodePointsArray(res)
  882. }
  883. // Based on http://stackoverflow.com/a/22747272/680742, the browser with
  884. // the lowest limit is Chrome, with 0x10000 args.
  885. // We go 1 magnitude less, for safety
  886. var MAX_ARGUMENTS_LENGTH = 0x1000
  887. function decodeCodePointsArray (codePoints) {
  888. var len = codePoints.length
  889. if (len <= MAX_ARGUMENTS_LENGTH) {
  890. return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
  891. }
  892. // Decode in chunks to avoid "call stack size exceeded".
  893. var res = ''
  894. var i = 0
  895. while (i < len) {
  896. res += String.fromCharCode.apply(
  897. String,
  898. codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
  899. )
  900. }
  901. return res
  902. }
  903. function asciiSlice (buf, start, end) {
  904. var ret = ''
  905. end = Math.min(buf.length, end)
  906. for (var i = start; i < end; ++i) {
  907. ret += String.fromCharCode(buf[i] & 0x7F)
  908. }
  909. return ret
  910. }
  911. function binarySlice (buf, start, end) {
  912. var ret = ''
  913. end = Math.min(buf.length, end)
  914. for (var i = start; i < end; ++i) {
  915. ret += String.fromCharCode(buf[i])
  916. }
  917. return ret
  918. }
  919. function hexSlice (buf, start, end) {
  920. var len = buf.length
  921. if (!start || start < 0) start = 0
  922. if (!end || end < 0 || end > len) end = len
  923. var out = ''
  924. for (var i = start; i < end; ++i) {
  925. out += toHex(buf[i])
  926. }
  927. return out
  928. }
  929. function utf16leSlice (buf, start, end) {
  930. var bytes = buf.slice(start, end)
  931. var res = ''
  932. for (var i = 0; i < bytes.length; i += 2) {
  933. res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)
  934. }
  935. return res
  936. }
  937. Buffer.prototype.slice = function slice (start, end) {
  938. var len = this.length
  939. start = ~~start
  940. end = end === undefined ? len : ~~end
  941. if (start < 0) {
  942. start += len
  943. if (start < 0) start = 0
  944. } else if (start > len) {
  945. start = len
  946. }
  947. if (end < 0) {
  948. end += len
  949. if (end < 0) end = 0
  950. } else if (end > len) {
  951. end = len
  952. }
  953. if (end < start) end = start
  954. var newBuf
  955. if (Buffer.TYPED_ARRAY_SUPPORT) {
  956. newBuf = this.subarray(start, end)
  957. newBuf.__proto__ = Buffer.prototype
  958. } else {
  959. var sliceLen = end - start
  960. newBuf = new Buffer(sliceLen, undefined)
  961. for (var i = 0; i < sliceLen; ++i) {
  962. newBuf[i] = this[i + start]
  963. }
  964. }
  965. return newBuf
  966. }
  967. /*
  968. * Need to make sure that buffer isn't trying to write out of bounds.
  969. */
  970. function checkOffset (offset, ext, length) {
  971. if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
  972. if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
  973. }
  974. Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
  975. offset = offset | 0
  976. byteLength = byteLength | 0
  977. if (!noAssert) checkOffset(offset, byteLength, this.length)
  978. var val = this[offset]
  979. var mul = 1
  980. var i = 0
  981. while (++i < byteLength && (mul *= 0x100)) {
  982. val += this[offset + i] * mul
  983. }
  984. return val
  985. }
  986. Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
  987. offset = offset | 0
  988. byteLength = byteLength | 0
  989. if (!noAssert) {
  990. checkOffset(offset, byteLength, this.length)
  991. }
  992. var val = this[offset + --byteLength]
  993. var mul = 1
  994. while (byteLength > 0 && (mul *= 0x100)) {
  995. val += this[offset + --byteLength] * mul
  996. }
  997. return val
  998. }
  999. Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
  1000. if (!noAssert) checkOffset(offset, 1, this.length)
  1001. return this[offset]
  1002. }
  1003. Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
  1004. if (!noAssert) checkOffset(offset, 2, this.length)
  1005. return this[offset] | (this[offset + 1] << 8)
  1006. }
  1007. Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
  1008. if (!noAssert) checkOffset(offset, 2, this.length)
  1009. return (this[offset] << 8) | this[offset + 1]
  1010. }
  1011. Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
  1012. if (!noAssert) checkOffset(offset, 4, this.length)
  1013. return ((this[offset]) |
  1014. (this[offset + 1] << 8) |
  1015. (this[offset + 2] << 16)) +
  1016. (this[offset + 3] * 0x1000000)
  1017. }
  1018. Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
  1019. if (!noAssert) checkOffset(offset, 4, this.length)
  1020. return (this[offset] * 0x1000000) +
  1021. ((this[offset + 1] << 16) |
  1022. (this[offset + 2] << 8) |
  1023. this[offset + 3])
  1024. }
  1025. Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
  1026. offset = offset | 0
  1027. byteLength = byteLength | 0
  1028. if (!noAssert) checkOffset(offset, byteLength, this.length)
  1029. var val = this[offset]
  1030. var mul = 1
  1031. var i = 0
  1032. while (++i < byteLength && (mul *= 0x100)) {
  1033. val += this[offset + i] * mul
  1034. }
  1035. mul *= 0x80
  1036. if (val >= mul) val -= Math.pow(2, 8 * byteLength)
  1037. return val
  1038. }
  1039. Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
  1040. offset = offset | 0
  1041. byteLength = byteLength | 0
  1042. if (!noAssert) checkOffset(offset, byteLength, this.length)
  1043. var i = byteLength
  1044. var mul = 1
  1045. var val = this[offset + --i]
  1046. while (i > 0 && (mul *= 0x100)) {
  1047. val += this[offset + --i] * mul
  1048. }
  1049. mul *= 0x80
  1050. if (val >= mul) val -= Math.pow(2, 8 * byteLength)
  1051. return val
  1052. }
  1053. Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
  1054. if (!noAssert) checkOffset(offset, 1, this.length)
  1055. if (!(this[offset] & 0x80)) return (this[offset])
  1056. return ((0xff - this[offset] + 1) * -1)
  1057. }
  1058. Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
  1059. if (!noAssert) checkOffset(offset, 2, this.length)
  1060. var val = this[offset] | (this[offset + 1] << 8)
  1061. return (val & 0x8000) ? val | 0xFFFF0000 : val
  1062. }
  1063. Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
  1064. if (!noAssert) checkOffset(offset, 2, this.length)
  1065. var val = this[offset + 1] | (this[offset] << 8)
  1066. return (val & 0x8000) ? val | 0xFFFF0000 : val
  1067. }
  1068. Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
  1069. if (!noAssert) checkOffset(offset, 4, this.length)
  1070. return (this[offset]) |
  1071. (this[offset + 1] << 8) |
  1072. (this[offset + 2] << 16) |
  1073. (this[offset + 3] << 24)
  1074. }
  1075. Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
  1076. if (!noAssert) checkOffset(offset, 4, this.length)
  1077. return (this[offset] << 24) |
  1078. (this[offset + 1] << 16) |
  1079. (this[offset + 2] << 8) |
  1080. (this[offset + 3])
  1081. }
  1082. Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
  1083. if (!noAssert) checkOffset(offset, 4, this.length)
  1084. return ieee754.read(this, offset, true, 23, 4)
  1085. }
  1086. Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
  1087. if (!noAssert) checkOffset(offset, 4, this.length)
  1088. return ieee754.read(this, offset, false, 23, 4)
  1089. }
  1090. Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
  1091. if (!noAssert) checkOffset(offset, 8, this.length)
  1092. return ieee754.read(this, offset, true, 52, 8)
  1093. }
  1094. Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
  1095. if (!noAssert) checkOffset(offset, 8, this.length)
  1096. return ieee754.read(this, offset, false, 52, 8)
  1097. }
  1098. function checkInt (buf, value, offset, ext, max, min) {
  1099. if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
  1100. if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
  1101. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  1102. }
  1103. Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
  1104. value = +value
  1105. offset = offset | 0
  1106. byteLength = byteLength | 0
  1107. if (!noAssert) {
  1108. var maxBytes = Math.pow(2, 8 * byteLength) - 1
  1109. checkInt(this, value, offset, byteLength, maxBytes, 0)
  1110. }
  1111. var mul = 1
  1112. var i = 0
  1113. this[offset] = value & 0xFF
  1114. while (++i < byteLength && (mul *= 0x100)) {
  1115. this[offset + i] = (value / mul) & 0xFF
  1116. }
  1117. return offset + byteLength
  1118. }
  1119. Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
  1120. value = +value
  1121. offset = offset | 0
  1122. byteLength = byteLength | 0
  1123. if (!noAssert) {
  1124. var maxBytes = Math.pow(2, 8 * byteLength) - 1
  1125. checkInt(this, value, offset, byteLength, maxBytes, 0)
  1126. }
  1127. var i = byteLength - 1
  1128. var mul = 1
  1129. this[offset + i] = value & 0xFF
  1130. while (--i >= 0 && (mul *= 0x100)) {
  1131. this[offset + i] = (value / mul) & 0xFF
  1132. }
  1133. return offset + byteLength
  1134. }
  1135. Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
  1136. value = +value
  1137. offset = offset | 0
  1138. if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
  1139. if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
  1140. this[offset] = (value & 0xff)
  1141. return offset + 1
  1142. }
  1143. function objectWriteUInt16 (buf, value, offset, littleEndian) {
  1144. if (value < 0) value = 0xffff + value + 1
  1145. for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) {
  1146. buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
  1147. (littleEndian ? i : 1 - i) * 8
  1148. }
  1149. }
  1150. Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
  1151. value = +value
  1152. offset = offset | 0
  1153. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  1154. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1155. this[offset] = (value & 0xff)
  1156. this[offset + 1] = (value >>> 8)
  1157. } else {
  1158. objectWriteUInt16(this, value, offset, true)
  1159. }
  1160. return offset + 2
  1161. }
  1162. Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
  1163. value = +value
  1164. offset = offset | 0
  1165. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  1166. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1167. this[offset] = (value >>> 8)
  1168. this[offset + 1] = (value & 0xff)
  1169. } else {
  1170. objectWriteUInt16(this, value, offset, false)
  1171. }
  1172. return offset + 2
  1173. }
  1174. function objectWriteUInt32 (buf, value, offset, littleEndian) {
  1175. if (value < 0) value = 0xffffffff + value + 1
  1176. for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) {
  1177. buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff
  1178. }
  1179. }
  1180. Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
  1181. value = +value
  1182. offset = offset | 0
  1183. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  1184. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1185. this[offset + 3] = (value >>> 24)
  1186. this[offset + 2] = (value >>> 16)
  1187. this[offset + 1] = (value >>> 8)
  1188. this[offset] = (value & 0xff)
  1189. } else {
  1190. objectWriteUInt32(this, value, offset, true)
  1191. }
  1192. return offset + 4
  1193. }
  1194. Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
  1195. value = +value
  1196. offset = offset | 0
  1197. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  1198. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1199. this[offset] = (value >>> 24)
  1200. this[offset + 1] = (value >>> 16)
  1201. this[offset + 2] = (value >>> 8)
  1202. this[offset + 3] = (value & 0xff)
  1203. } else {
  1204. objectWriteUInt32(this, value, offset, false)
  1205. }
  1206. return offset + 4
  1207. }
  1208. Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
  1209. value = +value
  1210. offset = offset | 0
  1211. if (!noAssert) {
  1212. var limit = Math.pow(2, 8 * byteLength - 1)
  1213. checkInt(this, value, offset, byteLength, limit - 1, -limit)
  1214. }
  1215. var i = 0
  1216. var mul = 1
  1217. var sub = 0
  1218. this[offset] = value & 0xFF
  1219. while (++i < byteLength && (mul *= 0x100)) {
  1220. if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
  1221. sub = 1
  1222. }
  1223. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  1224. }
  1225. return offset + byteLength
  1226. }
  1227. Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
  1228. value = +value
  1229. offset = offset | 0
  1230. if (!noAssert) {
  1231. var limit = Math.pow(2, 8 * byteLength - 1)
  1232. checkInt(this, value, offset, byteLength, limit - 1, -limit)
  1233. }
  1234. var i = byteLength - 1
  1235. var mul = 1
  1236. var sub = 0
  1237. this[offset + i] = value & 0xFF
  1238. while (--i >= 0 && (mul *= 0x100)) {
  1239. if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
  1240. sub = 1
  1241. }
  1242. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  1243. }
  1244. return offset + byteLength
  1245. }
  1246. Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
  1247. value = +value
  1248. offset = offset | 0
  1249. if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
  1250. if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
  1251. if (value < 0) value = 0xff + value + 1
  1252. this[offset] = (value & 0xff)
  1253. return offset + 1
  1254. }
  1255. Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
  1256. value = +value
  1257. offset = offset | 0
  1258. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  1259. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1260. this[offset] = (value & 0xff)
  1261. this[offset + 1] = (value >>> 8)
  1262. } else {
  1263. objectWriteUInt16(this, value, offset, true)
  1264. }
  1265. return offset + 2
  1266. }
  1267. Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
  1268. value = +value
  1269. offset = offset | 0
  1270. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  1271. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1272. this[offset] = (value >>> 8)
  1273. this[offset + 1] = (value & 0xff)
  1274. } else {
  1275. objectWriteUInt16(this, value, offset, false)
  1276. }
  1277. return offset + 2
  1278. }
  1279. Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
  1280. value = +value
  1281. offset = offset | 0
  1282. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  1283. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1284. this[offset] = (value & 0xff)
  1285. this[offset + 1] = (value >>> 8)
  1286. this[offset + 2] = (value >>> 16)
  1287. this[offset + 3] = (value >>> 24)
  1288. } else {
  1289. objectWriteUInt32(this, value, offset, true)
  1290. }
  1291. return offset + 4
  1292. }
  1293. Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
  1294. value = +value
  1295. offset = offset | 0
  1296. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  1297. if (value < 0) value = 0xffffffff + value + 1
  1298. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1299. this[offset] = (value >>> 24)
  1300. this[offset + 1] = (value >>> 16)
  1301. this[offset + 2] = (value >>> 8)
  1302. this[offset + 3] = (value & 0xff)
  1303. } else {
  1304. objectWriteUInt32(this, value, offset, false)
  1305. }
  1306. return offset + 4
  1307. }
  1308. function checkIEEE754 (buf, value, offset, ext, max, min) {
  1309. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  1310. if (offset < 0) throw new RangeError('Index out of range')
  1311. }
  1312. function writeFloat (buf, value, offset, littleEndian, noAssert) {
  1313. if (!noAssert) {
  1314. checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
  1315. }
  1316. ieee754.write(buf, value, offset, littleEndian, 23, 4)
  1317. return offset + 4
  1318. }
  1319. Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
  1320. return writeFloat(this, value, offset, true, noAssert)
  1321. }
  1322. Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
  1323. return writeFloat(this, value, offset, false, noAssert)
  1324. }
  1325. function writeDouble (buf, value, offset, littleEndian, noAssert) {
  1326. if (!noAssert) {
  1327. checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
  1328. }
  1329. ieee754.write(buf, value, offset, littleEndian, 52, 8)
  1330. return offset + 8
  1331. }
  1332. Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
  1333. return writeDouble(this, value, offset, true, noAssert)
  1334. }
  1335. Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
  1336. return writeDouble(this, value, offset, false, noAssert)
  1337. }
  1338. // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
  1339. Buffer.prototype.copy = function copy (target, targetStart, start, end) {
  1340. if (!start) start = 0
  1341. if (!end && end !== 0) end = this.length
  1342. if (targetStart >= target.length) targetStart = target.length
  1343. if (!targetStart) targetStart = 0
  1344. if (end > 0 && end < start) end = start
  1345. // Copy 0 bytes; we're done
  1346. if (end === start) return 0
  1347. if (target.length === 0 || this.length === 0) return 0
  1348. // Fatal error conditions
  1349. if (targetStart < 0) {
  1350. throw new RangeError('targetStart out of bounds')
  1351. }
  1352. if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
  1353. if (end < 0) throw new RangeError('sourceEnd out of bounds')
  1354. // Are we oob?
  1355. if (end > this.length) end = this.length
  1356. if (target.length - targetStart < end - start) {
  1357. end = target.length - targetStart + start
  1358. }
  1359. var len = end - start
  1360. var i
  1361. if (this === target && start < targetStart && targetStart < end) {
  1362. // descending copy from end
  1363. for (i = len - 1; i >= 0; --i) {
  1364. target[i + targetStart] = this[i + start]
  1365. }
  1366. } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {
  1367. // ascending copy from start
  1368. for (i = 0; i < len; ++i) {
  1369. target[i + targetStart] = this[i + start]
  1370. }
  1371. } else {
  1372. Uint8Array.prototype.set.call(
  1373. target,
  1374. this.subarray(start, start + len),
  1375. targetStart
  1376. )
  1377. }
  1378. return len
  1379. }
  1380. // Usage:
  1381. // buffer.fill(number[, offset[, end]])
  1382. // buffer.fill(buffer[, offset[, end]])
  1383. // buffer.fill(string[, offset[, end]][, encoding])
  1384. Buffer.prototype.fill = function fill (val, start, end, encoding) {
  1385. // Handle string cases:
  1386. if (typeof val === 'string') {
  1387. if (typeof start === 'string') {
  1388. encoding = start
  1389. start = 0
  1390. end = this.length
  1391. } else if (typeof end === 'string') {
  1392. encoding = end
  1393. end = this.length
  1394. }
  1395. if (val.length === 1) {
  1396. var code = val.charCodeAt(0)
  1397. if (code < 256) {
  1398. val = code
  1399. }
  1400. }
  1401. if (encoding !== undefined && typeof encoding !== 'string') {
  1402. throw new TypeError('encoding must be a string')
  1403. }
  1404. if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
  1405. throw new TypeError('Unknown encoding: ' + encoding)
  1406. }
  1407. } else if (typeof val === 'number') {
  1408. val = val & 255
  1409. }
  1410. // Invalid ranges are not set to a default, so can range check early.
  1411. if (start < 0 || this.length < start || this.length < end) {
  1412. throw new RangeError('Out of range index')
  1413. }
  1414. if (end <= start) {
  1415. return this
  1416. }
  1417. start = start >>> 0
  1418. end = end === undefined ? this.length : end >>> 0
  1419. if (!val) val = 0
  1420. var i
  1421. if (typeof val === 'number') {
  1422. for (i = start; i < end; ++i) {
  1423. this[i] = val
  1424. }
  1425. } else {
  1426. var bytes = Buffer.isBuffer(val)
  1427. ? val
  1428. : utf8ToBytes(new Buffer(val, encoding).toString())
  1429. var len = bytes.length
  1430. for (i = 0; i < end - start; ++i) {
  1431. this[i + start] = bytes[i % len]
  1432. }
  1433. }
  1434. return this
  1435. }
  1436. // HELPER FUNCTIONS
  1437. // ================
  1438. var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g
  1439. function base64clean (str) {
  1440. // Node strips out invalid characters like \n and \t from the string, base64-js does not
  1441. str = stringtrim(str).replace(INVALID_BASE64_RE, '')
  1442. // Node converts strings with length < 2 to ''
  1443. if (str.length < 2) return ''
  1444. // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
  1445. while (str.length % 4 !== 0) {
  1446. str = str + '='
  1447. }
  1448. return str
  1449. }
  1450. function stringtrim (str) {
  1451. if (str.trim) return str.trim()
  1452. return str.replace(/^\s+|\s+$/g, '')
  1453. }
  1454. function toHex (n) {
  1455. if (n < 16) return '0' + n.toString(16)
  1456. return n.toString(16)
  1457. }
  1458. function utf8ToBytes (string, units) {
  1459. units = units || Infinity
  1460. var codePoint
  1461. var length = string.length
  1462. var leadSurrogate = null
  1463. var bytes = []
  1464. for (var i = 0; i < length; ++i) {
  1465. codePoint = string.charCodeAt(i)
  1466. // is surrogate component
  1467. if (codePoint > 0xD7FF && codePoint < 0xE000) {
  1468. // last char was a lead
  1469. if (!leadSurrogate) {
  1470. // no lead yet
  1471. if (codePoint > 0xDBFF) {
  1472. // unexpected trail
  1473. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  1474. continue
  1475. } else if (i + 1 === length) {
  1476. // unpaired lead
  1477. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  1478. continue
  1479. }
  1480. // valid lead
  1481. leadSurrogate = codePoint
  1482. continue
  1483. }
  1484. // 2 leads in a row
  1485. if (codePoint < 0xDC00) {
  1486. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  1487. leadSurrogate = codePoint
  1488. continue
  1489. }
  1490. // valid surrogate pair
  1491. codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
  1492. } else if (leadSurrogate) {
  1493. // valid bmp char, but last char was a lead
  1494. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  1495. }
  1496. leadSurrogate = null
  1497. // encode utf8
  1498. if (codePoint < 0x80) {
  1499. if ((units -= 1) < 0) break
  1500. bytes.push(codePoint)
  1501. } else if (codePoint < 0x800) {
  1502. if ((units -= 2) < 0) break
  1503. bytes.push(
  1504. codePoint >> 0x6 | 0xC0,
  1505. codePoint & 0x3F | 0x80
  1506. )
  1507. } else if (codePoint < 0x10000) {
  1508. if ((units -= 3) < 0) break
  1509. bytes.push(
  1510. codePoint >> 0xC | 0xE0,
  1511. codePoint >> 0x6 & 0x3F | 0x80,
  1512. codePoint & 0x3F | 0x80
  1513. )
  1514. } else if (codePoint < 0x110000) {
  1515. if ((units -= 4) < 0) break
  1516. bytes.push(
  1517. codePoint >> 0x12 | 0xF0,
  1518. codePoint >> 0xC & 0x3F | 0x80,
  1519. codePoint >> 0x6 & 0x3F | 0x80,
  1520. codePoint & 0x3F | 0x80
  1521. )
  1522. } else {
  1523. throw new Error('Invalid code point')
  1524. }
  1525. }
  1526. return bytes
  1527. }
  1528. function asciiToBytes (str) {
  1529. var byteArray = []
  1530. for (var i = 0; i < str.length; ++i) {
  1531. // Node's code seems to be doing this and not & 0x7F..
  1532. byteArray.push(str.charCodeAt(i) & 0xFF)
  1533. }
  1534. return byteArray
  1535. }
  1536. function utf16leToBytes (str, units) {
  1537. var c, hi, lo
  1538. var byteArray = []
  1539. for (var i = 0; i < str.length; ++i) {
  1540. if ((units -= 2) < 0) break
  1541. c = str.charCodeAt(i)
  1542. hi = c >> 8
  1543. lo = c % 256
  1544. byteArray.push(lo)
  1545. byteArray.push(hi)
  1546. }
  1547. return byteArray
  1548. }
  1549. function base64ToBytes (str) {
  1550. return base64.toByteArray(base64clean(str))
  1551. }
  1552. function blitBuffer (src, dst, offset, length) {
  1553. for (var i = 0; i < length; ++i) {
  1554. if ((i + offset >= dst.length) || (i >= src.length)) break
  1555. dst[i + offset] = src[i]
  1556. }
  1557. return i
  1558. }
  1559. function isnan (val) {
  1560. return val !== val // eslint-disable-line no-self-compare
  1561. }
  1562. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  1563. },{"base64-js":1,"ieee754":15,"isarray":16}],4:[function(require,module,exports){
  1564. // Use strict mode (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode)
  1565. "use strict";
  1566. // Requires
  1567. var Typo = require("typo-js");
  1568. // Create function
  1569. function CodeMirrorSpellChecker(options) {
  1570. // Initialize
  1571. options = options || {};
  1572. // Verify
  1573. if(typeof options.codeMirrorInstance !== "function" || typeof options.codeMirrorInstance.defineMode !== "function") {
  1574. console.log("CodeMirror Spell Checker: You must provide an instance of CodeMirror via the option `codeMirrorInstance`");
  1575. return;
  1576. }
  1577. // Because some browsers don't support this functionality yet
  1578. if(!String.prototype.includes) {
  1579. String.prototype.includes = function() {
  1580. "use strict";
  1581. return String.prototype.indexOf.apply(this, arguments) !== -1;
  1582. };
  1583. }
  1584. // Define the new mode
  1585. options.codeMirrorInstance.defineMode("spell-checker", function(config) {
  1586. // Load AFF/DIC data
  1587. if(!CodeMirrorSpellChecker.aff_loading) {
  1588. CodeMirrorSpellChecker.aff_loading = true;
  1589. var xhr_aff = new XMLHttpRequest();
  1590. xhr_aff.open("GET", "https://cdn.jsdelivr.net/codemirror.spell-checker/latest/en_US.aff", true);
  1591. xhr_aff.onload = function() {
  1592. if(xhr_aff.readyState === 4 && xhr_aff.status === 200) {
  1593. CodeMirrorSpellChecker.aff_data = xhr_aff.responseText;
  1594. CodeMirrorSpellChecker.num_loaded++;
  1595. if(CodeMirrorSpellChecker.num_loaded == 2) {
  1596. CodeMirrorSpellChecker.typo = new Typo("en_US", CodeMirrorSpellChecker.aff_data, CodeMirrorSpellChecker.dic_data, {
  1597. platform: "any"
  1598. });
  1599. }
  1600. }
  1601. };
  1602. xhr_aff.send(null);
  1603. }
  1604. if(!CodeMirrorSpellChecker.dic_loading) {
  1605. CodeMirrorSpellChecker.dic_loading = true;
  1606. var xhr_dic = new XMLHttpRequest();
  1607. xhr_dic.open("GET", "https://cdn.jsdelivr.net/codemirror.spell-checker/latest/en_US.dic", true);
  1608. xhr_dic.onload = function() {
  1609. if(xhr_dic.readyState === 4 && xhr_dic.status === 200) {
  1610. CodeMirrorSpellChecker.dic_data = xhr_dic.responseText;
  1611. CodeMirrorSpellChecker.num_loaded++;
  1612. if(CodeMirrorSpellChecker.num_loaded == 2) {
  1613. CodeMirrorSpellChecker.typo = new Typo("en_US", CodeMirrorSpellChecker.aff_data, CodeMirrorSpellChecker.dic_data, {
  1614. platform: "any"
  1615. });
  1616. }
  1617. }
  1618. };
  1619. xhr_dic.send(null);
  1620. }
  1621. // Define what separates a word
  1622. var rx_word = "!\"#$%&()*+,-./:;<=>?@[\\]^_`{|}~ ";
  1623. // Create the overlay and such
  1624. var overlay = {
  1625. token: function(stream) {
  1626. var ch = stream.peek();
  1627. var word = "";
  1628. if(rx_word.includes(ch)) {
  1629. stream.next();
  1630. return null;
  1631. }
  1632. while((ch = stream.peek()) != null && !rx_word.includes(ch)) {
  1633. word += ch;
  1634. stream.next();
  1635. }
  1636. if(CodeMirrorSpellChecker.typo && !CodeMirrorSpellChecker.typo.check(word))
  1637. return "spell-error"; // CSS class: cm-spell-error
  1638. return null;
  1639. }
  1640. };
  1641. var mode = options.codeMirrorInstance.getMode(
  1642. config, config.backdrop || "text/plain"
  1643. );
  1644. return options.codeMirrorInstance.overlayMode(mode, overlay, true);
  1645. });
  1646. }
  1647. // Initialize data globally to reduce memory consumption
  1648. CodeMirrorSpellChecker.num_loaded = 0;
  1649. CodeMirrorSpellChecker.aff_loading = false;
  1650. CodeMirrorSpellChecker.dic_loading = false;
  1651. CodeMirrorSpellChecker.aff_data = "";
  1652. CodeMirrorSpellChecker.dic_data = "";
  1653. CodeMirrorSpellChecker.typo;
  1654. // Export
  1655. module.exports = CodeMirrorSpellChecker;
  1656. },{"typo-js":18}],5:[function(require,module,exports){
  1657. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  1658. // Distributed under an MIT license: http://codemirror.net/LICENSE
  1659. (function(mod) {
  1660. if (typeof exports == "object" && typeof module == "object") // CommonJS
  1661. mod(require("../../lib/codemirror"));
  1662. else if (typeof define == "function" && define.amd) // AMD
  1663. define(["../../lib/codemirror"], mod);
  1664. else // Plain browser env
  1665. mod(CodeMirror);
  1666. })(function(CodeMirror) {
  1667. "use strict";
  1668. CodeMirror.defineOption("fullScreen", false, function(cm, val, old) {
  1669. if (old == CodeMirror.Init) old = false;
  1670. if (!old == !val) return;
  1671. if (val) setFullscreen(cm);
  1672. else setNormal(cm);
  1673. });
  1674. function setFullscreen(cm) {
  1675. var wrap = cm.getWrapperElement();
  1676. cm.state.fullScreenRestore = {scrollTop: window.pageYOffset, scrollLeft: window.pageXOffset,
  1677. width: wrap.style.width, height: wrap.style.height};
  1678. wrap.style.width = "";
  1679. wrap.style.height = "auto";
  1680. wrap.className += " CodeMirror-fullscreen";
  1681. document.documentElement.style.overflow = "hidden";
  1682. cm.refresh();
  1683. }
  1684. function setNormal(cm) {
  1685. var wrap = cm.getWrapperElement();
  1686. wrap.className = wrap.className.replace(/\s*CodeMirror-fullscreen\b/, "");
  1687. document.documentElement.style.overflow = "";
  1688. var info = cm.state.fullScreenRestore;
  1689. wrap.style.width = info.width; wrap.style.height = info.height;
  1690. window.scrollTo(info.scrollLeft, info.scrollTop);
  1691. cm.refresh();
  1692. }
  1693. });
  1694. },{"../../lib/codemirror":10}],6:[function(require,module,exports){
  1695. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  1696. // Distributed under an MIT license: http://codemirror.net/LICENSE
  1697. (function(mod) {
  1698. if (typeof exports == "object" && typeof module == "object") // CommonJS
  1699. mod(require("../../lib/codemirror"));
  1700. else if (typeof define == "function" && define.amd) // AMD
  1701. define(["../../lib/codemirror"], mod);
  1702. else // Plain browser env
  1703. mod(CodeMirror);
  1704. })(function(CodeMirror) {
  1705. CodeMirror.defineOption("placeholder", "", function(cm, val, old) {
  1706. var prev = old && old != CodeMirror.Init;
  1707. if (val && !prev) {
  1708. cm.on("blur", onBlur);
  1709. cm.on("change", onChange);
  1710. cm.on("swapDoc", onChange);
  1711. onChange(cm);
  1712. } else if (!val && prev) {
  1713. cm.off("blur", onBlur);
  1714. cm.off("change", onChange);
  1715. cm.off("swapDoc", onChange);
  1716. clearPlaceholder(cm);
  1717. var wrapper = cm.getWrapperElement();
  1718. wrapper.className = wrapper.className.replace(" CodeMirror-empty", "");
  1719. }
  1720. if (val && !cm.hasFocus()) onBlur(cm);
  1721. });
  1722. function clearPlaceholder(cm) {
  1723. if (cm.state.placeholder) {
  1724. cm.state.placeholder.parentNode.removeChild(cm.state.placeholder);
  1725. cm.state.placeholder = null;
  1726. }
  1727. }
  1728. function setPlaceholder(cm) {
  1729. clearPlaceholder(cm);
  1730. var elt = cm.state.placeholder = document.createElement("pre");
  1731. elt.style.cssText = "height: 0; overflow: visible";
  1732. elt.className = "CodeMirror-placeholder";
  1733. var placeHolder = cm.getOption("placeholder")
  1734. if (typeof placeHolder == "string") placeHolder = document.createTextNode(placeHolder)
  1735. elt.appendChild(placeHolder)
  1736. cm.display.lineSpace.insertBefore(elt, cm.display.lineSpace.firstChild);
  1737. }
  1738. function onBlur(cm) {
  1739. if (isEmpty(cm)) setPlaceholder(cm);
  1740. }
  1741. function onChange(cm) {
  1742. var wrapper = cm.getWrapperElement(), empty = isEmpty(cm);
  1743. wrapper.className = wrapper.className.replace(" CodeMirror-empty", "") + (empty ? " CodeMirror-empty" : "");
  1744. if (empty) setPlaceholder(cm);
  1745. else clearPlaceholder(cm);
  1746. }
  1747. function isEmpty(cm) {
  1748. return (cm.lineCount() === 1) && (cm.getLine(0) === "");
  1749. }
  1750. });
  1751. },{"../../lib/codemirror":10}],7:[function(require,module,exports){
  1752. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  1753. // Distributed under an MIT license: http://codemirror.net/LICENSE
  1754. (function(mod) {
  1755. if (typeof exports == "object" && typeof module == "object") // CommonJS
  1756. mod(require("../../lib/codemirror"));
  1757. else if (typeof define == "function" && define.amd) // AMD
  1758. define(["../../lib/codemirror"], mod);
  1759. else // Plain browser env
  1760. mod(CodeMirror);
  1761. })(function(CodeMirror) {
  1762. "use strict";
  1763. var listRE = /^(\s*)(>[> ]*|[*+-]\s|(\d+)([.)]))(\s*)/,
  1764. emptyListRE = /^(\s*)(>[> ]*|[*+-]|(\d+)[.)])(\s*)$/,
  1765. unorderedListRE = /[*+-]\s/;
  1766. CodeMirror.commands.newlineAndIndentContinueMarkdownList = function(cm) {
  1767. if (cm.getOption("disableInput")) return CodeMirror.Pass;
  1768. var ranges = cm.listSelections(), replacements = [];
  1769. for (var i = 0; i < ranges.length; i++) {
  1770. var pos = ranges[i].head;
  1771. var eolState = cm.getStateAfter(pos.line);
  1772. var inList = eolState.list !== false;
  1773. var inQuote = eolState.quote !== 0;
  1774. var line = cm.getLine(pos.line), match = listRE.exec(line);
  1775. if (!ranges[i].empty() || (!inList && !inQuote) || !match) {
  1776. cm.execCommand("newlineAndIndent");
  1777. return;
  1778. }
  1779. if (emptyListRE.test(line)) {
  1780. cm.replaceRange("", {
  1781. line: pos.line, ch: 0
  1782. }, {
  1783. line: pos.line, ch: pos.ch + 1
  1784. });
  1785. replacements[i] = "\n";
  1786. } else {
  1787. var indent = match[1], after = match[5];
  1788. var bullet = unorderedListRE.test(match[2]) || match[2].indexOf(">") >= 0
  1789. ? match[2]
  1790. : (parseInt(match[3], 10) + 1) + match[4];
  1791. replacements[i] = "\n" + indent + bullet + after;
  1792. }
  1793. }
  1794. cm.replaceSelections(replacements);
  1795. };
  1796. });
  1797. },{"../../lib/codemirror":10}],8:[function(require,module,exports){
  1798. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  1799. // Distributed under an MIT license: http://codemirror.net/LICENSE
  1800. // Utility function that allows modes to be combined. The mode given
  1801. // as the base argument takes care of most of the normal mode
  1802. // functionality, but a second (typically simple) mode is used, which
  1803. // can override the style of text. Both modes get to parse all of the
  1804. // text, but when both assign a non-null style to a piece of code, the
  1805. // overlay wins, unless the combine argument was true and not overridden,
  1806. // or state.overlay.combineTokens was true, in which case the styles are
  1807. // combined.
  1808. (function(mod) {
  1809. if (typeof exports == "object" && typeof module == "object") // CommonJS
  1810. mod(require("../../lib/codemirror"));
  1811. else if (typeof define == "function" && define.amd) // AMD
  1812. define(["../../lib/codemirror"], mod);
  1813. else // Plain browser env
  1814. mod(CodeMirror);
  1815. })(function(CodeMirror) {
  1816. "use strict";
  1817. CodeMirror.overlayMode = function(base, overlay, combine) {
  1818. return {
  1819. startState: function() {
  1820. return {
  1821. base: CodeMirror.startState(base),
  1822. overlay: CodeMirror.startState(overlay),
  1823. basePos: 0, baseCur: null,
  1824. overlayPos: 0, overlayCur: null,
  1825. streamSeen: null
  1826. };
  1827. },
  1828. copyState: function(state) {
  1829. return {
  1830. base: CodeMirror.copyState(base, state.base),
  1831. overlay: CodeMirror.copyState(overlay, state.overlay),
  1832. basePos: state.basePos, baseCur: null,
  1833. overlayPos: state.overlayPos, overlayCur: null
  1834. };
  1835. },
  1836. token: function(stream, state) {
  1837. if (stream != state.streamSeen ||
  1838. Math.min(state.basePos, state.overlayPos) < stream.start) {
  1839. state.streamSeen = stream;
  1840. state.basePos = state.overlayPos = stream.start;
  1841. }
  1842. if (stream.start == state.basePos) {
  1843. state.baseCur = base.token(stream, state.base);
  1844. state.basePos = stream.pos;
  1845. }
  1846. if (stream.start == state.overlayPos) {
  1847. stream.pos = stream.start;
  1848. state.overlayCur = overlay.token(stream, state.overlay);
  1849. state.overlayPos = stream.pos;
  1850. }
  1851. stream.pos = Math.min(state.basePos, state.overlayPos);
  1852. // state.overlay.combineTokens always takes precedence over combine,
  1853. // unless set to null
  1854. if (state.overlayCur == null) return state.baseCur;
  1855. else if (state.baseCur != null &&
  1856. state.overlay.combineTokens ||
  1857. combine && state.overlay.combineTokens == null)
  1858. return state.baseCur + " " + state.overlayCur;
  1859. else return state.overlayCur;
  1860. },
  1861. indent: base.indent && function(state, textAfter) {
  1862. return base.indent(state.base, textAfter);
  1863. },
  1864. electricChars: base.electricChars,
  1865. innerMode: function(state) { return {state: state.base, mode: base}; },
  1866. blankLine: function(state) {
  1867. if (base.blankLine) base.blankLine(state.base);
  1868. if (overlay.blankLine) overlay.blankLine(state.overlay);
  1869. }
  1870. };
  1871. };
  1872. });
  1873. },{"../../lib/codemirror":10}],9:[function(require,module,exports){
  1874. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  1875. // Distributed under an MIT license: http://codemirror.net/LICENSE
  1876. // Because sometimes you need to mark the selected *text*.
  1877. //
  1878. // Adds an option 'styleSelectedText' which, when enabled, gives
  1879. // selected text the CSS class given as option value, or
  1880. // "CodeMirror-selectedtext" when the value is not a string.
  1881. (function(mod) {
  1882. if (typeof exports == "object" && typeof module == "object") // CommonJS
  1883. mod(require("../../lib/codemirror"));
  1884. else if (typeof define == "function" && define.amd) // AMD
  1885. define(["../../lib/codemirror"], mod);
  1886. else // Plain browser env
  1887. mod(CodeMirror);
  1888. })(function(CodeMirror) {
  1889. "use strict";
  1890. CodeMirror.defineOption("styleSelectedText", false, function(cm, val, old) {
  1891. var prev = old && old != CodeMirror.Init;
  1892. if (val && !prev) {
  1893. cm.state.markedSelection = [];
  1894. cm.state.markedSelectionStyle = typeof val == "string" ? val : "CodeMirror-selectedtext";
  1895. reset(cm);
  1896. cm.on("cursorActivity", onCursorActivity);
  1897. cm.on("change", onChange);
  1898. } else if (!val && prev) {
  1899. cm.off("cursorActivity", onCursorActivity);
  1900. cm.off("change", onChange);
  1901. clear(cm);
  1902. cm.state.markedSelection = cm.state.markedSelectionStyle = null;
  1903. }
  1904. });
  1905. function onCursorActivity(cm) {
  1906. cm.operation(function() { update(cm); });
  1907. }
  1908. function onChange(cm) {
  1909. if (cm.state.markedSelection.length)
  1910. cm.operation(function() { clear(cm); });
  1911. }
  1912. var CHUNK_SIZE = 8;
  1913. var Pos = CodeMirror.Pos;
  1914. var cmp = CodeMirror.cmpPos;
  1915. function coverRange(cm, from, to, addAt) {
  1916. if (cmp(from, to) == 0) return;
  1917. var array = cm.state.markedSelection;
  1918. var cls = cm.state.markedSelectionStyle;
  1919. for (var line = from.line;;) {
  1920. var start = line == from.line ? from : Pos(line, 0);
  1921. var endLine = line + CHUNK_SIZE, atEnd = endLine >= to.line;
  1922. var end = atEnd ? to : Pos(endLine, 0);
  1923. var mark = cm.markText(start, end, {className: cls});
  1924. if (addAt == null) array.push(mark);
  1925. else array.splice(addAt++, 0, mark);
  1926. if (atEnd) break;
  1927. line = endLine;
  1928. }
  1929. }
  1930. function clear(cm) {
  1931. var array = cm.state.markedSelection;
  1932. for (var i = 0; i < array.length; ++i) array[i].clear();
  1933. array.length = 0;
  1934. }
  1935. function reset(cm) {
  1936. clear(cm);
  1937. var ranges = cm.listSelections();
  1938. for (var i = 0; i < ranges.length; i++)
  1939. coverRange(cm, ranges[i].from(), ranges[i].to());
  1940. }
  1941. function update(cm) {
  1942. if (!cm.somethingSelected()) return clear(cm);
  1943. if (cm.listSelections().length > 1) return reset(cm);
  1944. var from = cm.getCursor("start"), to = cm.getCursor("end");
  1945. var array = cm.state.markedSelection;
  1946. if (!array.length) return coverRange(cm, from, to);
  1947. var coverStart = array[0].find(), coverEnd = array[array.length - 1].find();
  1948. if (!coverStart || !coverEnd || to.line - from.line < CHUNK_SIZE ||
  1949. cmp(from, coverEnd.to) >= 0 || cmp(to, coverStart.from) <= 0)
  1950. return reset(cm);
  1951. while (cmp(from, coverStart.from) > 0) {
  1952. array.shift().clear();
  1953. coverStart = array[0].find();
  1954. }
  1955. if (cmp(from, coverStart.from) < 0) {
  1956. if (coverStart.to.line - from.line < CHUNK_SIZE) {
  1957. array.shift().clear();
  1958. coverRange(cm, from, coverStart.to, 0);
  1959. } else {
  1960. coverRange(cm, from, coverStart.from, 0);
  1961. }
  1962. }
  1963. while (cmp(to, coverEnd.to) < 0) {
  1964. array.pop().clear();
  1965. coverEnd = array[array.length - 1].find();
  1966. }
  1967. if (cmp(to, coverEnd.to) > 0) {
  1968. if (to.line - coverEnd.from.line < CHUNK_SIZE) {
  1969. array.pop().clear();
  1970. coverRange(cm, coverEnd.from, to);
  1971. } else {
  1972. coverRange(cm, coverEnd.to, to);
  1973. }
  1974. }
  1975. }
  1976. });
  1977. },{"../../lib/codemirror":10}],10:[function(require,module,exports){
  1978. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  1979. // Distributed under an MIT license: http://codemirror.net/LICENSE
  1980. // This is CodeMirror (http://codemirror.net), a code editor
  1981. // implemented in JavaScript on top of the browser's DOM.
  1982. //
  1983. // You can find some technical background for some of the code below
  1984. // at http://marijnhaverbeke.nl/blog/#cm-internals .
  1985. (function(mod) {
  1986. if (typeof exports == "object" && typeof module == "object") // CommonJS
  1987. module.exports = mod();
  1988. else if (typeof define == "function" && define.amd) // AMD
  1989. return define([], mod);
  1990. else // Plain browser env
  1991. (this || window).CodeMirror = mod();
  1992. })(function() {
  1993. "use strict";
  1994. // BROWSER SNIFFING
  1995. // Kludges for bugs and behavior differences that can't be feature
  1996. // detected are enabled based on userAgent etc sniffing.
  1997. var userAgent = navigator.userAgent;
  1998. var platform = navigator.platform;
  1999. var gecko = /gecko\/\d/i.test(userAgent);
  2000. var ie_upto10 = /MSIE \d/.test(userAgent);
  2001. var ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(userAgent);
  2002. var ie = ie_upto10 || ie_11up;
  2003. var ie_version = ie && (ie_upto10 ? document.documentMode || 6 : ie_11up[1]);
  2004. var webkit = /WebKit\//.test(userAgent);
  2005. var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(userAgent);
  2006. var chrome = /Chrome\//.test(userAgent);
  2007. var presto = /Opera\//.test(userAgent);
  2008. var safari = /Apple Computer/.test(navigator.vendor);
  2009. var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(userAgent);
  2010. var phantom = /PhantomJS/.test(userAgent);
  2011. var ios = /AppleWebKit/.test(userAgent) && /Mobile\/\w+/.test(userAgent);
  2012. // This is woefully incomplete. Suggestions for alternative methods welcome.
  2013. var mobile = ios || /Android|webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(userAgent);
  2014. var mac = ios || /Mac/.test(platform);
  2015. var chromeOS = /\bCrOS\b/.test(userAgent);
  2016. var windows = /win/i.test(platform);
  2017. var presto_version = presto && userAgent.match(/Version\/(\d*\.\d*)/);
  2018. if (presto_version) presto_version = Number(presto_version[1]);
  2019. if (presto_version && presto_version >= 15) { presto = false; webkit = true; }
  2020. // Some browsers use the wrong event properties to signal cmd/ctrl on OS X
  2021. var flipCtrlCmd = mac && (qtwebkit || presto && (presto_version == null || presto_version < 12.11));
  2022. var captureRightClick = gecko || (ie && ie_version >= 9);
  2023. // Optimize some code when these features are not used.
  2024. var sawReadOnlySpans = false, sawCollapsedSpans = false;
  2025. // EDITOR CONSTRUCTOR
  2026. // A CodeMirror instance represents an editor. This is the object
  2027. // that user code is usually dealing with.
  2028. function CodeMirror(place, options) {
  2029. if (!(this instanceof CodeMirror)) return new CodeMirror(place, options);
  2030. this.options = options = options ? copyObj(options) : {};
  2031. // Determine effective options based on given values and defaults.
  2032. copyObj(defaults, options, false);
  2033. setGuttersForLineNumbers(options);
  2034. var doc = options.value;
  2035. if (typeof doc == "string") doc = new Doc(doc, options.mode, null, options.lineSeparator);
  2036. this.doc = doc;
  2037. var input = new CodeMirror.inputStyles[options.inputStyle](this);
  2038. var display = this.display = new Display(place, doc, input);
  2039. display.wrapper.CodeMirror = this;
  2040. updateGutters(this);
  2041. themeChanged(this);
  2042. if (options.lineWrapping)
  2043. this.display.wrapper.className += " CodeMirror-wrap";
  2044. if (options.autofocus && !mobile) display.input.focus();
  2045. initScrollbars(this);
  2046. this.state = {
  2047. keyMaps: [], // stores maps added by addKeyMap
  2048. overlays: [], // highlighting overlays, as added by addOverlay
  2049. modeGen: 0, // bumped when mode/overlay changes, used to invalidate highlighting info
  2050. overwrite: false,
  2051. delayingBlurEvent: false,
  2052. focused: false,
  2053. suppressEdits: false, // used to disable editing during key handlers when in readOnly mode
  2054. pasteIncoming: false, cutIncoming: false, // help recognize paste/cut edits in input.poll
  2055. selectingText: false,
  2056. draggingText: false,
  2057. highlight: new Delayed(), // stores highlight worker timeout
  2058. keySeq: null, // Unfinished key sequence
  2059. specialChars: null
  2060. };
  2061. var cm = this;
  2062. // Override magic textarea content restore that IE sometimes does
  2063. // on our hidden textarea on reload
  2064. if (ie && ie_version < 11) setTimeout(function() { cm.display.input.reset(true); }, 20);
  2065. registerEventHandlers(this);
  2066. ensureGlobalHandlers();
  2067. startOperation(this);
  2068. this.curOp.forceUpdate = true;
  2069. attachDoc(this, doc);
  2070. if ((options.autofocus && !mobile) || cm.hasFocus())
  2071. setTimeout(bind(onFocus, this), 20);
  2072. else
  2073. onBlur(this);
  2074. for (var opt in optionHandlers) if (optionHandlers.hasOwnProperty(opt))
  2075. optionHandlers[opt](this, options[opt], Init);
  2076. maybeUpdateLineNumberWidth(this);
  2077. if (options.finishInit) options.finishInit(this);
  2078. for (var i = 0; i < initHooks.length; ++i) initHooks[i](this);
  2079. endOperation(this);
  2080. // Suppress optimizelegibility in Webkit, since it breaks text
  2081. // measuring on line wrapping boundaries.
  2082. if (webkit && options.lineWrapping &&
  2083. getComputedStyle(display.lineDiv).textRendering == "optimizelegibility")
  2084. display.lineDiv.style.textRendering = "auto";
  2085. }
  2086. // DISPLAY CONSTRUCTOR
  2087. // The display handles the DOM integration, both for input reading
  2088. // and content drawing. It holds references to DOM nodes and
  2089. // display-related state.
  2090. function Display(place, doc, input) {
  2091. var d = this;
  2092. this.input = input;
  2093. // Covers bottom-right square when both scrollbars are present.
  2094. d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler");
  2095. d.scrollbarFiller.setAttribute("cm-not-content", "true");
  2096. // Covers bottom of gutter when coverGutterNextToScrollbar is on
  2097. // and h scrollbar is present.
  2098. d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler");
  2099. d.gutterFiller.setAttribute("cm-not-content", "true");
  2100. // Will contain the actual code, positioned to cover the viewport.
  2101. d.lineDiv = elt("div", null, "CodeMirror-code");
  2102. // Elements are added to these to represent selection and cursors.
  2103. d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1");
  2104. d.cursorDiv = elt("div", null, "CodeMirror-cursors");
  2105. // A visibility: hidden element used to find the size of things.
  2106. d.measure = elt("div", null, "CodeMirror-measure");
  2107. // When lines outside of the viewport are measured, they are drawn in this.
  2108. d.lineMeasure = elt("div", null, "CodeMirror-measure");
  2109. // Wraps everything that needs to exist inside the vertically-padded coordinate system
  2110. d.lineSpace = elt("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv],
  2111. null, "position: relative; outline: none");
  2112. // Moved around its parent to cover visible view.
  2113. d.mover = elt("div", [elt("div", [d.lineSpace], "CodeMirror-lines")], null, "position: relative");
  2114. // Set to the height of the document, allowing scrolling.
  2115. d.sizer = elt("div", [d.mover], "CodeMirror-sizer");
  2116. d.sizerWidth = null;
  2117. // Behavior of elts with overflow: auto and padding is
  2118. // inconsistent across browsers. This is used to ensure the
  2119. // scrollable area is big enough.
  2120. d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerGap + "px; width: 1px;");
  2121. // Will contain the gutters, if any.
  2122. d.gutters = elt("div", null, "CodeMirror-gutters");
  2123. d.lineGutter = null;
  2124. // Actual scrollable element.
  2125. d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll");
  2126. d.scroller.setAttribute("tabIndex", "-1");
  2127. // The element in which the editor lives.
  2128. d.wrapper = elt("div", [d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror");
  2129. // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported)
  2130. if (ie && ie_version < 8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; }
  2131. if (!webkit && !(gecko && mobile)) d.scroller.draggable = true;
  2132. if (place) {
  2133. if (place.appendChild) place.appendChild(d.wrapper);
  2134. else place(d.wrapper);
  2135. }
  2136. // Current rendered range (may be bigger than the view window).
  2137. d.viewFrom = d.viewTo = doc.first;
  2138. d.reportedViewFrom = d.reportedViewTo = doc.first;
  2139. // Information about the rendered lines.
  2140. d.view = [];
  2141. d.renderedView = null;
  2142. // Holds info about a single rendered line when it was rendered
  2143. // for measurement, while not in view.
  2144. d.externalMeasured = null;
  2145. // Empty space (in pixels) above the view
  2146. d.viewOffset = 0;
  2147. d.lastWrapHeight = d.lastWrapWidth = 0;
  2148. d.updateLineNumbers = null;
  2149. d.nativeBarWidth = d.barHeight = d.barWidth = 0;
  2150. d.scrollbarsClipped = false;
  2151. // Used to only resize the line number gutter when necessary (when
  2152. // the amount of lines crosses a boundary that makes its width change)
  2153. d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null;
  2154. // Set to true when a non-horizontal-scrolling line widget is
  2155. // added. As an optimization, line widget aligning is skipped when
  2156. // this is false.
  2157. d.alignWidgets = false;
  2158. d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
  2159. // Tracks the maximum line length so that the horizontal scrollbar
  2160. // can be kept static when scrolling.
  2161. d.maxLine = null;
  2162. d.maxLineLength = 0;
  2163. d.maxLineChanged = false;
  2164. // Used for measuring wheel scrolling granularity
  2165. d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null;
  2166. // True when shift is held down.
  2167. d.shift = false;
  2168. // Used to track whether anything happened since the context menu
  2169. // was opened.
  2170. d.selForContextMenu = null;
  2171. d.activeTouch = null;
  2172. input.init(d);
  2173. }
  2174. // STATE UPDATES
  2175. // Used to get the editor into a consistent state again when options change.
  2176. function loadMode(cm) {
  2177. cm.doc.mode = CodeMirror.getMode(cm.options, cm.doc.modeOption);
  2178. resetModeState(cm);
  2179. }
  2180. function resetModeState(cm) {
  2181. cm.doc.iter(function(line) {
  2182. if (line.stateAfter) line.stateAfter = null;
  2183. if (line.styles) line.styles = null;
  2184. });
  2185. cm.doc.frontier = cm.doc.first;
  2186. startWorker(cm, 100);
  2187. cm.state.modeGen++;
  2188. if (cm.curOp) regChange(cm);
  2189. }
  2190. function wrappingChanged(cm) {
  2191. if (cm.options.lineWrapping) {
  2192. addClass(cm.display.wrapper, "CodeMirror-wrap");
  2193. cm.display.sizer.style.minWidth = "";
  2194. cm.display.sizerWidth = null;
  2195. } else {
  2196. rmClass(cm.display.wrapper, "CodeMirror-wrap");
  2197. findMaxLine(cm);
  2198. }
  2199. estimateLineHeights(cm);
  2200. regChange(cm);
  2201. clearCaches(cm);
  2202. setTimeout(function(){updateScrollbars(cm);}, 100);
  2203. }
  2204. // Returns a function that estimates the height of a line, to use as
  2205. // first approximation until the line becomes visible (and is thus
  2206. // properly measurable).
  2207. function estimateHeight(cm) {
  2208. var th = textHeight(cm.display), wrapping = cm.options.lineWrapping;
  2209. var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3);
  2210. return function(line) {
  2211. if (lineIsHidden(cm.doc, line)) return 0;
  2212. var widgetsHeight = 0;
  2213. if (line.widgets) for (var i = 0; i < line.widgets.length; i++) {
  2214. if (line.widgets[i].height) widgetsHeight += line.widgets[i].height;
  2215. }
  2216. if (wrapping)
  2217. return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th;
  2218. else
  2219. return widgetsHeight + th;
  2220. };
  2221. }
  2222. function estimateLineHeights(cm) {
  2223. var doc = cm.doc, est = estimateHeight(cm);
  2224. doc.iter(function(line) {
  2225. var estHeight = est(line);
  2226. if (estHeight != line.height) updateLineHeight(line, estHeight);
  2227. });
  2228. }
  2229. function themeChanged(cm) {
  2230. cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") +
  2231. cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-");
  2232. clearCaches(cm);
  2233. }
  2234. function guttersChanged(cm) {
  2235. updateGutters(cm);
  2236. regChange(cm);
  2237. setTimeout(function(){alignHorizontally(cm);}, 20);
  2238. }
  2239. // Rebuild the gutter elements, ensure the margin to the left of the
  2240. // code matches their width.
  2241. function updateGutters(cm) {
  2242. var gutters = cm.display.gutters, specs = cm.options.gutters;
  2243. removeChildren(gutters);
  2244. for (var i = 0; i < specs.length; ++i) {
  2245. var gutterClass = specs[i];
  2246. var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + gutterClass));
  2247. if (gutterClass == "CodeMirror-linenumbers") {
  2248. cm.display.lineGutter = gElt;
  2249. gElt.style.width = (cm.display.lineNumWidth || 1) + "px";
  2250. }
  2251. }
  2252. gutters.style.display = i ? "" : "none";
  2253. updateGutterSpace(cm);
  2254. }
  2255. function updateGutterSpace(cm) {
  2256. var width = cm.display.gutters.offsetWidth;
  2257. cm.display.sizer.style.marginLeft = width + "px";
  2258. }
  2259. // Compute the character length of a line, taking into account
  2260. // collapsed ranges (see markText) that might hide parts, and join
  2261. // other lines onto it.
  2262. function lineLength(line) {
  2263. if (line.height == 0) return 0;
  2264. var len = line.text.length, merged, cur = line;
  2265. while (merged = collapsedSpanAtStart(cur)) {
  2266. var found = merged.find(0, true);
  2267. cur = found.from.line;
  2268. len += found.from.ch - found.to.ch;
  2269. }
  2270. cur = line;
  2271. while (merged = collapsedSpanAtEnd(cur)) {
  2272. var found = merged.find(0, true);
  2273. len -= cur.text.length - found.from.ch;
  2274. cur = found.to.line;
  2275. len += cur.text.length - found.to.ch;
  2276. }
  2277. return len;
  2278. }
  2279. // Find the longest line in the document.
  2280. function findMaxLine(cm) {
  2281. var d = cm.display, doc = cm.doc;
  2282. d.maxLine = getLine(doc, doc.first);
  2283. d.maxLineLength = lineLength(d.maxLine);
  2284. d.maxLineChanged = true;
  2285. doc.iter(function(line) {
  2286. var len = lineLength(line);
  2287. if (len > d.maxLineLength) {
  2288. d.maxLineLength = len;
  2289. d.maxLine = line;
  2290. }
  2291. });
  2292. }
  2293. // Make sure the gutters options contains the element
  2294. // "CodeMirror-linenumbers" when the lineNumbers option is true.
  2295. function setGuttersForLineNumbers(options) {
  2296. var found = indexOf(options.gutters, "CodeMirror-linenumbers");
  2297. if (found == -1 && options.lineNumbers) {
  2298. options.gutters = options.gutters.concat(["CodeMirror-linenumbers"]);
  2299. } else if (found > -1 && !options.lineNumbers) {
  2300. options.gutters = options.gutters.slice(0);
  2301. options.gutters.splice(found, 1);
  2302. }
  2303. }
  2304. // SCROLLBARS
  2305. // Prepare DOM reads needed to update the scrollbars. Done in one
  2306. // shot to minimize update/measure roundtrips.
  2307. function measureForScrollbars(cm) {
  2308. var d = cm.display, gutterW = d.gutters.offsetWidth;
  2309. var docH = Math.round(cm.doc.height + paddingVert(cm.display));
  2310. return {
  2311. clientHeight: d.scroller.clientHeight,
  2312. viewHeight: d.wrapper.clientHeight,
  2313. scrollWidth: d.scroller.scrollWidth, clientWidth: d.scroller.clientWidth,
  2314. viewWidth: d.wrapper.clientWidth,
  2315. barLeft: cm.options.fixedGutter ? gutterW : 0,
  2316. docHeight: docH,
  2317. scrollHeight: docH + scrollGap(cm) + d.barHeight,
  2318. nativeBarWidth: d.nativeBarWidth,
  2319. gutterWidth: gutterW
  2320. };
  2321. }
  2322. function NativeScrollbars(place, scroll, cm) {
  2323. this.cm = cm;
  2324. var vert = this.vert = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar");
  2325. var horiz = this.horiz = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar");
  2326. place(vert); place(horiz);
  2327. on(vert, "scroll", function() {
  2328. if (vert.clientHeight) scroll(vert.scrollTop, "vertical");
  2329. });
  2330. on(horiz, "scroll", function() {
  2331. if (horiz.clientWidth) scroll(horiz.scrollLeft, "horizontal");
  2332. });
  2333. this.checkedZeroWidth = false;
  2334. // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8).
  2335. if (ie && ie_version < 8) this.horiz.style.minHeight = this.vert.style.minWidth = "18px";
  2336. }
  2337. NativeScrollbars.prototype = copyObj({
  2338. update: function(measure) {
  2339. var needsH = measure.scrollWidth > measure.clientWidth + 1;
  2340. var needsV = measure.scrollHeight > measure.clientHeight + 1;
  2341. var sWidth = measure.nativeBarWidth;
  2342. if (needsV) {
  2343. this.vert.style.display = "block";
  2344. this.vert.style.bottom = needsH ? sWidth + "px" : "0";
  2345. var totalHeight = measure.viewHeight - (needsH ? sWidth : 0);
  2346. // A bug in IE8 can cause this value to be negative, so guard it.
  2347. this.vert.firstChild.style.height =
  2348. Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + "px";
  2349. } else {
  2350. this.vert.style.display = "";
  2351. this.vert.firstChild.style.height = "0";
  2352. }
  2353. if (needsH) {
  2354. this.horiz.style.display = "block";
  2355. this.horiz.style.right = needsV ? sWidth + "px" : "0";
  2356. this.horiz.style.left = measure.barLeft + "px";
  2357. var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0);
  2358. this.horiz.firstChild.style.width =
  2359. (measure.scrollWidth - measure.clientWidth + totalWidth) + "px";
  2360. } else {
  2361. this.horiz.style.display = "";
  2362. this.horiz.firstChild.style.width = "0";
  2363. }
  2364. if (!this.checkedZeroWidth && measure.clientHeight > 0) {
  2365. if (sWidth == 0) this.zeroWidthHack();
  2366. this.checkedZeroWidth = true;
  2367. }
  2368. return {right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0};
  2369. },
  2370. setScrollLeft: function(pos) {
  2371. if (this.horiz.scrollLeft != pos) this.horiz.scrollLeft = pos;
  2372. if (this.disableHoriz) this.enableZeroWidthBar(this.horiz, this.disableHoriz);
  2373. },
  2374. setScrollTop: function(pos) {
  2375. if (this.vert.scrollTop != pos) this.vert.scrollTop = pos;
  2376. if (this.disableVert) this.enableZeroWidthBar(this.vert, this.disableVert);
  2377. },
  2378. zeroWidthHack: function() {
  2379. var w = mac && !mac_geMountainLion ? "12px" : "18px";
  2380. this.horiz.style.height = this.vert.style.width = w;
  2381. this.horiz.style.pointerEvents = this.vert.style.pointerEvents = "none";
  2382. this.disableHoriz = new Delayed;
  2383. this.disableVert = new Delayed;
  2384. },
  2385. enableZeroWidthBar: function(bar, delay) {
  2386. bar.style.pointerEvents = "auto";
  2387. function maybeDisable() {
  2388. // To find out whether the scrollbar is still visible, we
  2389. // check whether the element under the pixel in the bottom
  2390. // left corner of the scrollbar box is the scrollbar box
  2391. // itself (when the bar is still visible) or its filler child
  2392. // (when the bar is hidden). If it is still visible, we keep
  2393. // it enabled, if it's hidden, we disable pointer events.
  2394. var box = bar.getBoundingClientRect();
  2395. var elt = document.elementFromPoint(box.left + 1, box.bottom - 1);
  2396. if (elt != bar) bar.style.pointerEvents = "none";
  2397. else delay.set(1000, maybeDisable);
  2398. }
  2399. delay.set(1000, maybeDisable);
  2400. },
  2401. clear: function() {
  2402. var parent = this.horiz.parentNode;
  2403. parent.removeChild(this.horiz);
  2404. parent.removeChild(this.vert);
  2405. }
  2406. }, NativeScrollbars.prototype);
  2407. function NullScrollbars() {}
  2408. NullScrollbars.prototype = copyObj({
  2409. update: function() { return {bottom: 0, right: 0}; },
  2410. setScrollLeft: function() {},
  2411. setScrollTop: function() {},
  2412. clear: function() {}
  2413. }, NullScrollbars.prototype);
  2414. CodeMirror.scrollbarModel = {"native": NativeScrollbars, "null": NullScrollbars};
  2415. function initScrollbars(cm) {
  2416. if (cm.display.scrollbars) {
  2417. cm.display.scrollbars.clear();
  2418. if (cm.display.scrollbars.addClass)
  2419. rmClass(cm.display.wrapper, cm.display.scrollbars.addClass);
  2420. }
  2421. cm.display.scrollbars = new CodeMirror.scrollbarModel[cm.options.scrollbarStyle](function(node) {
  2422. cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller);
  2423. // Prevent clicks in the scrollbars from killing focus
  2424. on(node, "mousedown", function() {
  2425. if (cm.state.focused) setTimeout(function() { cm.display.input.focus(); }, 0);
  2426. });
  2427. node.setAttribute("cm-not-content", "true");
  2428. }, function(pos, axis) {
  2429. if (axis == "horizontal") setScrollLeft(cm, pos);
  2430. else setScrollTop(cm, pos);
  2431. }, cm);
  2432. if (cm.display.scrollbars.addClass)
  2433. addClass(cm.display.wrapper, cm.display.scrollbars.addClass);
  2434. }
  2435. function updateScrollbars(cm, measure) {
  2436. if (!measure) measure = measureForScrollbars(cm);
  2437. var startWidth = cm.display.barWidth, startHeight = cm.display.barHeight;
  2438. updateScrollbarsInner(cm, measure);
  2439. for (var i = 0; i < 4 && startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i++) {
  2440. if (startWidth != cm.display.barWidth && cm.options.lineWrapping)
  2441. updateHeightsInViewport(cm);
  2442. updateScrollbarsInner(cm, measureForScrollbars(cm));
  2443. startWidth = cm.display.barWidth; startHeight = cm.display.barHeight;
  2444. }
  2445. }
  2446. // Re-synchronize the fake scrollbars with the actual size of the
  2447. // content.
  2448. function updateScrollbarsInner(cm, measure) {
  2449. var d = cm.display;
  2450. var sizes = d.scrollbars.update(measure);
  2451. d.sizer.style.paddingRight = (d.barWidth = sizes.right) + "px";
  2452. d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + "px";
  2453. d.heightForcer.style.borderBottom = sizes.bottom + "px solid transparent"
  2454. if (sizes.right && sizes.bottom) {
  2455. d.scrollbarFiller.style.display = "block";
  2456. d.scrollbarFiller.style.height = sizes.bottom + "px";
  2457. d.scrollbarFiller.style.width = sizes.right + "px";
  2458. } else d.scrollbarFiller.style.display = "";
  2459. if (sizes.bottom && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) {
  2460. d.gutterFiller.style.display = "block";
  2461. d.gutterFiller.style.height = sizes.bottom + "px";
  2462. d.gutterFiller.style.width = measure.gutterWidth + "px";
  2463. } else d.gutterFiller.style.display = "";
  2464. }
  2465. // Compute the lines that are visible in a given viewport (defaults
  2466. // the the current scroll position). viewport may contain top,
  2467. // height, and ensure (see op.scrollToPos) properties.
  2468. function visibleLines(display, doc, viewport) {
  2469. var top = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop;
  2470. top = Math.floor(top - paddingTop(display));
  2471. var bottom = viewport && viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight;
  2472. var from = lineAtHeight(doc, top), to = lineAtHeight(doc, bottom);
  2473. // Ensure is a {from: {line, ch}, to: {line, ch}} object, and
  2474. // forces those lines into the viewport (if possible).
  2475. if (viewport && viewport.ensure) {
  2476. var ensureFrom = viewport.ensure.from.line, ensureTo = viewport.ensure.to.line;
  2477. if (ensureFrom < from) {
  2478. from = ensureFrom;
  2479. to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight);
  2480. } else if (Math.min(ensureTo, doc.lastLine()) >= to) {
  2481. from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight);
  2482. to = ensureTo;
  2483. }
  2484. }
  2485. return {from: from, to: Math.max(to, from + 1)};
  2486. }
  2487. // LINE NUMBERS
  2488. // Re-align line numbers and gutter marks to compensate for
  2489. // horizontal scrolling.
  2490. function alignHorizontally(cm) {
  2491. var display = cm.display, view = display.view;
  2492. if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) return;
  2493. var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft;
  2494. var gutterW = display.gutters.offsetWidth, left = comp + "px";
  2495. for (var i = 0; i < view.length; i++) if (!view[i].hidden) {
  2496. if (cm.options.fixedGutter && view[i].gutter)
  2497. view[i].gutter.style.left = left;
  2498. var align = view[i].alignable;
  2499. if (align) for (var j = 0; j < align.length; j++)
  2500. align[j].style.left = left;
  2501. }
  2502. if (cm.options.fixedGutter)
  2503. display.gutters.style.left = (comp + gutterW) + "px";
  2504. }
  2505. // Used to ensure that the line number gutter is still the right
  2506. // size for the current document size. Returns true when an update
  2507. // is needed.
  2508. function maybeUpdateLineNumberWidth(cm) {
  2509. if (!cm.options.lineNumbers) return false;
  2510. var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display;
  2511. if (last.length != display.lineNumChars) {
  2512. var test = display.measure.appendChild(elt("div", [elt("div", last)],
  2513. "CodeMirror-linenumber CodeMirror-gutter-elt"));
  2514. var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW;
  2515. display.lineGutter.style.width = "";
  2516. display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding) + 1;
  2517. display.lineNumWidth = display.lineNumInnerWidth + padding;
  2518. display.lineNumChars = display.lineNumInnerWidth ? last.length : -1;
  2519. display.lineGutter.style.width = display.lineNumWidth + "px";
  2520. updateGutterSpace(cm);
  2521. return true;
  2522. }
  2523. return false;
  2524. }
  2525. function lineNumberFor(options, i) {
  2526. return String(options.lineNumberFormatter(i + options.firstLineNumber));
  2527. }
  2528. // Computes display.scroller.scrollLeft + display.gutters.offsetWidth,
  2529. // but using getBoundingClientRect to get a sub-pixel-accurate
  2530. // result.
  2531. function compensateForHScroll(display) {
  2532. return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left;
  2533. }
  2534. // DISPLAY DRAWING
  2535. function DisplayUpdate(cm, viewport, force) {
  2536. var display = cm.display;
  2537. this.viewport = viewport;
  2538. // Store some values that we'll need later (but don't want to force a relayout for)
  2539. this.visible = visibleLines(display, cm.doc, viewport);
  2540. this.editorIsHidden = !display.wrapper.offsetWidth;
  2541. this.wrapperHeight = display.wrapper.clientHeight;
  2542. this.wrapperWidth = display.wrapper.clientWidth;
  2543. this.oldDisplayWidth = displayWidth(cm);
  2544. this.force = force;
  2545. this.dims = getDimensions(cm);
  2546. this.events = [];
  2547. }
  2548. DisplayUpdate.prototype.signal = function(emitter, type) {
  2549. if (hasHandler(emitter, type))
  2550. this.events.push(arguments);
  2551. };
  2552. DisplayUpdate.prototype.finish = function() {
  2553. for (var i = 0; i < this.events.length; i++)
  2554. signal.apply(null, this.events[i]);
  2555. };
  2556. function maybeClipScrollbars(cm) {
  2557. var display = cm.display;
  2558. if (!display.scrollbarsClipped && display.scroller.offsetWidth) {
  2559. display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth;
  2560. display.heightForcer.style.height = scrollGap(cm) + "px";
  2561. display.sizer.style.marginBottom = -display.nativeBarWidth + "px";
  2562. display.sizer.style.borderRightWidth = scrollGap(cm) + "px";
  2563. display.scrollbarsClipped = true;
  2564. }
  2565. }
  2566. // Does the actual updating of the line display. Bails out
  2567. // (returning false) when there is nothing to be done and forced is
  2568. // false.
  2569. function updateDisplayIfNeeded(cm, update) {
  2570. var display = cm.display, doc = cm.doc;
  2571. if (update.editorIsHidden) {
  2572. resetView(cm);
  2573. return false;
  2574. }
  2575. // Bail out if the visible area is already rendered and nothing changed.
  2576. if (!update.force &&
  2577. update.visible.from >= display.viewFrom && update.visible.to <= display.viewTo &&
  2578. (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) &&
  2579. display.renderedView == display.view && countDirtyView(cm) == 0)
  2580. return false;
  2581. if (maybeUpdateLineNumberWidth(cm)) {
  2582. resetView(cm);
  2583. update.dims = getDimensions(cm);
  2584. }
  2585. // Compute a suitable new viewport (from & to)
  2586. var end = doc.first + doc.size;
  2587. var from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first);
  2588. var to = Math.min(end, update.visible.to + cm.options.viewportMargin);
  2589. if (display.viewFrom < from && from - display.viewFrom < 20) from = Math.max(doc.first, display.viewFrom);
  2590. if (display.viewTo > to && display.viewTo - to < 20) to = Math.min(end, display.viewTo);
  2591. if (sawCollapsedSpans) {
  2592. from = visualLineNo(cm.doc, from);
  2593. to = visualLineEndNo(cm.doc, to);
  2594. }
  2595. var different = from != display.viewFrom || to != display.viewTo ||
  2596. display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth;
  2597. adjustView(cm, from, to);
  2598. display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom));
  2599. // Position the mover div to align with the current scroll position
  2600. cm.display.mover.style.top = display.viewOffset + "px";
  2601. var toUpdate = countDirtyView(cm);
  2602. if (!different && toUpdate == 0 && !update.force && display.renderedView == display.view &&
  2603. (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo))
  2604. return false;
  2605. // For big changes, we hide the enclosing element during the
  2606. // update, since that speeds up the operations on most browsers.
  2607. var focused = activeElt();
  2608. if (toUpdate > 4) display.lineDiv.style.display = "none";
  2609. patchDisplay(cm, display.updateLineNumbers, update.dims);
  2610. if (toUpdate > 4) display.lineDiv.style.display = "";
  2611. display.renderedView = display.view;
  2612. // There might have been a widget with a focused element that got
  2613. // hidden or updated, if so re-focus it.
  2614. if (focused && activeElt() != focused && focused.offsetHeight) focused.focus();
  2615. // Prevent selection and cursors from interfering with the scroll
  2616. // width and height.
  2617. removeChildren(display.cursorDiv);
  2618. removeChildren(display.selectionDiv);
  2619. display.gutters.style.height = display.sizer.style.minHeight = 0;
  2620. if (different) {
  2621. display.lastWrapHeight = update.wrapperHeight;
  2622. display.lastWrapWidth = update.wrapperWidth;
  2623. startWorker(cm, 400);
  2624. }
  2625. display.updateLineNumbers = null;
  2626. return true;
  2627. }
  2628. function postUpdateDisplay(cm, update) {
  2629. var viewport = update.viewport;
  2630. for (var first = true;; first = false) {
  2631. if (!first || !cm.options.lineWrapping || update.oldDisplayWidth == displayWidth(cm)) {
  2632. // Clip forced viewport to actual scrollable area.
  2633. if (viewport && viewport.top != null)
  2634. viewport = {top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top)};
  2635. // Updated line heights might result in the drawn area not
  2636. // actually covering the viewport. Keep looping until it does.
  2637. update.visible = visibleLines(cm.display, cm.doc, viewport);
  2638. if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo)
  2639. break;
  2640. }
  2641. if (!updateDisplayIfNeeded(cm, update)) break;
  2642. updateHeightsInViewport(cm);
  2643. var barMeasure = measureForScrollbars(cm);
  2644. updateSelection(cm);
  2645. updateScrollbars(cm, barMeasure);
  2646. setDocumentHeight(cm, barMeasure);
  2647. }
  2648. update.signal(cm, "update", cm);
  2649. if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) {
  2650. update.signal(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo);
  2651. cm.display.reportedViewFrom = cm.display.viewFrom; cm.display.reportedViewTo = cm.display.viewTo;
  2652. }
  2653. }
  2654. function updateDisplaySimple(cm, viewport) {
  2655. var update = new DisplayUpdate(cm, viewport);
  2656. if (updateDisplayIfNeeded(cm, update)) {
  2657. updateHeightsInViewport(cm);
  2658. postUpdateDisplay(cm, update);
  2659. var barMeasure = measureForScrollbars(cm);
  2660. updateSelection(cm);
  2661. updateScrollbars(cm, barMeasure);
  2662. setDocumentHeight(cm, barMeasure);
  2663. update.finish();
  2664. }
  2665. }
  2666. function setDocumentHeight(cm, measure) {
  2667. cm.display.sizer.style.minHeight = measure.docHeight + "px";
  2668. cm.display.heightForcer.style.top = measure.docHeight + "px";
  2669. cm.display.gutters.style.height = (measure.docHeight + cm.display.barHeight + scrollGap(cm)) + "px";
  2670. }
  2671. // Read the actual heights of the rendered lines, and update their
  2672. // stored heights to match.
  2673. function updateHeightsInViewport(cm) {
  2674. var display = cm.display;
  2675. var prevBottom = display.lineDiv.offsetTop;
  2676. for (var i = 0; i < display.view.length; i++) {
  2677. var cur = display.view[i], height;
  2678. if (cur.hidden) continue;
  2679. if (ie && ie_version < 8) {
  2680. var bot = cur.node.offsetTop + cur.node.offsetHeight;
  2681. height = bot - prevBottom;
  2682. prevBottom = bot;
  2683. } else {
  2684. var box = cur.node.getBoundingClientRect();
  2685. height = box.bottom - box.top;
  2686. }
  2687. var diff = cur.line.height - height;
  2688. if (height < 2) height = textHeight(display);
  2689. if (diff > .001 || diff < -.001) {
  2690. updateLineHeight(cur.line, height);
  2691. updateWidgetHeight(cur.line);
  2692. if (cur.rest) for (var j = 0; j < cur.rest.length; j++)
  2693. updateWidgetHeight(cur.rest[j]);
  2694. }
  2695. }
  2696. }
  2697. // Read and store the height of line widgets associated with the
  2698. // given line.
  2699. function updateWidgetHeight(line) {
  2700. if (line.widgets) for (var i = 0; i < line.widgets.length; ++i)
  2701. line.widgets[i].height = line.widgets[i].node.parentNode.offsetHeight;
  2702. }
  2703. // Do a bulk-read of the DOM positions and sizes needed to draw the
  2704. // view, so that we don't interleave reading and writing to the DOM.
  2705. function getDimensions(cm) {
  2706. var d = cm.display, left = {}, width = {};
  2707. var gutterLeft = d.gutters.clientLeft;
  2708. for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) {
  2709. left[cm.options.gutters[i]] = n.offsetLeft + n.clientLeft + gutterLeft;
  2710. width[cm.options.gutters[i]] = n.clientWidth;
  2711. }
  2712. return {fixedPos: compensateForHScroll(d),
  2713. gutterTotalWidth: d.gutters.offsetWidth,
  2714. gutterLeft: left,
  2715. gutterWidth: width,
  2716. wrapperWidth: d.wrapper.clientWidth};
  2717. }
  2718. // Sync the actual display DOM structure with display.view, removing
  2719. // nodes for lines that are no longer in view, and creating the ones
  2720. // that are not there yet, and updating the ones that are out of
  2721. // date.
  2722. function patchDisplay(cm, updateNumbersFrom, dims) {
  2723. var display = cm.display, lineNumbers = cm.options.lineNumbers;
  2724. var container = display.lineDiv, cur = container.firstChild;
  2725. function rm(node) {
  2726. var next = node.nextSibling;
  2727. // Works around a throw-scroll bug in OS X Webkit
  2728. if (webkit && mac && cm.display.currentWheelTarget == node)
  2729. node.style.display = "none";
  2730. else
  2731. node.parentNode.removeChild(node);
  2732. return next;
  2733. }
  2734. var view = display.view, lineN = display.viewFrom;
  2735. // Loop over the elements in the view, syncing cur (the DOM nodes
  2736. // in display.lineDiv) with the view as we go.
  2737. for (var i = 0; i < view.length; i++) {
  2738. var lineView = view[i];
  2739. if (lineView.hidden) {
  2740. } else if (!lineView.node || lineView.node.parentNode != container) { // Not drawn yet
  2741. var node = buildLineElement(cm, lineView, lineN, dims);
  2742. container.insertBefore(node, cur);
  2743. } else { // Already drawn
  2744. while (cur != lineView.node) cur = rm(cur);
  2745. var updateNumber = lineNumbers && updateNumbersFrom != null &&
  2746. updateNumbersFrom <= lineN && lineView.lineNumber;
  2747. if (lineView.changes) {
  2748. if (indexOf(lineView.changes, "gutter") > -1) updateNumber = false;
  2749. updateLineForChanges(cm, lineView, lineN, dims);
  2750. }
  2751. if (updateNumber) {
  2752. removeChildren(lineView.lineNumber);
  2753. lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN)));
  2754. }
  2755. cur = lineView.node.nextSibling;
  2756. }
  2757. lineN += lineView.size;
  2758. }
  2759. while (cur) cur = rm(cur);
  2760. }
  2761. // When an aspect of a line changes, a string is added to
  2762. // lineView.changes. This updates the relevant part of the line's
  2763. // DOM structure.
  2764. function updateLineForChanges(cm, lineView, lineN, dims) {
  2765. for (var j = 0; j < lineView.changes.length; j++) {
  2766. var type = lineView.changes[j];
  2767. if (type == "text") updateLineText(cm, lineView);
  2768. else if (type == "gutter") updateLineGutter(cm, lineView, lineN, dims);
  2769. else if (type == "class") updateLineClasses(lineView);
  2770. else if (type == "widget") updateLineWidgets(cm, lineView, dims);
  2771. }
  2772. lineView.changes = null;
  2773. }
  2774. // Lines with gutter elements, widgets or a background class need to
  2775. // be wrapped, and have the extra elements added to the wrapper div
  2776. function ensureLineWrapped(lineView) {
  2777. if (lineView.node == lineView.text) {
  2778. lineView.node = elt("div", null, null, "position: relative");
  2779. if (lineView.text.parentNode)
  2780. lineView.text.parentNode.replaceChild(lineView.node, lineView.text);
  2781. lineView.node.appendChild(lineView.text);
  2782. if (ie && ie_version < 8) lineView.node.style.zIndex = 2;
  2783. }
  2784. return lineView.node;
  2785. }
  2786. function updateLineBackground(lineView) {
  2787. var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass;
  2788. if (cls) cls += " CodeMirror-linebackground";
  2789. if (lineView.background) {
  2790. if (cls) lineView.background.className = cls;
  2791. else { lineView.background.parentNode.removeChild(lineView.background); lineView.background = null; }
  2792. } else if (cls) {
  2793. var wrap = ensureLineWrapped(lineView);
  2794. lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild);
  2795. }
  2796. }
  2797. // Wrapper around buildLineContent which will reuse the structure
  2798. // in display.externalMeasured when possible.
  2799. function getLineContent(cm, lineView) {
  2800. var ext = cm.display.externalMeasured;
  2801. if (ext && ext.line == lineView.line) {
  2802. cm.display.externalMeasured = null;
  2803. lineView.measure = ext.measure;
  2804. return ext.built;
  2805. }
  2806. return buildLineContent(cm, lineView);
  2807. }
  2808. // Redraw the line's text. Interacts with the background and text
  2809. // classes because the mode may output tokens that influence these
  2810. // classes.
  2811. function updateLineText(cm, lineView) {
  2812. var cls = lineView.text.className;
  2813. var built = getLineContent(cm, lineView);
  2814. if (lineView.text == lineView.node) lineView.node = built.pre;
  2815. lineView.text.parentNode.replaceChild(built.pre, lineView.text);
  2816. lineView.text = built.pre;
  2817. if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) {
  2818. lineView.bgClass = built.bgClass;
  2819. lineView.textClass = built.textClass;
  2820. updateLineClasses(lineView);
  2821. } else if (cls) {
  2822. lineView.text.className = cls;
  2823. }
  2824. }
  2825. function updateLineClasses(lineView) {
  2826. updateLineBackground(lineView);
  2827. if (lineView.line.wrapClass)
  2828. ensureLineWrapped(lineView).className = lineView.line.wrapClass;
  2829. else if (lineView.node != lineView.text)
  2830. lineView.node.className = "";
  2831. var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass;
  2832. lineView.text.className = textClass || "";
  2833. }
  2834. function updateLineGutter(cm, lineView, lineN, dims) {
  2835. if (lineView.gutter) {
  2836. lineView.node.removeChild(lineView.gutter);
  2837. lineView.gutter = null;
  2838. }
  2839. if (lineView.gutterBackground) {
  2840. lineView.node.removeChild(lineView.gutterBackground);
  2841. lineView.gutterBackground = null;
  2842. }
  2843. if (lineView.line.gutterClass) {
  2844. var wrap = ensureLineWrapped(lineView);
  2845. lineView.gutterBackground = elt("div", null, "CodeMirror-gutter-background " + lineView.line.gutterClass,
  2846. "left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) +
  2847. "px; width: " + dims.gutterTotalWidth + "px");
  2848. wrap.insertBefore(lineView.gutterBackground, lineView.text);
  2849. }
  2850. var markers = lineView.line.gutterMarkers;
  2851. if (cm.options.lineNumbers || markers) {
  2852. var wrap = ensureLineWrapped(lineView);
  2853. var gutterWrap = lineView.gutter = elt("div", null, "CodeMirror-gutter-wrapper", "left: " +
  2854. (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px");
  2855. cm.display.input.setUneditable(gutterWrap);
  2856. wrap.insertBefore(gutterWrap, lineView.text);
  2857. if (lineView.line.gutterClass)
  2858. gutterWrap.className += " " + lineView.line.gutterClass;
  2859. if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"]))
  2860. lineView.lineNumber = gutterWrap.appendChild(
  2861. elt("div", lineNumberFor(cm.options, lineN),
  2862. "CodeMirror-linenumber CodeMirror-gutter-elt",
  2863. "left: " + dims.gutterLeft["CodeMirror-linenumbers"] + "px; width: "
  2864. + cm.display.lineNumInnerWidth + "px"));
  2865. if (markers) for (var k = 0; k < cm.options.gutters.length; ++k) {
  2866. var id = cm.options.gutters[k], found = markers.hasOwnProperty(id) && markers[id];
  2867. if (found)
  2868. gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt", "left: " +
  2869. dims.gutterLeft[id] + "px; width: " + dims.gutterWidth[id] + "px"));
  2870. }
  2871. }
  2872. }
  2873. function updateLineWidgets(cm, lineView, dims) {
  2874. if (lineView.alignable) lineView.alignable = null;
  2875. for (var node = lineView.node.firstChild, next; node; node = next) {
  2876. var next = node.nextSibling;
  2877. if (node.className == "CodeMirror-linewidget")
  2878. lineView.node.removeChild(node);
  2879. }
  2880. insertLineWidgets(cm, lineView, dims);
  2881. }
  2882. // Build a line's DOM representation from scratch
  2883. function buildLineElement(cm, lineView, lineN, dims) {
  2884. var built = getLineContent(cm, lineView);
  2885. lineView.text = lineView.node = built.pre;
  2886. if (built.bgClass) lineView.bgClass = built.bgClass;
  2887. if (built.textClass) lineView.textClass = built.textClass;
  2888. updateLineClasses(lineView);
  2889. updateLineGutter(cm, lineView, lineN, dims);
  2890. insertLineWidgets(cm, lineView, dims);
  2891. return lineView.node;
  2892. }
  2893. // A lineView may contain multiple logical lines (when merged by
  2894. // collapsed spans). The widgets for all of them need to be drawn.
  2895. function insertLineWidgets(cm, lineView, dims) {
  2896. insertLineWidgetsFor(cm, lineView.line, lineView, dims, true);
  2897. if (lineView.rest) for (var i = 0; i < lineView.rest.length; i++)
  2898. insertLineWidgetsFor(cm, lineView.rest[i], lineView, dims, false);
  2899. }
  2900. function insertLineWidgetsFor(cm, line, lineView, dims, allowAbove) {
  2901. if (!line.widgets) return;
  2902. var wrap = ensureLineWrapped(lineView);
  2903. for (var i = 0, ws = line.widgets; i < ws.length; ++i) {
  2904. var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget");
  2905. if (!widget.handleMouseEvents) node.setAttribute("cm-ignore-events", "true");
  2906. positionLineWidget(widget, node, lineView, dims);
  2907. cm.display.input.setUneditable(node);
  2908. if (allowAbove && widget.above)
  2909. wrap.insertBefore(node, lineView.gutter || lineView.text);
  2910. else
  2911. wrap.appendChild(node);
  2912. signalLater(widget, "redraw");
  2913. }
  2914. }
  2915. function positionLineWidget(widget, node, lineView, dims) {
  2916. if (widget.noHScroll) {
  2917. (lineView.alignable || (lineView.alignable = [])).push(node);
  2918. var width = dims.wrapperWidth;
  2919. node.style.left = dims.fixedPos + "px";
  2920. if (!widget.coverGutter) {
  2921. width -= dims.gutterTotalWidth;
  2922. node.style.paddingLeft = dims.gutterTotalWidth + "px";
  2923. }
  2924. node.style.width = width + "px";
  2925. }
  2926. if (widget.coverGutter) {
  2927. node.style.zIndex = 5;
  2928. node.style.position = "relative";
  2929. if (!widget.noHScroll) node.style.marginLeft = -dims.gutterTotalWidth + "px";
  2930. }
  2931. }
  2932. // POSITION OBJECT
  2933. // A Pos instance represents a position within the text.
  2934. var Pos = CodeMirror.Pos = function(line, ch) {
  2935. if (!(this instanceof Pos)) return new Pos(line, ch);
  2936. this.line = line; this.ch = ch;
  2937. };
  2938. // Compare two positions, return 0 if they are the same, a negative
  2939. // number when a is less, and a positive number otherwise.
  2940. var cmp = CodeMirror.cmpPos = function(a, b) { return a.line - b.line || a.ch - b.ch; };
  2941. function copyPos(x) {return Pos(x.line, x.ch);}
  2942. function maxPos(a, b) { return cmp(a, b) < 0 ? b : a; }
  2943. function minPos(a, b) { return cmp(a, b) < 0 ? a : b; }
  2944. // INPUT HANDLING
  2945. function ensureFocus(cm) {
  2946. if (!cm.state.focused) { cm.display.input.focus(); onFocus(cm); }
  2947. }
  2948. // This will be set to a {lineWise: bool, text: [string]} object, so
  2949. // that, when pasting, we know what kind of selections the copied
  2950. // text was made out of.
  2951. var lastCopied = null;
  2952. function applyTextInput(cm, inserted, deleted, sel, origin) {
  2953. var doc = cm.doc;
  2954. cm.display.shift = false;
  2955. if (!sel) sel = doc.sel;
  2956. var paste = cm.state.pasteIncoming || origin == "paste";
  2957. var textLines = doc.splitLines(inserted), multiPaste = null
  2958. // When pasing N lines into N selections, insert one line per selection
  2959. if (paste && sel.ranges.length > 1) {
  2960. if (lastCopied && lastCopied.text.join("\n") == inserted) {
  2961. if (sel.ranges.length % lastCopied.text.length == 0) {
  2962. multiPaste = [];
  2963. for (var i = 0; i < lastCopied.text.length; i++)
  2964. multiPaste.push(doc.splitLines(lastCopied.text[i]));
  2965. }
  2966. } else if (textLines.length == sel.ranges.length) {
  2967. multiPaste = map(textLines, function(l) { return [l]; });
  2968. }
  2969. }
  2970. // Normal behavior is to insert the new text into every selection
  2971. for (var i = sel.ranges.length - 1; i >= 0; i--) {
  2972. var range = sel.ranges[i];
  2973. var from = range.from(), to = range.to();
  2974. if (range.empty()) {
  2975. if (deleted && deleted > 0) // Handle deletion
  2976. from = Pos(from.line, from.ch - deleted);
  2977. else if (cm.state.overwrite && !paste) // Handle overwrite
  2978. to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length));
  2979. else if (lastCopied && lastCopied.lineWise && lastCopied.text.join("\n") == inserted)
  2980. from = to = Pos(from.line, 0)
  2981. }
  2982. var updateInput = cm.curOp.updateInput;
  2983. var changeEvent = {from: from, to: to, text: multiPaste ? multiPaste[i % multiPaste.length] : textLines,
  2984. origin: origin || (paste ? "paste" : cm.state.cutIncoming ? "cut" : "+input")};
  2985. makeChange(cm.doc, changeEvent);
  2986. signalLater(cm, "inputRead", cm, changeEvent);
  2987. }
  2988. if (inserted && !paste)
  2989. triggerElectric(cm, inserted);
  2990. ensureCursorVisible(cm);
  2991. cm.curOp.updateInput = updateInput;
  2992. cm.curOp.typing = true;
  2993. cm.state.pasteIncoming = cm.state.cutIncoming = false;
  2994. }
  2995. function handlePaste(e, cm) {
  2996. var pasted = e.clipboardData && e.clipboardData.getData("text/plain");
  2997. if (pasted) {
  2998. e.preventDefault();
  2999. if (!cm.isReadOnly() && !cm.options.disableInput)
  3000. runInOp(cm, function() { applyTextInput(cm, pasted, 0, null, "paste"); });
  3001. return true;
  3002. }
  3003. }
  3004. function triggerElectric(cm, inserted) {
  3005. // When an 'electric' character is inserted, immediately trigger a reindent
  3006. if (!cm.options.electricChars || !cm.options.smartIndent) return;
  3007. var sel = cm.doc.sel;
  3008. for (var i = sel.ranges.length - 1; i >= 0; i--) {
  3009. var range = sel.ranges[i];
  3010. if (range.head.ch > 100 || (i && sel.ranges[i - 1].head.line == range.head.line)) continue;
  3011. var mode = cm.getModeAt(range.head);
  3012. var indented = false;
  3013. if (mode.electricChars) {
  3014. for (var j = 0; j < mode.electricChars.length; j++)
  3015. if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) {
  3016. indented = indentLine(cm, range.head.line, "smart");
  3017. break;
  3018. }
  3019. } else if (mode.electricInput) {
  3020. if (mode.electricInput.test(getLine(cm.doc, range.head.line).text.slice(0, range.head.ch)))
  3021. indented = indentLine(cm, range.head.line, "smart");
  3022. }
  3023. if (indented) signalLater(cm, "electricInput", cm, range.head.line);
  3024. }
  3025. }
  3026. function copyableRanges(cm) {
  3027. var text = [], ranges = [];
  3028. for (var i = 0; i < cm.doc.sel.ranges.length; i++) {
  3029. var line = cm.doc.sel.ranges[i].head.line;
  3030. var lineRange = {anchor: Pos(line, 0), head: Pos(line + 1, 0)};
  3031. ranges.push(lineRange);
  3032. text.push(cm.getRange(lineRange.anchor, lineRange.head));
  3033. }
  3034. return {text: text, ranges: ranges};
  3035. }
  3036. function disableBrowserMagic(field) {
  3037. field.setAttribute("autocorrect", "off");
  3038. field.setAttribute("autocapitalize", "off");
  3039. field.setAttribute("spellcheck", "false");
  3040. }
  3041. // TEXTAREA INPUT STYLE
  3042. function TextareaInput(cm) {
  3043. this.cm = cm;
  3044. // See input.poll and input.reset
  3045. this.prevInput = "";
  3046. // Flag that indicates whether we expect input to appear real soon
  3047. // now (after some event like 'keypress' or 'input') and are
  3048. // polling intensively.
  3049. this.pollingFast = false;
  3050. // Self-resetting timeout for the poller
  3051. this.polling = new Delayed();
  3052. // Tracks when input.reset has punted to just putting a short
  3053. // string into the textarea instead of the full selection.
  3054. this.inaccurateSelection = false;
  3055. // Used to work around IE issue with selection being forgotten when focus moves away from textarea
  3056. this.hasSelection = false;
  3057. this.composing = null;
  3058. };
  3059. function hiddenTextarea() {
  3060. var te = elt("textarea", null, null, "position: absolute; bottom: -1em; padding: 0; width: 1px; height: 1em; outline: none");
  3061. var div = elt("div", [te], null, "overflow: hidden; position: relative; width: 3px; height: 0px;");
  3062. // The textarea is kept positioned near the cursor to prevent the
  3063. // fact that it'll be scrolled into view on input from scrolling
  3064. // our fake cursor out of view. On webkit, when wrap=off, paste is
  3065. // very slow. So make the area wide instead.
  3066. if (webkit) te.style.width = "1000px";
  3067. else te.setAttribute("wrap", "off");
  3068. // If border: 0; -- iOS fails to open keyboard (issue #1287)
  3069. if (ios) te.style.border = "1px solid black";
  3070. disableBrowserMagic(te);
  3071. return div;
  3072. }
  3073. TextareaInput.prototype = copyObj({
  3074. init: function(display) {
  3075. var input = this, cm = this.cm;
  3076. // Wraps and hides input textarea
  3077. var div = this.wrapper = hiddenTextarea();
  3078. // The semihidden textarea that is focused when the editor is
  3079. // focused, and receives input.
  3080. var te = this.textarea = div.firstChild;
  3081. display.wrapper.insertBefore(div, display.wrapper.firstChild);
  3082. // Needed to hide big blue blinking cursor on Mobile Safari (doesn't seem to work in iOS 8 anymore)
  3083. if (ios) te.style.width = "0px";
  3084. on(te, "input", function() {
  3085. if (ie && ie_version >= 9 && input.hasSelection) input.hasSelection = null;
  3086. input.poll();
  3087. });
  3088. on(te, "paste", function(e) {
  3089. if (signalDOMEvent(cm, e) || handlePaste(e, cm)) return
  3090. cm.state.pasteIncoming = true;
  3091. input.fastPoll();
  3092. });
  3093. function prepareCopyCut(e) {
  3094. if (signalDOMEvent(cm, e)) return
  3095. if (cm.somethingSelected()) {
  3096. lastCopied = {lineWise: false, text: cm.getSelections()};
  3097. if (input.inaccurateSelection) {
  3098. input.prevInput = "";
  3099. input.inaccurateSelection = false;
  3100. te.value = lastCopied.text.join("\n");
  3101. selectInput(te);
  3102. }
  3103. } else if (!cm.options.lineWiseCopyCut) {
  3104. return;
  3105. } else {
  3106. var ranges = copyableRanges(cm);
  3107. lastCopied = {lineWise: true, text: ranges.text};
  3108. if (e.type == "cut") {
  3109. cm.setSelections(ranges.ranges, null, sel_dontScroll);
  3110. } else {
  3111. input.prevInput = "";
  3112. te.value = ranges.text.join("\n");
  3113. selectInput(te);
  3114. }
  3115. }
  3116. if (e.type == "cut") cm.state.cutIncoming = true;
  3117. }
  3118. on(te, "cut", prepareCopyCut);
  3119. on(te, "copy", prepareCopyCut);
  3120. on(display.scroller, "paste", function(e) {
  3121. if (eventInWidget(display, e) || signalDOMEvent(cm, e)) return;
  3122. cm.state.pasteIncoming = true;
  3123. input.focus();
  3124. });
  3125. // Prevent normal selection in the editor (we handle our own)
  3126. on(display.lineSpace, "selectstart", function(e) {
  3127. if (!eventInWidget(display, e)) e_preventDefault(e);
  3128. });
  3129. on(te, "compositionstart", function() {
  3130. var start = cm.getCursor("from");
  3131. if (input.composing) input.composing.range.clear()
  3132. input.composing = {
  3133. start: start,
  3134. range: cm.markText(start, cm.getCursor("to"), {className: "CodeMirror-composing"})
  3135. };
  3136. });
  3137. on(te, "compositionend", function() {
  3138. if (input.composing) {
  3139. input.poll();
  3140. input.composing.range.clear();
  3141. input.composing = null;
  3142. }
  3143. });
  3144. },
  3145. prepareSelection: function() {
  3146. // Redraw the selection and/or cursor
  3147. var cm = this.cm, display = cm.display, doc = cm.doc;
  3148. var result = prepareSelection(cm);
  3149. // Move the hidden textarea near the cursor to prevent scrolling artifacts
  3150. if (cm.options.moveInputWithCursor) {
  3151. var headPos = cursorCoords(cm, doc.sel.primary().head, "div");
  3152. var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect();
  3153. result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10,
  3154. headPos.top + lineOff.top - wrapOff.top));
  3155. result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10,
  3156. headPos.left + lineOff.left - wrapOff.left));
  3157. }
  3158. return result;
  3159. },
  3160. showSelection: function(drawn) {
  3161. var cm = this.cm, display = cm.display;
  3162. removeChildrenAndAdd(display.cursorDiv, drawn.cursors);
  3163. removeChildrenAndAdd(display.selectionDiv, drawn.selection);
  3164. if (drawn.teTop != null) {
  3165. this.wrapper.style.top = drawn.teTop + "px";
  3166. this.wrapper.style.left = drawn.teLeft + "px";
  3167. }
  3168. },
  3169. // Reset the input to correspond to the selection (or to be empty,
  3170. // when not typing and nothing is selected)
  3171. reset: function(typing) {
  3172. if (this.contextMenuPending) return;
  3173. var minimal, selected, cm = this.cm, doc = cm.doc;
  3174. if (cm.somethingSelected()) {
  3175. this.prevInput = "";
  3176. var range = doc.sel.primary();
  3177. minimal = hasCopyEvent &&
  3178. (range.to().line - range.from().line > 100 || (selected = cm.getSelection()).length > 1000);
  3179. var content = minimal ? "-" : selected || cm.getSelection();
  3180. this.textarea.value = content;
  3181. if (cm.state.focused) selectInput(this.textarea);
  3182. if (ie && ie_version >= 9) this.hasSelection = content;
  3183. } else if (!typing) {
  3184. this.prevInput = this.textarea.value = "";
  3185. if (ie && ie_version >= 9) this.hasSelection = null;
  3186. }
  3187. this.inaccurateSelection = minimal;
  3188. },
  3189. getField: function() { return this.textarea; },
  3190. supportsTouch: function() { return false; },
  3191. focus: function() {
  3192. if (this.cm.options.readOnly != "nocursor" && (!mobile || activeElt() != this.textarea)) {
  3193. try { this.textarea.focus(); }
  3194. catch (e) {} // IE8 will throw if the textarea is display: none or not in DOM
  3195. }
  3196. },
  3197. blur: function() { this.textarea.blur(); },
  3198. resetPosition: function() {
  3199. this.wrapper.style.top = this.wrapper.style.left = 0;
  3200. },
  3201. receivedFocus: function() { this.slowPoll(); },
  3202. // Poll for input changes, using the normal rate of polling. This
  3203. // runs as long as the editor is focused.
  3204. slowPoll: function() {
  3205. var input = this;
  3206. if (input.pollingFast) return;
  3207. input.polling.set(this.cm.options.pollInterval, function() {
  3208. input.poll();
  3209. if (input.cm.state.focused) input.slowPoll();
  3210. });
  3211. },
  3212. // When an event has just come in that is likely to add or change
  3213. // something in the input textarea, we poll faster, to ensure that
  3214. // the change appears on the screen quickly.
  3215. fastPoll: function() {
  3216. var missed = false, input = this;
  3217. input.pollingFast = true;
  3218. function p() {
  3219. var changed = input.poll();
  3220. if (!changed && !missed) {missed = true; input.polling.set(60, p);}
  3221. else {input.pollingFast = false; input.slowPoll();}
  3222. }
  3223. input.polling.set(20, p);
  3224. },
  3225. // Read input from the textarea, and update the document to match.
  3226. // When something is selected, it is present in the textarea, and
  3227. // selected (unless it is huge, in which case a placeholder is
  3228. // used). When nothing is selected, the cursor sits after previously
  3229. // seen text (can be empty), which is stored in prevInput (we must
  3230. // not reset the textarea when typing, because that breaks IME).
  3231. poll: function() {
  3232. var cm = this.cm, input = this.textarea, prevInput = this.prevInput;
  3233. // Since this is called a *lot*, try to bail out as cheaply as
  3234. // possible when it is clear that nothing happened. hasSelection
  3235. // will be the case when there is a lot of text in the textarea,
  3236. // in which case reading its value would be expensive.
  3237. if (this.contextMenuPending || !cm.state.focused ||
  3238. (hasSelection(input) && !prevInput && !this.composing) ||
  3239. cm.isReadOnly() || cm.options.disableInput || cm.state.keySeq)
  3240. return false;
  3241. var text = input.value;
  3242. // If nothing changed, bail.
  3243. if (text == prevInput && !cm.somethingSelected()) return false;
  3244. // Work around nonsensical selection resetting in IE9/10, and
  3245. // inexplicable appearance of private area unicode characters on
  3246. // some key combos in Mac (#2689).
  3247. if (ie && ie_version >= 9 && this.hasSelection === text ||
  3248. mac && /[\uf700-\uf7ff]/.test(text)) {
  3249. cm.display.input.reset();
  3250. return false;
  3251. }
  3252. if (cm.doc.sel == cm.display.selForContextMenu) {
  3253. var first = text.charCodeAt(0);
  3254. if (first == 0x200b && !prevInput) prevInput = "\u200b";
  3255. if (first == 0x21da) { this.reset(); return this.cm.execCommand("undo"); }
  3256. }
  3257. // Find the part of the input that is actually new
  3258. var same = 0, l = Math.min(prevInput.length, text.length);
  3259. while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) ++same;
  3260. var self = this;
  3261. runInOp(cm, function() {
  3262. applyTextInput(cm, text.slice(same), prevInput.length - same,
  3263. null, self.composing ? "*compose" : null);
  3264. // Don't leave long text in the textarea, since it makes further polling slow
  3265. if (text.length > 1000 || text.indexOf("\n") > -1) input.value = self.prevInput = "";
  3266. else self.prevInput = text;
  3267. if (self.composing) {
  3268. self.composing.range.clear();
  3269. self.composing.range = cm.markText(self.composing.start, cm.getCursor("to"),
  3270. {className: "CodeMirror-composing"});
  3271. }
  3272. });
  3273. return true;
  3274. },
  3275. ensurePolled: function() {
  3276. if (this.pollingFast && this.poll()) this.pollingFast = false;
  3277. },
  3278. onKeyPress: function() {
  3279. if (ie && ie_version >= 9) this.hasSelection = null;
  3280. this.fastPoll();
  3281. },
  3282. onContextMenu: function(e) {
  3283. var input = this, cm = input.cm, display = cm.display, te = input.textarea;
  3284. var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop;
  3285. if (!pos || presto) return; // Opera is difficult.
  3286. // Reset the current text selection only if the click is done outside of the selection
  3287. // and 'resetSelectionOnContextMenu' option is true.
  3288. var reset = cm.options.resetSelectionOnContextMenu;
  3289. if (reset && cm.doc.sel.contains(pos) == -1)
  3290. operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll);
  3291. var oldCSS = te.style.cssText, oldWrapperCSS = input.wrapper.style.cssText;
  3292. input.wrapper.style.cssText = "position: absolute"
  3293. var wrapperBox = input.wrapper.getBoundingClientRect()
  3294. te.style.cssText = "position: absolute; width: 30px; height: 30px; top: " + (e.clientY - wrapperBox.top - 5) +
  3295. "px; left: " + (e.clientX - wrapperBox.left - 5) + "px; z-index: 1000; background: " +
  3296. (ie ? "rgba(255, 255, 255, .05)" : "transparent") +
  3297. "; outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);";
  3298. if (webkit) var oldScrollY = window.scrollY; // Work around Chrome issue (#2712)
  3299. display.input.focus();
  3300. if (webkit) window.scrollTo(null, oldScrollY);
  3301. display.input.reset();
  3302. // Adds "Select all" to context menu in FF
  3303. if (!cm.somethingSelected()) te.value = input.prevInput = " ";
  3304. input.contextMenuPending = true;
  3305. display.selForContextMenu = cm.doc.sel;
  3306. clearTimeout(display.detectingSelectAll);
  3307. // Select-all will be greyed out if there's nothing to select, so
  3308. // this adds a zero-width space so that we can later check whether
  3309. // it got selected.
  3310. function prepareSelectAllHack() {
  3311. if (te.selectionStart != null) {
  3312. var selected = cm.somethingSelected();
  3313. var extval = "\u200b" + (selected ? te.value : "");
  3314. te.value = "\u21da"; // Used to catch context-menu undo
  3315. te.value = extval;
  3316. input.prevInput = selected ? "" : "\u200b";
  3317. te.selectionStart = 1; te.selectionEnd = extval.length;
  3318. // Re-set this, in case some other handler touched the
  3319. // selection in the meantime.
  3320. display.selForContextMenu = cm.doc.sel;
  3321. }
  3322. }
  3323. function rehide() {
  3324. input.contextMenuPending = false;
  3325. input.wrapper.style.cssText = oldWrapperCSS
  3326. te.style.cssText = oldCSS;
  3327. if (ie && ie_version < 9) display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos);
  3328. // Try to detect the user choosing select-all
  3329. if (te.selectionStart != null) {
  3330. if (!ie || (ie && ie_version < 9)) prepareSelectAllHack();
  3331. var i = 0, poll = function() {
  3332. if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0 &&
  3333. te.selectionEnd > 0 && input.prevInput == "\u200b")
  3334. operation(cm, commands.selectAll)(cm);
  3335. else if (i++ < 10) display.detectingSelectAll = setTimeout(poll, 500);
  3336. else display.input.reset();
  3337. };
  3338. display.detectingSelectAll = setTimeout(poll, 200);
  3339. }
  3340. }
  3341. if (ie && ie_version >= 9) prepareSelectAllHack();
  3342. if (captureRightClick) {
  3343. e_stop(e);
  3344. var mouseup = function() {
  3345. off(window, "mouseup", mouseup);
  3346. setTimeout(rehide, 20);
  3347. };
  3348. on(window, "mouseup", mouseup);
  3349. } else {
  3350. setTimeout(rehide, 50);
  3351. }
  3352. },
  3353. readOnlyChanged: function(val) {
  3354. if (!val) this.reset();
  3355. },
  3356. setUneditable: nothing,
  3357. needsContentAttribute: false
  3358. }, TextareaInput.prototype);
  3359. // CONTENTEDITABLE INPUT STYLE
  3360. function ContentEditableInput(cm) {
  3361. this.cm = cm;
  3362. this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null;
  3363. this.polling = new Delayed();
  3364. this.gracePeriod = false;
  3365. }
  3366. ContentEditableInput.prototype = copyObj({
  3367. init: function(display) {
  3368. var input = this, cm = input.cm;
  3369. var div = input.div = display.lineDiv;
  3370. disableBrowserMagic(div);
  3371. on(div, "paste", function(e) {
  3372. if (!signalDOMEvent(cm, e)) handlePaste(e, cm);
  3373. })
  3374. on(div, "compositionstart", function(e) {
  3375. var data = e.data;
  3376. input.composing = {sel: cm.doc.sel, data: data, startData: data};
  3377. if (!data) return;
  3378. var prim = cm.doc.sel.primary();
  3379. var line = cm.getLine(prim.head.line);
  3380. var found = line.indexOf(data, Math.max(0, prim.head.ch - data.length));
  3381. if (found > -1 && found <= prim.head.ch)
  3382. input.composing.sel = simpleSelection(Pos(prim.head.line, found),
  3383. Pos(prim.head.line, found + data.length));
  3384. });
  3385. on(div, "compositionupdate", function(e) {
  3386. input.composing.data = e.data;
  3387. });
  3388. on(div, "compositionend", function(e) {
  3389. var ours = input.composing;
  3390. if (!ours) return;
  3391. if (e.data != ours.startData && !/\u200b/.test(e.data))
  3392. ours.data = e.data;
  3393. // Need a small delay to prevent other code (input event,
  3394. // selection polling) from doing damage when fired right after
  3395. // compositionend.
  3396. setTimeout(function() {
  3397. if (!ours.handled)
  3398. input.applyComposition(ours);
  3399. if (input.composing == ours)
  3400. input.composing = null;
  3401. }, 50);
  3402. });
  3403. on(div, "touchstart", function() {
  3404. input.forceCompositionEnd();
  3405. });
  3406. on(div, "input", function() {
  3407. if (input.composing) return;
  3408. if (cm.isReadOnly() || !input.pollContent())
  3409. runInOp(input.cm, function() {regChange(cm);});
  3410. });
  3411. function onCopyCut(e) {
  3412. if (signalDOMEvent(cm, e)) return
  3413. if (cm.somethingSelected()) {
  3414. lastCopied = {lineWise: false, text: cm.getSelections()};
  3415. if (e.type == "cut") cm.replaceSelection("", null, "cut");
  3416. } else if (!cm.options.lineWiseCopyCut) {
  3417. return;
  3418. } else {
  3419. var ranges = copyableRanges(cm);
  3420. lastCopied = {lineWise: true, text: ranges.text};
  3421. if (e.type == "cut") {
  3422. cm.operation(function() {
  3423. cm.setSelections(ranges.ranges, 0, sel_dontScroll);
  3424. cm.replaceSelection("", null, "cut");
  3425. });
  3426. }
  3427. }
  3428. // iOS exposes the clipboard API, but seems to discard content inserted into it
  3429. if (e.clipboardData && !ios) {
  3430. e.preventDefault();
  3431. e.clipboardData.clearData();
  3432. e.clipboardData.setData("text/plain", lastCopied.text.join("\n"));
  3433. } else {
  3434. // Old-fashioned briefly-focus-a-textarea hack
  3435. var kludge = hiddenTextarea(), te = kludge.firstChild;
  3436. cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild);
  3437. te.value = lastCopied.text.join("\n");
  3438. var hadFocus = document.activeElement;
  3439. selectInput(te);
  3440. setTimeout(function() {
  3441. cm.display.lineSpace.removeChild(kludge);
  3442. hadFocus.focus();
  3443. }, 50);
  3444. }
  3445. }
  3446. on(div, "copy", onCopyCut);
  3447. on(div, "cut", onCopyCut);
  3448. },
  3449. prepareSelection: function() {
  3450. var result = prepareSelection(this.cm, false);
  3451. result.focus = this.cm.state.focused;
  3452. return result;
  3453. },
  3454. showSelection: function(info, takeFocus) {
  3455. if (!info || !this.cm.display.view.length) return;
  3456. if (info.focus || takeFocus) this.showPrimarySelection();
  3457. this.showMultipleSelections(info);
  3458. },
  3459. showPrimarySelection: function() {
  3460. var sel = window.getSelection(), prim = this.cm.doc.sel.primary();
  3461. var curAnchor = domToPos(this.cm, sel.anchorNode, sel.anchorOffset);
  3462. var curFocus = domToPos(this.cm, sel.focusNode, sel.focusOffset);
  3463. if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad &&
  3464. cmp(minPos(curAnchor, curFocus), prim.from()) == 0 &&
  3465. cmp(maxPos(curAnchor, curFocus), prim.to()) == 0)
  3466. return;
  3467. var start = posToDOM(this.cm, prim.from());
  3468. var end = posToDOM(this.cm, prim.to());
  3469. if (!start && !end) return;
  3470. var view = this.cm.display.view;
  3471. var old = sel.rangeCount && sel.getRangeAt(0);
  3472. if (!start) {
  3473. start = {node: view[0].measure.map[2], offset: 0};
  3474. } else if (!end) { // FIXME dangerously hacky
  3475. var measure = view[view.length - 1].measure;
  3476. var map = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map;
  3477. end = {node: map[map.length - 1], offset: map[map.length - 2] - map[map.length - 3]};
  3478. }
  3479. try { var rng = range(start.node, start.offset, end.offset, end.node); }
  3480. catch(e) {} // Our model of the DOM might be outdated, in which case the range we try to set can be impossible
  3481. if (rng) {
  3482. if (!gecko && this.cm.state.focused) {
  3483. sel.collapse(start.node, start.offset);
  3484. if (!rng.collapsed) sel.addRange(rng);
  3485. } else {
  3486. sel.removeAllRanges();
  3487. sel.addRange(rng);
  3488. }
  3489. if (old && sel.anchorNode == null) sel.addRange(old);
  3490. else if (gecko) this.startGracePeriod();
  3491. }
  3492. this.rememberSelection();
  3493. },
  3494. startGracePeriod: function() {
  3495. var input = this;
  3496. clearTimeout(this.gracePeriod);
  3497. this.gracePeriod = setTimeout(function() {
  3498. input.gracePeriod = false;
  3499. if (input.selectionChanged())
  3500. input.cm.operation(function() { input.cm.curOp.selectionChanged = true; });
  3501. }, 20);
  3502. },
  3503. showMultipleSelections: function(info) {
  3504. removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors);
  3505. removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection);
  3506. },
  3507. rememberSelection: function() {
  3508. var sel = window.getSelection();
  3509. this.lastAnchorNode = sel.anchorNode; this.lastAnchorOffset = sel.anchorOffset;
  3510. this.lastFocusNode = sel.focusNode; this.lastFocusOffset = sel.focusOffset;
  3511. },
  3512. selectionInEditor: function() {
  3513. var sel = window.getSelection();
  3514. if (!sel.rangeCount) return false;
  3515. var node = sel.getRangeAt(0).commonAncestorContainer;
  3516. return contains(this.div, node);
  3517. },
  3518. focus: function() {
  3519. if (this.cm.options.readOnly != "nocursor") this.div.focus();
  3520. },
  3521. blur: function() { this.div.blur(); },
  3522. getField: function() { return this.div; },
  3523. supportsTouch: function() { return true; },
  3524. receivedFocus: function() {
  3525. var input = this;
  3526. if (this.selectionInEditor())
  3527. this.pollSelection();
  3528. else
  3529. runInOp(this.cm, function() { input.cm.curOp.selectionChanged = true; });
  3530. function poll() {
  3531. if (input.cm.state.focused) {
  3532. input.pollSelection();
  3533. input.polling.set(input.cm.options.pollInterval, poll);
  3534. }
  3535. }
  3536. this.polling.set(this.cm.options.pollInterval, poll);
  3537. },
  3538. selectionChanged: function() {
  3539. var sel = window.getSelection();
  3540. return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset ||
  3541. sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset;
  3542. },
  3543. pollSelection: function() {
  3544. if (!this.composing && !this.gracePeriod && this.selectionChanged()) {
  3545. var sel = window.getSelection(), cm = this.cm;
  3546. this.rememberSelection();
  3547. var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset);
  3548. var head = domToPos(cm, sel.focusNode, sel.focusOffset);
  3549. if (anchor && head) runInOp(cm, function() {
  3550. setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll);
  3551. if (anchor.bad || head.bad) cm.curOp.selectionChanged = true;
  3552. });
  3553. }
  3554. },
  3555. pollContent: function() {
  3556. var cm = this.cm, display = cm.display, sel = cm.doc.sel.primary();
  3557. var from = sel.from(), to = sel.to();
  3558. if (from.line < display.viewFrom || to.line > display.viewTo - 1) return false;
  3559. var fromIndex;
  3560. if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) {
  3561. var fromLine = lineNo(display.view[0].line);
  3562. var fromNode = display.view[0].node;
  3563. } else {
  3564. var fromLine = lineNo(display.view[fromIndex].line);
  3565. var fromNode = display.view[fromIndex - 1].node.nextSibling;
  3566. }
  3567. var toIndex = findViewIndex(cm, to.line);
  3568. if (toIndex == display.view.length - 1) {
  3569. var toLine = display.viewTo - 1;
  3570. var toNode = display.lineDiv.lastChild;
  3571. } else {
  3572. var toLine = lineNo(display.view[toIndex + 1].line) - 1;
  3573. var toNode = display.view[toIndex + 1].node.previousSibling;
  3574. }
  3575. var newText = cm.doc.splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine));
  3576. var oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length));
  3577. while (newText.length > 1 && oldText.length > 1) {
  3578. if (lst(newText) == lst(oldText)) { newText.pop(); oldText.pop(); toLine--; }
  3579. else if (newText[0] == oldText[0]) { newText.shift(); oldText.shift(); fromLine++; }
  3580. else break;
  3581. }
  3582. var cutFront = 0, cutEnd = 0;
  3583. var newTop = newText[0], oldTop = oldText[0], maxCutFront = Math.min(newTop.length, oldTop.length);
  3584. while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront))
  3585. ++cutFront;
  3586. var newBot = lst(newText), oldBot = lst(oldText);
  3587. var maxCutEnd = Math.min(newBot.length - (newText.length == 1 ? cutFront : 0),
  3588. oldBot.length - (oldText.length == 1 ? cutFront : 0));
  3589. while (cutEnd < maxCutEnd &&
  3590. newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1))
  3591. ++cutEnd;
  3592. newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd);
  3593. newText[0] = newText[0].slice(cutFront);
  3594. var chFrom = Pos(fromLine, cutFront);
  3595. var chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0);
  3596. if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) {
  3597. replaceRange(cm.doc, newText, chFrom, chTo, "+input");
  3598. return true;
  3599. }
  3600. },
  3601. ensurePolled: function() {
  3602. this.forceCompositionEnd();
  3603. },
  3604. reset: function() {
  3605. this.forceCompositionEnd();
  3606. },
  3607. forceCompositionEnd: function() {
  3608. if (!this.composing || this.composing.handled) return;
  3609. this.applyComposition(this.composing);
  3610. this.composing.handled = true;
  3611. this.div.blur();
  3612. this.div.focus();
  3613. },
  3614. applyComposition: function(composing) {
  3615. if (this.cm.isReadOnly())
  3616. operation(this.cm, regChange)(this.cm)
  3617. else if (composing.data && composing.data != composing.startData)
  3618. operation(this.cm, applyTextInput)(this.cm, composing.data, 0, composing.sel);
  3619. },
  3620. setUneditable: function(node) {
  3621. node.contentEditable = "false"
  3622. },
  3623. onKeyPress: function(e) {
  3624. e.preventDefault();
  3625. if (!this.cm.isReadOnly())
  3626. operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0);
  3627. },
  3628. readOnlyChanged: function(val) {
  3629. this.div.contentEditable = String(val != "nocursor")
  3630. },
  3631. onContextMenu: nothing,
  3632. resetPosition: nothing,
  3633. needsContentAttribute: true
  3634. }, ContentEditableInput.prototype);
  3635. function posToDOM(cm, pos) {
  3636. var view = findViewForLine(cm, pos.line);
  3637. if (!view || view.hidden) return null;
  3638. var line = getLine(cm.doc, pos.line);
  3639. var info = mapFromLineView(view, line, pos.line);
  3640. var order = getOrder(line), side = "left";
  3641. if (order) {
  3642. var partPos = getBidiPartAt(order, pos.ch);
  3643. side = partPos % 2 ? "right" : "left";
  3644. }
  3645. var result = nodeAndOffsetInLineMap(info.map, pos.ch, side);
  3646. result.offset = result.collapse == "right" ? result.end : result.start;
  3647. return result;
  3648. }
  3649. function badPos(pos, bad) { if (bad) pos.bad = true; return pos; }
  3650. function domToPos(cm, node, offset) {
  3651. var lineNode;
  3652. if (node == cm.display.lineDiv) {
  3653. lineNode = cm.display.lineDiv.childNodes[offset];
  3654. if (!lineNode) return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true);
  3655. node = null; offset = 0;
  3656. } else {
  3657. for (lineNode = node;; lineNode = lineNode.parentNode) {
  3658. if (!lineNode || lineNode == cm.display.lineDiv) return null;
  3659. if (lineNode.parentNode && lineNode.parentNode == cm.display.lineDiv) break;
  3660. }
  3661. }
  3662. for (var i = 0; i < cm.display.view.length; i++) {
  3663. var lineView = cm.display.view[i];
  3664. if (lineView.node == lineNode)
  3665. return locateNodeInLineView(lineView, node, offset);
  3666. }
  3667. }
  3668. function locateNodeInLineView(lineView, node, offset) {
  3669. var wrapper = lineView.text.firstChild, bad = false;
  3670. if (!node || !contains(wrapper, node)) return badPos(Pos(lineNo(lineView.line), 0), true);
  3671. if (node == wrapper) {
  3672. bad = true;
  3673. node = wrapper.childNodes[offset];
  3674. offset = 0;
  3675. if (!node) {
  3676. var line = lineView.rest ? lst(lineView.rest) : lineView.line;
  3677. return badPos(Pos(lineNo(line), line.text.length), bad);
  3678. }
  3679. }
  3680. var textNode = node.nodeType == 3 ? node : null, topNode = node;
  3681. if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) {
  3682. textNode = node.firstChild;
  3683. if (offset) offset = textNode.nodeValue.length;
  3684. }
  3685. while (topNode.parentNode != wrapper) topNode = topNode.parentNode;
  3686. var measure = lineView.measure, maps = measure.maps;
  3687. function find(textNode, topNode, offset) {
  3688. for (var i = -1; i < (maps ? maps.length : 0); i++) {
  3689. var map = i < 0 ? measure.map : maps[i];
  3690. for (var j = 0; j < map.length; j += 3) {
  3691. var curNode = map[j + 2];
  3692. if (curNode == textNode || curNode == topNode) {
  3693. var line = lineNo(i < 0 ? lineView.line : lineView.rest[i]);
  3694. var ch = map[j] + offset;
  3695. if (offset < 0 || curNode != textNode) ch = map[j + (offset ? 1 : 0)];
  3696. return Pos(line, ch);
  3697. }
  3698. }
  3699. }
  3700. }
  3701. var found = find(textNode, topNode, offset);
  3702. if (found) return badPos(found, bad);
  3703. // FIXME this is all really shaky. might handle the few cases it needs to handle, but likely to cause problems
  3704. for (var after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) {
  3705. found = find(after, after.firstChild, 0);
  3706. if (found)
  3707. return badPos(Pos(found.line, found.ch - dist), bad);
  3708. else
  3709. dist += after.textContent.length;
  3710. }
  3711. for (var before = topNode.previousSibling, dist = offset; before; before = before.previousSibling) {
  3712. found = find(before, before.firstChild, -1);
  3713. if (found)
  3714. return badPos(Pos(found.line, found.ch + dist), bad);
  3715. else
  3716. dist += after.textContent.length;
  3717. }
  3718. }
  3719. function domTextBetween(cm, from, to, fromLine, toLine) {
  3720. var text = "", closing = false, lineSep = cm.doc.lineSeparator();
  3721. function recognizeMarker(id) { return function(marker) { return marker.id == id; }; }
  3722. function walk(node) {
  3723. if (node.nodeType == 1) {
  3724. var cmText = node.getAttribute("cm-text");
  3725. if (cmText != null) {
  3726. if (cmText == "") cmText = node.textContent.replace(/\u200b/g, "");
  3727. text += cmText;
  3728. return;
  3729. }
  3730. var markerID = node.getAttribute("cm-marker"), range;
  3731. if (markerID) {
  3732. var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID));
  3733. if (found.length && (range = found[0].find()))
  3734. text += getBetween(cm.doc, range.from, range.to).join(lineSep);
  3735. return;
  3736. }
  3737. if (node.getAttribute("contenteditable") == "false") return;
  3738. for (var i = 0; i < node.childNodes.length; i++)
  3739. walk(node.childNodes[i]);
  3740. if (/^(pre|div|p)$/i.test(node.nodeName))
  3741. closing = true;
  3742. } else if (node.nodeType == 3) {
  3743. var val = node.nodeValue;
  3744. if (!val) return;
  3745. if (closing) {
  3746. text += lineSep;
  3747. closing = false;
  3748. }
  3749. text += val;
  3750. }
  3751. }
  3752. for (;;) {
  3753. walk(from);
  3754. if (from == to) break;
  3755. from = from.nextSibling;
  3756. }
  3757. return text;
  3758. }
  3759. CodeMirror.inputStyles = {"textarea": TextareaInput, "contenteditable": ContentEditableInput};
  3760. // SELECTION / CURSOR
  3761. // Selection objects are immutable. A new one is created every time
  3762. // the selection changes. A selection is one or more non-overlapping
  3763. // (and non-touching) ranges, sorted, and an integer that indicates
  3764. // which one is the primary selection (the one that's scrolled into
  3765. // view, that getCursor returns, etc).
  3766. function Selection(ranges, primIndex) {
  3767. this.ranges = ranges;
  3768. this.primIndex = primIndex;
  3769. }
  3770. Selection.prototype = {
  3771. primary: function() { return this.ranges[this.primIndex]; },
  3772. equals: function(other) {
  3773. if (other == this) return true;
  3774. if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) return false;
  3775. for (var i = 0; i < this.ranges.length; i++) {
  3776. var here = this.ranges[i], there = other.ranges[i];
  3777. if (cmp(here.anchor, there.anchor) != 0 || cmp(here.head, there.head) != 0) return false;
  3778. }
  3779. return true;
  3780. },
  3781. deepCopy: function() {
  3782. for (var out = [], i = 0; i < this.ranges.length; i++)
  3783. out[i] = new Range(copyPos(this.ranges[i].anchor), copyPos(this.ranges[i].head));
  3784. return new Selection(out, this.primIndex);
  3785. },
  3786. somethingSelected: function() {
  3787. for (var i = 0; i < this.ranges.length; i++)
  3788. if (!this.ranges[i].empty()) return true;
  3789. return false;
  3790. },
  3791. contains: function(pos, end) {
  3792. if (!end) end = pos;
  3793. for (var i = 0; i < this.ranges.length; i++) {
  3794. var range = this.ranges[i];
  3795. if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0)
  3796. return i;
  3797. }
  3798. return -1;
  3799. }
  3800. };
  3801. function Range(anchor, head) {
  3802. this.anchor = anchor; this.head = head;
  3803. }
  3804. Range.prototype = {
  3805. from: function() { return minPos(this.anchor, this.head); },
  3806. to: function() { return maxPos(this.anchor, this.head); },
  3807. empty: function() {
  3808. return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch;
  3809. }
  3810. };
  3811. // Take an unsorted, potentially overlapping set of ranges, and
  3812. // build a selection out of it. 'Consumes' ranges array (modifying
  3813. // it).
  3814. function normalizeSelection(ranges, primIndex) {
  3815. var prim = ranges[primIndex];
  3816. ranges.sort(function(a, b) { return cmp(a.from(), b.from()); });
  3817. primIndex = indexOf(ranges, prim);
  3818. for (var i = 1; i < ranges.length; i++) {
  3819. var cur = ranges[i], prev = ranges[i - 1];
  3820. if (cmp(prev.to(), cur.from()) >= 0) {
  3821. var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to());
  3822. var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head;
  3823. if (i <= primIndex) --primIndex;
  3824. ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to));
  3825. }
  3826. }
  3827. return new Selection(ranges, primIndex);
  3828. }
  3829. function simpleSelection(anchor, head) {
  3830. return new Selection([new Range(anchor, head || anchor)], 0);
  3831. }
  3832. // Most of the external API clips given positions to make sure they
  3833. // actually exist within the document.
  3834. function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1));}
  3835. function clipPos(doc, pos) {
  3836. if (pos.line < doc.first) return Pos(doc.first, 0);
  3837. var last = doc.first + doc.size - 1;
  3838. if (pos.line > last) return Pos(last, getLine(doc, last).text.length);
  3839. return clipToLen(pos, getLine(doc, pos.line).text.length);
  3840. }
  3841. function clipToLen(pos, linelen) {
  3842. var ch = pos.ch;
  3843. if (ch == null || ch > linelen) return Pos(pos.line, linelen);
  3844. else if (ch < 0) return Pos(pos.line, 0);
  3845. else return pos;
  3846. }
  3847. function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size;}
  3848. function clipPosArray(doc, array) {
  3849. for (var out = [], i = 0; i < array.length; i++) out[i] = clipPos(doc, array[i]);
  3850. return out;
  3851. }
  3852. // SELECTION UPDATES
  3853. // The 'scroll' parameter given to many of these indicated whether
  3854. // the new cursor position should be scrolled into view after
  3855. // modifying the selection.
  3856. // If shift is held or the extend flag is set, extends a range to
  3857. // include a given position (and optionally a second position).
  3858. // Otherwise, simply returns the range between the given positions.
  3859. // Used for cursor motion and such.
  3860. function extendRange(doc, range, head, other) {
  3861. if (doc.cm && doc.cm.display.shift || doc.extend) {
  3862. var anchor = range.anchor;
  3863. if (other) {
  3864. var posBefore = cmp(head, anchor) < 0;
  3865. if (posBefore != (cmp(other, anchor) < 0)) {
  3866. anchor = head;
  3867. head = other;
  3868. } else if (posBefore != (cmp(head, other) < 0)) {
  3869. head = other;
  3870. }
  3871. }
  3872. return new Range(anchor, head);
  3873. } else {
  3874. return new Range(other || head, head);
  3875. }
  3876. }
  3877. // Extend the primary selection range, discard the rest.
  3878. function extendSelection(doc, head, other, options) {
  3879. setSelection(doc, new Selection([extendRange(doc, doc.sel.primary(), head, other)], 0), options);
  3880. }
  3881. // Extend all selections (pos is an array of selections with length
  3882. // equal the number of selections)
  3883. function extendSelections(doc, heads, options) {
  3884. for (var out = [], i = 0; i < doc.sel.ranges.length; i++)
  3885. out[i] = extendRange(doc, doc.sel.ranges[i], heads[i], null);
  3886. var newSel = normalizeSelection(out, doc.sel.primIndex);
  3887. setSelection(doc, newSel, options);
  3888. }
  3889. // Updates a single range in the selection.
  3890. function replaceOneSelection(doc, i, range, options) {
  3891. var ranges = doc.sel.ranges.slice(0);
  3892. ranges[i] = range;
  3893. setSelection(doc, normalizeSelection(ranges, doc.sel.primIndex), options);
  3894. }
  3895. // Reset the selection to a single range.
  3896. function setSimpleSelection(doc, anchor, head, options) {
  3897. setSelection(doc, simpleSelection(anchor, head), options);
  3898. }
  3899. // Give beforeSelectionChange handlers a change to influence a
  3900. // selection update.
  3901. function filterSelectionChange(doc, sel, options) {
  3902. var obj = {
  3903. ranges: sel.ranges,
  3904. update: function(ranges) {
  3905. this.ranges = [];
  3906. for (var i = 0; i < ranges.length; i++)
  3907. this.ranges[i] = new Range(clipPos(doc, ranges[i].anchor),
  3908. clipPos(doc, ranges[i].head));
  3909. },
  3910. origin: options && options.origin
  3911. };
  3912. signal(doc, "beforeSelectionChange", doc, obj);
  3913. if (doc.cm) signal(doc.cm, "beforeSelectionChange", doc.cm, obj);
  3914. if (obj.ranges != sel.ranges) return normalizeSelection(obj.ranges, obj.ranges.length - 1);
  3915. else return sel;
  3916. }
  3917. function setSelectionReplaceHistory(doc, sel, options) {
  3918. var done = doc.history.done, last = lst(done);
  3919. if (last && last.ranges) {
  3920. done[done.length - 1] = sel;
  3921. setSelectionNoUndo(doc, sel, options);
  3922. } else {
  3923. setSelection(doc, sel, options);
  3924. }
  3925. }
  3926. // Set a new selection.
  3927. function setSelection(doc, sel, options) {
  3928. setSelectionNoUndo(doc, sel, options);
  3929. addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options);
  3930. }
  3931. function setSelectionNoUndo(doc, sel, options) {
  3932. if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange"))
  3933. sel = filterSelectionChange(doc, sel, options);
  3934. var bias = options && options.bias ||
  3935. (cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1);
  3936. setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true));
  3937. if (!(options && options.scroll === false) && doc.cm)
  3938. ensureCursorVisible(doc.cm);
  3939. }
  3940. function setSelectionInner(doc, sel) {
  3941. if (sel.equals(doc.sel)) return;
  3942. doc.sel = sel;
  3943. if (doc.cm) {
  3944. doc.cm.curOp.updateInput = doc.cm.curOp.selectionChanged = true;
  3945. signalCursorActivity(doc.cm);
  3946. }
  3947. signalLater(doc, "cursorActivity", doc);
  3948. }
  3949. // Verify that the selection does not partially select any atomic
  3950. // marked ranges.
  3951. function reCheckSelection(doc) {
  3952. setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false), sel_dontScroll);
  3953. }
  3954. // Return a selection that does not partially select any atomic
  3955. // ranges.
  3956. function skipAtomicInSelection(doc, sel, bias, mayClear) {
  3957. var out;
  3958. for (var i = 0; i < sel.ranges.length; i++) {
  3959. var range = sel.ranges[i];
  3960. var old = sel.ranges.length == doc.sel.ranges.length && doc.sel.ranges[i];
  3961. var newAnchor = skipAtomic(doc, range.anchor, old && old.anchor, bias, mayClear);
  3962. var newHead = skipAtomic(doc, range.head, old && old.head, bias, mayClear);
  3963. if (out || newAnchor != range.anchor || newHead != range.head) {
  3964. if (!out) out = sel.ranges.slice(0, i);
  3965. out[i] = new Range(newAnchor, newHead);
  3966. }
  3967. }
  3968. return out ? normalizeSelection(out, sel.primIndex) : sel;
  3969. }
  3970. function skipAtomicInner(doc, pos, oldPos, dir, mayClear) {
  3971. var line = getLine(doc, pos.line);
  3972. if (line.markedSpans) for (var i = 0; i < line.markedSpans.length; ++i) {
  3973. var sp = line.markedSpans[i], m = sp.marker;
  3974. if ((sp.from == null || (m.inclusiveLeft ? sp.from <= pos.ch : sp.from < pos.ch)) &&
  3975. (sp.to == null || (m.inclusiveRight ? sp.to >= pos.ch : sp.to > pos.ch))) {
  3976. if (mayClear) {
  3977. signal(m, "beforeCursorEnter");
  3978. if (m.explicitlyCleared) {
  3979. if (!line.markedSpans) break;
  3980. else {--i; continue;}
  3981. }
  3982. }
  3983. if (!m.atomic) continue;
  3984. if (oldPos) {
  3985. var near = m.find(dir < 0 ? 1 : -1), diff;
  3986. if (dir < 0 ? m.inclusiveRight : m.inclusiveLeft)
  3987. near = movePos(doc, near, -dir, near && near.line == pos.line ? line : null);
  3988. if (near && near.line == pos.line && (diff = cmp(near, oldPos)) && (dir < 0 ? diff < 0 : diff > 0))
  3989. return skipAtomicInner(doc, near, pos, dir, mayClear);
  3990. }
  3991. var far = m.find(dir < 0 ? -1 : 1);
  3992. if (dir < 0 ? m.inclusiveLeft : m.inclusiveRight)
  3993. far = movePos(doc, far, dir, far.line == pos.line ? line : null);
  3994. return far ? skipAtomicInner(doc, far, pos, dir, mayClear) : null;
  3995. }
  3996. }
  3997. return pos;
  3998. }
  3999. // Ensure a given position is not inside an atomic range.
  4000. function skipAtomic(doc, pos, oldPos, bias, mayClear) {
  4001. var dir = bias || 1;
  4002. var found = skipAtomicInner(doc, pos, oldPos, dir, mayClear) ||
  4003. (!mayClear && skipAtomicInner(doc, pos, oldPos, dir, true)) ||
  4004. skipAtomicInner(doc, pos, oldPos, -dir, mayClear) ||
  4005. (!mayClear && skipAtomicInner(doc, pos, oldPos, -dir, true));
  4006. if (!found) {
  4007. doc.cantEdit = true;
  4008. return Pos(doc.first, 0);
  4009. }
  4010. return found;
  4011. }
  4012. function movePos(doc, pos, dir, line) {
  4013. if (dir < 0 && pos.ch == 0) {
  4014. if (pos.line > doc.first) return clipPos(doc, Pos(pos.line - 1));
  4015. else return null;
  4016. } else if (dir > 0 && pos.ch == (line || getLine(doc, pos.line)).text.length) {
  4017. if (pos.line < doc.first + doc.size - 1) return Pos(pos.line + 1, 0);
  4018. else return null;
  4019. } else {
  4020. return new Pos(pos.line, pos.ch + dir);
  4021. }
  4022. }
  4023. // SELECTION DRAWING
  4024. function updateSelection(cm) {
  4025. cm.display.input.showSelection(cm.display.input.prepareSelection());
  4026. }
  4027. function prepareSelection(cm, primary) {
  4028. var doc = cm.doc, result = {};
  4029. var curFragment = result.cursors = document.createDocumentFragment();
  4030. var selFragment = result.selection = document.createDocumentFragment();
  4031. for (var i = 0; i < doc.sel.ranges.length; i++) {
  4032. if (primary === false && i == doc.sel.primIndex) continue;
  4033. var range = doc.sel.ranges[i];
  4034. if (range.from().line >= cm.display.viewTo || range.to().line < cm.display.viewFrom) continue;
  4035. var collapsed = range.empty();
  4036. if (collapsed || cm.options.showCursorWhenSelecting)
  4037. drawSelectionCursor(cm, range.head, curFragment);
  4038. if (!collapsed)
  4039. drawSelectionRange(cm, range, selFragment);
  4040. }
  4041. return result;
  4042. }
  4043. // Draws a cursor for the given range
  4044. function drawSelectionCursor(cm, head, output) {
  4045. var pos = cursorCoords(cm, head, "div", null, null, !cm.options.singleCursorHeightPerLine);
  4046. var cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor"));
  4047. cursor.style.left = pos.left + "px";
  4048. cursor.style.top = pos.top + "px";
  4049. cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px";
  4050. if (pos.other) {
  4051. // Secondary cursor, shown when on a 'jump' in bi-directional text
  4052. var otherCursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor"));
  4053. otherCursor.style.display = "";
  4054. otherCursor.style.left = pos.other.left + "px";
  4055. otherCursor.style.top = pos.other.top + "px";
  4056. otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px";
  4057. }
  4058. }
  4059. // Draws the given range as a highlighted selection
  4060. function drawSelectionRange(cm, range, output) {
  4061. var display = cm.display, doc = cm.doc;
  4062. var fragment = document.createDocumentFragment();
  4063. var padding = paddingH(cm.display), leftSide = padding.left;
  4064. var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right;
  4065. function add(left, top, width, bottom) {
  4066. if (top < 0) top = 0;
  4067. top = Math.round(top);
  4068. bottom = Math.round(bottom);
  4069. fragment.appendChild(elt("div", null, "CodeMirror-selected", "position: absolute; left: " + left +
  4070. "px; top: " + top + "px; width: " + (width == null ? rightSide - left : width) +
  4071. "px; height: " + (bottom - top) + "px"));
  4072. }
  4073. function drawForLine(line, fromArg, toArg) {
  4074. var lineObj = getLine(doc, line);
  4075. var lineLen = lineObj.text.length;
  4076. var start, end;
  4077. function coords(ch, bias) {
  4078. return charCoords(cm, Pos(line, ch), "div", lineObj, bias);
  4079. }
  4080. iterateBidiSections(getOrder(lineObj), fromArg || 0, toArg == null ? lineLen : toArg, function(from, to, dir) {
  4081. var leftPos = coords(from, "left"), rightPos, left, right;
  4082. if (from == to) {
  4083. rightPos = leftPos;
  4084. left = right = leftPos.left;
  4085. } else {
  4086. rightPos = coords(to - 1, "right");
  4087. if (dir == "rtl") { var tmp = leftPos; leftPos = rightPos; rightPos = tmp; }
  4088. left = leftPos.left;
  4089. right = rightPos.right;
  4090. }
  4091. if (fromArg == null && from == 0) left = leftSide;
  4092. if (rightPos.top - leftPos.top > 3) { // Different lines, draw top part
  4093. add(left, leftPos.top, null, leftPos.bottom);
  4094. left = leftSide;
  4095. if (leftPos.bottom < rightPos.top) add(left, leftPos.bottom, null, rightPos.top);
  4096. }
  4097. if (toArg == null && to == lineLen) right = rightSide;
  4098. if (!start || leftPos.top < start.top || leftPos.top == start.top && leftPos.left < start.left)
  4099. start = leftPos;
  4100. if (!end || rightPos.bottom > end.bottom || rightPos.bottom == end.bottom && rightPos.right > end.right)
  4101. end = rightPos;
  4102. if (left < leftSide + 1) left = leftSide;
  4103. add(left, rightPos.top, right - left, rightPos.bottom);
  4104. });
  4105. return {start: start, end: end};
  4106. }
  4107. var sFrom = range.from(), sTo = range.to();
  4108. if (sFrom.line == sTo.line) {
  4109. drawForLine(sFrom.line, sFrom.ch, sTo.ch);
  4110. } else {
  4111. var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line);
  4112. var singleVLine = visualLine(fromLine) == visualLine(toLine);
  4113. var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end;
  4114. var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start;
  4115. if (singleVLine) {
  4116. if (leftEnd.top < rightStart.top - 2) {
  4117. add(leftEnd.right, leftEnd.top, null, leftEnd.bottom);
  4118. add(leftSide, rightStart.top, rightStart.left, rightStart.bottom);
  4119. } else {
  4120. add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom);
  4121. }
  4122. }
  4123. if (leftEnd.bottom < rightStart.top)
  4124. add(leftSide, leftEnd.bottom, null, rightStart.top);
  4125. }
  4126. output.appendChild(fragment);
  4127. }
  4128. // Cursor-blinking
  4129. function restartBlink(cm) {
  4130. if (!cm.state.focused) return;
  4131. var display = cm.display;
  4132. clearInterval(display.blinker);
  4133. var on = true;
  4134. display.cursorDiv.style.visibility = "";
  4135. if (cm.options.cursorBlinkRate > 0)
  4136. display.blinker = setInterval(function() {
  4137. display.cursorDiv.style.visibility = (on = !on) ? "" : "hidden";
  4138. }, cm.options.cursorBlinkRate);
  4139. else if (cm.options.cursorBlinkRate < 0)
  4140. display.cursorDiv.style.visibility = "hidden";
  4141. }
  4142. // HIGHLIGHT WORKER
  4143. function startWorker(cm, time) {
  4144. if (cm.doc.mode.startState && cm.doc.frontier < cm.display.viewTo)
  4145. cm.state.highlight.set(time, bind(highlightWorker, cm));
  4146. }
  4147. function highlightWorker(cm) {
  4148. var doc = cm.doc;
  4149. if (doc.frontier < doc.first) doc.frontier = doc.first;
  4150. if (doc.frontier >= cm.display.viewTo) return;
  4151. var end = +new Date + cm.options.workTime;
  4152. var state = copyState(doc.mode, getStateBefore(cm, doc.frontier));
  4153. var changedLines = [];
  4154. doc.iter(doc.frontier, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function(line) {
  4155. if (doc.frontier >= cm.display.viewFrom) { // Visible
  4156. var oldStyles = line.styles, tooLong = line.text.length > cm.options.maxHighlightLength;
  4157. var highlighted = highlightLine(cm, line, tooLong ? copyState(doc.mode, state) : state, true);
  4158. line.styles = highlighted.styles;
  4159. var oldCls = line.styleClasses, newCls = highlighted.classes;
  4160. if (newCls) line.styleClasses = newCls;
  4161. else if (oldCls) line.styleClasses = null;
  4162. var ischange = !oldStyles || oldStyles.length != line.styles.length ||
  4163. oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass);
  4164. for (var i = 0; !ischange && i < oldStyles.length; ++i) ischange = oldStyles[i] != line.styles[i];
  4165. if (ischange) changedLines.push(doc.frontier);
  4166. line.stateAfter = tooLong ? state : copyState(doc.mode, state);
  4167. } else {
  4168. if (line.text.length <= cm.options.maxHighlightLength)
  4169. processLine(cm, line.text, state);
  4170. line.stateAfter = doc.frontier % 5 == 0 ? copyState(doc.mode, state) : null;
  4171. }
  4172. ++doc.frontier;
  4173. if (+new Date > end) {
  4174. startWorker(cm, cm.options.workDelay);
  4175. return true;
  4176. }
  4177. });
  4178. if (changedLines.length) runInOp(cm, function() {
  4179. for (var i = 0; i < changedLines.length; i++)
  4180. regLineChange(cm, changedLines[i], "text");
  4181. });
  4182. }
  4183. // Finds the line to start with when starting a parse. Tries to
  4184. // find a line with a stateAfter, so that it can start with a
  4185. // valid state. If that fails, it returns the line with the
  4186. // smallest indentation, which tends to need the least context to
  4187. // parse correctly.
  4188. function findStartLine(cm, n, precise) {
  4189. var minindent, minline, doc = cm.doc;
  4190. var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100);
  4191. for (var search = n; search > lim; --search) {
  4192. if (search <= doc.first) return doc.first;
  4193. var line = getLine(doc, search - 1);
  4194. if (line.stateAfter && (!precise || search <= doc.frontier)) return search;
  4195. var indented = countColumn(line.text, null, cm.options.tabSize);
  4196. if (minline == null || minindent > indented) {
  4197. minline = search - 1;
  4198. minindent = indented;
  4199. }
  4200. }
  4201. return minline;
  4202. }
  4203. function getStateBefore(cm, n, precise) {
  4204. var doc = cm.doc, display = cm.display;
  4205. if (!doc.mode.startState) return true;
  4206. var pos = findStartLine(cm, n, precise), state = pos > doc.first && getLine(doc, pos-1).stateAfter;
  4207. if (!state) state = startState(doc.mode);
  4208. else state = copyState(doc.mode, state);
  4209. doc.iter(pos, n, function(line) {
  4210. processLine(cm, line.text, state);
  4211. var save = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo;
  4212. line.stateAfter = save ? copyState(doc.mode, state) : null;
  4213. ++pos;
  4214. });
  4215. if (precise) doc.frontier = pos;
  4216. return state;
  4217. }
  4218. // POSITION MEASUREMENT
  4219. function paddingTop(display) {return display.lineSpace.offsetTop;}
  4220. function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight;}
  4221. function paddingH(display) {
  4222. if (display.cachedPaddingH) return display.cachedPaddingH;
  4223. var e = removeChildrenAndAdd(display.measure, elt("pre", "x"));
  4224. var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle;
  4225. var data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)};
  4226. if (!isNaN(data.left) && !isNaN(data.right)) display.cachedPaddingH = data;
  4227. return data;
  4228. }
  4229. function scrollGap(cm) { return scrollerGap - cm.display.nativeBarWidth; }
  4230. function displayWidth(cm) {
  4231. return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth;
  4232. }
  4233. function displayHeight(cm) {
  4234. return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight;
  4235. }
  4236. // Ensure the lineView.wrapping.heights array is populated. This is
  4237. // an array of bottom offsets for the lines that make up a drawn
  4238. // line. When lineWrapping is on, there might be more than one
  4239. // height.
  4240. function ensureLineHeights(cm, lineView, rect) {
  4241. var wrapping = cm.options.lineWrapping;
  4242. var curWidth = wrapping && displayWidth(cm);
  4243. if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) {
  4244. var heights = lineView.measure.heights = [];
  4245. if (wrapping) {
  4246. lineView.measure.width = curWidth;
  4247. var rects = lineView.text.firstChild.getClientRects();
  4248. for (var i = 0; i < rects.length - 1; i++) {
  4249. var cur = rects[i], next = rects[i + 1];
  4250. if (Math.abs(cur.bottom - next.bottom) > 2)
  4251. heights.push((cur.bottom + next.top) / 2 - rect.top);
  4252. }
  4253. }
  4254. heights.push(rect.bottom - rect.top);
  4255. }
  4256. }
  4257. // Find a line map (mapping character offsets to text nodes) and a
  4258. // measurement cache for the given line number. (A line view might
  4259. // contain multiple lines when collapsed ranges are present.)
  4260. function mapFromLineView(lineView, line, lineN) {
  4261. if (lineView.line == line)
  4262. return {map: lineView.measure.map, cache: lineView.measure.cache};
  4263. for (var i = 0; i < lineView.rest.length; i++)
  4264. if (lineView.rest[i] == line)
  4265. return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i]};
  4266. for (var i = 0; i < lineView.rest.length; i++)
  4267. if (lineNo(lineView.rest[i]) > lineN)
  4268. return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i], before: true};
  4269. }
  4270. // Render a line into the hidden node display.externalMeasured. Used
  4271. // when measurement is needed for a line that's not in the viewport.
  4272. function updateExternalMeasurement(cm, line) {
  4273. line = visualLine(line);
  4274. var lineN = lineNo(line);
  4275. var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN);
  4276. view.lineN = lineN;
  4277. var built = view.built = buildLineContent(cm, view);
  4278. view.text = built.pre;
  4279. removeChildrenAndAdd(cm.display.lineMeasure, built.pre);
  4280. return view;
  4281. }
  4282. // Get a {top, bottom, left, right} box (in line-local coordinates)
  4283. // for a given character.
  4284. function measureChar(cm, line, ch, bias) {
  4285. return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias);
  4286. }
  4287. // Find a line view that corresponds to the given line number.
  4288. function findViewForLine(cm, lineN) {
  4289. if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo)
  4290. return cm.display.view[findViewIndex(cm, lineN)];
  4291. var ext = cm.display.externalMeasured;
  4292. if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size)
  4293. return ext;
  4294. }
  4295. // Measurement can be split in two steps, the set-up work that
  4296. // applies to the whole line, and the measurement of the actual
  4297. // character. Functions like coordsChar, that need to do a lot of
  4298. // measurements in a row, can thus ensure that the set-up work is
  4299. // only done once.
  4300. function prepareMeasureForLine(cm, line) {
  4301. var lineN = lineNo(line);
  4302. var view = findViewForLine(cm, lineN);
  4303. if (view && !view.text) {
  4304. view = null;
  4305. } else if (view && view.changes) {
  4306. updateLineForChanges(cm, view, lineN, getDimensions(cm));
  4307. cm.curOp.forceUpdate = true;
  4308. }
  4309. if (!view)
  4310. view = updateExternalMeasurement(cm, line);
  4311. var info = mapFromLineView(view, line, lineN);
  4312. return {
  4313. line: line, view: view, rect: null,
  4314. map: info.map, cache: info.cache, before: info.before,
  4315. hasHeights: false
  4316. };
  4317. }
  4318. // Given a prepared measurement object, measures the position of an
  4319. // actual character (or fetches it from the cache).
  4320. function measureCharPrepared(cm, prepared, ch, bias, varHeight) {
  4321. if (prepared.before) ch = -1;
  4322. var key = ch + (bias || ""), found;
  4323. if (prepared.cache.hasOwnProperty(key)) {
  4324. found = prepared.cache[key];
  4325. } else {
  4326. if (!prepared.rect)
  4327. prepared.rect = prepared.view.text.getBoundingClientRect();
  4328. if (!prepared.hasHeights) {
  4329. ensureLineHeights(cm, prepared.view, prepared.rect);
  4330. prepared.hasHeights = true;
  4331. }
  4332. found = measureCharInner(cm, prepared, ch, bias);
  4333. if (!found.bogus) prepared.cache[key] = found;
  4334. }
  4335. return {left: found.left, right: found.right,
  4336. top: varHeight ? found.rtop : found.top,
  4337. bottom: varHeight ? found.rbottom : found.bottom};
  4338. }
  4339. var nullRect = {left: 0, right: 0, top: 0, bottom: 0};
  4340. function nodeAndOffsetInLineMap(map, ch, bias) {
  4341. var node, start, end, collapse;
  4342. // First, search the line map for the text node corresponding to,
  4343. // or closest to, the target character.
  4344. for (var i = 0; i < map.length; i += 3) {
  4345. var mStart = map[i], mEnd = map[i + 1];
  4346. if (ch < mStart) {
  4347. start = 0; end = 1;
  4348. collapse = "left";
  4349. } else if (ch < mEnd) {
  4350. start = ch - mStart;
  4351. end = start + 1;
  4352. } else if (i == map.length - 3 || ch == mEnd && map[i + 3] > ch) {
  4353. end = mEnd - mStart;
  4354. start = end - 1;
  4355. if (ch >= mEnd) collapse = "right";
  4356. }
  4357. if (start != null) {
  4358. node = map[i + 2];
  4359. if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right"))
  4360. collapse = bias;
  4361. if (bias == "left" && start == 0)
  4362. while (i && map[i - 2] == map[i - 3] && map[i - 1].insertLeft) {
  4363. node = map[(i -= 3) + 2];
  4364. collapse = "left";
  4365. }
  4366. if (bias == "right" && start == mEnd - mStart)
  4367. while (i < map.length - 3 && map[i + 3] == map[i + 4] && !map[i + 5].insertLeft) {
  4368. node = map[(i += 3) + 2];
  4369. collapse = "right";
  4370. }
  4371. break;
  4372. }
  4373. }
  4374. return {node: node, start: start, end: end, collapse: collapse, coverStart: mStart, coverEnd: mEnd};
  4375. }
  4376. function getUsefulRect(rects, bias) {
  4377. var rect = nullRect
  4378. if (bias == "left") for (var i = 0; i < rects.length; i++) {
  4379. if ((rect = rects[i]).left != rect.right) break
  4380. } else for (var i = rects.length - 1; i >= 0; i--) {
  4381. if ((rect = rects[i]).left != rect.right) break
  4382. }
  4383. return rect
  4384. }
  4385. function measureCharInner(cm, prepared, ch, bias) {
  4386. var place = nodeAndOffsetInLineMap(prepared.map, ch, bias);
  4387. var node = place.node, start = place.start, end = place.end, collapse = place.collapse;
  4388. var rect;
  4389. if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates.
  4390. for (var i = 0; i < 4; i++) { // Retry a maximum of 4 times when nonsense rectangles are returned
  4391. while (start && isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) --start;
  4392. while (place.coverStart + end < place.coverEnd && isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) ++end;
  4393. if (ie && ie_version < 9 && start == 0 && end == place.coverEnd - place.coverStart)
  4394. rect = node.parentNode.getBoundingClientRect();
  4395. else
  4396. rect = getUsefulRect(range(node, start, end).getClientRects(), bias)
  4397. if (rect.left || rect.right || start == 0) break;
  4398. end = start;
  4399. start = start - 1;
  4400. collapse = "right";
  4401. }
  4402. if (ie && ie_version < 11) rect = maybeUpdateRectForZooming(cm.display.measure, rect);
  4403. } else { // If it is a widget, simply get the box for the whole widget.
  4404. if (start > 0) collapse = bias = "right";
  4405. var rects;
  4406. if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1)
  4407. rect = rects[bias == "right" ? rects.length - 1 : 0];
  4408. else
  4409. rect = node.getBoundingClientRect();
  4410. }
  4411. if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) {
  4412. var rSpan = node.parentNode.getClientRects()[0];
  4413. if (rSpan)
  4414. rect = {left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom};
  4415. else
  4416. rect = nullRect;
  4417. }
  4418. var rtop = rect.top - prepared.rect.top, rbot = rect.bottom - prepared.rect.top;
  4419. var mid = (rtop + rbot) / 2;
  4420. var heights = prepared.view.measure.heights;
  4421. for (var i = 0; i < heights.length - 1; i++)
  4422. if (mid < heights[i]) break;
  4423. var top = i ? heights[i - 1] : 0, bot = heights[i];
  4424. var result = {left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left,
  4425. right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left,
  4426. top: top, bottom: bot};
  4427. if (!rect.left && !rect.right) result.bogus = true;
  4428. if (!cm.options.singleCursorHeightPerLine) { result.rtop = rtop; result.rbottom = rbot; }
  4429. return result;
  4430. }
  4431. // Work around problem with bounding client rects on ranges being
  4432. // returned incorrectly when zoomed on IE10 and below.
  4433. function maybeUpdateRectForZooming(measure, rect) {
  4434. if (!window.screen || screen.logicalXDPI == null ||
  4435. screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure))
  4436. return rect;
  4437. var scaleX = screen.logicalXDPI / screen.deviceXDPI;
  4438. var scaleY = screen.logicalYDPI / screen.deviceYDPI;
  4439. return {left: rect.left * scaleX, right: rect.right * scaleX,
  4440. top: rect.top * scaleY, bottom: rect.bottom * scaleY};
  4441. }
  4442. function clearLineMeasurementCacheFor(lineView) {
  4443. if (lineView.measure) {
  4444. lineView.measure.cache = {};
  4445. lineView.measure.heights = null;
  4446. if (lineView.rest) for (var i = 0; i < lineView.rest.length; i++)
  4447. lineView.measure.caches[i] = {};
  4448. }
  4449. }
  4450. function clearLineMeasurementCache(cm) {
  4451. cm.display.externalMeasure = null;
  4452. removeChildren(cm.display.lineMeasure);
  4453. for (var i = 0; i < cm.display.view.length; i++)
  4454. clearLineMeasurementCacheFor(cm.display.view[i]);
  4455. }
  4456. function clearCaches(cm) {
  4457. clearLineMeasurementCache(cm);
  4458. cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null;
  4459. if (!cm.options.lineWrapping) cm.display.maxLineChanged = true;
  4460. cm.display.lineNumChars = null;
  4461. }
  4462. function pageScrollX() { return window.pageXOffset || (document.documentElement || document.body).scrollLeft; }
  4463. function pageScrollY() { return window.pageYOffset || (document.documentElement || document.body).scrollTop; }
  4464. // Converts a {top, bottom, left, right} box from line-local
  4465. // coordinates into another coordinate system. Context may be one of
  4466. // "line", "div" (display.lineDiv), "local"/null (editor), "window",
  4467. // or "page".
  4468. function intoCoordSystem(cm, lineObj, rect, context) {
  4469. if (lineObj.widgets) for (var i = 0; i < lineObj.widgets.length; ++i) if (lineObj.widgets[i].above) {
  4470. var size = widgetHeight(lineObj.widgets[i]);
  4471. rect.top += size; rect.bottom += size;
  4472. }
  4473. if (context == "line") return rect;
  4474. if (!context) context = "local";
  4475. var yOff = heightAtLine(lineObj);
  4476. if (context == "local") yOff += paddingTop(cm.display);
  4477. else yOff -= cm.display.viewOffset;
  4478. if (context == "page" || context == "window") {
  4479. var lOff = cm.display.lineSpace.getBoundingClientRect();
  4480. yOff += lOff.top + (context == "window" ? 0 : pageScrollY());
  4481. var xOff = lOff.left + (context == "window" ? 0 : pageScrollX());
  4482. rect.left += xOff; rect.right += xOff;
  4483. }
  4484. rect.top += yOff; rect.bottom += yOff;
  4485. return rect;
  4486. }
  4487. // Coverts a box from "div" coords to another coordinate system.
  4488. // Context may be "window", "page", "div", or "local"/null.
  4489. function fromCoordSystem(cm, coords, context) {
  4490. if (context == "div") return coords;
  4491. var left = coords.left, top = coords.top;
  4492. // First move into "page" coordinate system
  4493. if (context == "page") {
  4494. left -= pageScrollX();
  4495. top -= pageScrollY();
  4496. } else if (context == "local" || !context) {
  4497. var localBox = cm.display.sizer.getBoundingClientRect();
  4498. left += localBox.left;
  4499. top += localBox.top;
  4500. }
  4501. var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect();
  4502. return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top};
  4503. }
  4504. function charCoords(cm, pos, context, lineObj, bias) {
  4505. if (!lineObj) lineObj = getLine(cm.doc, pos.line);
  4506. return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context);
  4507. }
  4508. // Returns a box for a given cursor position, which may have an
  4509. // 'other' property containing the position of the secondary cursor
  4510. // on a bidi boundary.
  4511. function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) {
  4512. lineObj = lineObj || getLine(cm.doc, pos.line);
  4513. if (!preparedMeasure) preparedMeasure = prepareMeasureForLine(cm, lineObj);
  4514. function get(ch, right) {
  4515. var m = measureCharPrepared(cm, preparedMeasure, ch, right ? "right" : "left", varHeight);
  4516. if (right) m.left = m.right; else m.right = m.left;
  4517. return intoCoordSystem(cm, lineObj, m, context);
  4518. }
  4519. function getBidi(ch, partPos) {
  4520. var part = order[partPos], right = part.level % 2;
  4521. if (ch == bidiLeft(part) && partPos && part.level < order[partPos - 1].level) {
  4522. part = order[--partPos];
  4523. ch = bidiRight(part) - (part.level % 2 ? 0 : 1);
  4524. right = true;
  4525. } else if (ch == bidiRight(part) && partPos < order.length - 1 && part.level < order[partPos + 1].level) {
  4526. part = order[++partPos];
  4527. ch = bidiLeft(part) - part.level % 2;
  4528. right = false;
  4529. }
  4530. if (right && ch == part.to && ch > part.from) return get(ch - 1);
  4531. return get(ch, right);
  4532. }
  4533. var order = getOrder(lineObj), ch = pos.ch;
  4534. if (!order) return get(ch);
  4535. var partPos = getBidiPartAt(order, ch);
  4536. var val = getBidi(ch, partPos);
  4537. if (bidiOther != null) val.other = getBidi(ch, bidiOther);
  4538. return val;
  4539. }
  4540. // Used to cheaply estimate the coordinates for a position. Used for
  4541. // intermediate scroll updates.
  4542. function estimateCoords(cm, pos) {
  4543. var left = 0, pos = clipPos(cm.doc, pos);
  4544. if (!cm.options.lineWrapping) left = charWidth(cm.display) * pos.ch;
  4545. var lineObj = getLine(cm.doc, pos.line);
  4546. var top = heightAtLine(lineObj) + paddingTop(cm.display);
  4547. return {left: left, right: left, top: top, bottom: top + lineObj.height};
  4548. }
  4549. // Positions returned by coordsChar contain some extra information.
  4550. // xRel is the relative x position of the input coordinates compared
  4551. // to the found position (so xRel > 0 means the coordinates are to
  4552. // the right of the character position, for example). When outside
  4553. // is true, that means the coordinates lie outside the line's
  4554. // vertical range.
  4555. function PosWithInfo(line, ch, outside, xRel) {
  4556. var pos = Pos(line, ch);
  4557. pos.xRel = xRel;
  4558. if (outside) pos.outside = true;
  4559. return pos;
  4560. }
  4561. // Compute the character position closest to the given coordinates.
  4562. // Input must be lineSpace-local ("div" coordinate system).
  4563. function coordsChar(cm, x, y) {
  4564. var doc = cm.doc;
  4565. y += cm.display.viewOffset;
  4566. if (y < 0) return PosWithInfo(doc.first, 0, true, -1);
  4567. var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1;
  4568. if (lineN > last)
  4569. return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, true, 1);
  4570. if (x < 0) x = 0;
  4571. var lineObj = getLine(doc, lineN);
  4572. for (;;) {
  4573. var found = coordsCharInner(cm, lineObj, lineN, x, y);
  4574. var merged = collapsedSpanAtEnd(lineObj);
  4575. var mergedPos = merged && merged.find(0, true);
  4576. if (merged && (found.ch > mergedPos.from.ch || found.ch == mergedPos.from.ch && found.xRel > 0))
  4577. lineN = lineNo(lineObj = mergedPos.to.line);
  4578. else
  4579. return found;
  4580. }
  4581. }
  4582. function coordsCharInner(cm, lineObj, lineNo, x, y) {
  4583. var innerOff = y - heightAtLine(lineObj);
  4584. var wrongLine = false, adjust = 2 * cm.display.wrapper.clientWidth;
  4585. var preparedMeasure = prepareMeasureForLine(cm, lineObj);
  4586. function getX(ch) {
  4587. var sp = cursorCoords(cm, Pos(lineNo, ch), "line", lineObj, preparedMeasure);
  4588. wrongLine = true;
  4589. if (innerOff > sp.bottom) return sp.left - adjust;
  4590. else if (innerOff < sp.top) return sp.left + adjust;
  4591. else wrongLine = false;
  4592. return sp.left;
  4593. }
  4594. var bidi = getOrder(lineObj), dist = lineObj.text.length;
  4595. var from = lineLeft(lineObj), to = lineRight(lineObj);
  4596. var fromX = getX(from), fromOutside = wrongLine, toX = getX(to), toOutside = wrongLine;
  4597. if (x > toX) return PosWithInfo(lineNo, to, toOutside, 1);
  4598. // Do a binary search between these bounds.
  4599. for (;;) {
  4600. if (bidi ? to == from || to == moveVisually(lineObj, from, 1) : to - from <= 1) {
  4601. var ch = x < fromX || x - fromX <= toX - x ? from : to;
  4602. var outside = ch == from ? fromOutside : toOutside
  4603. var xDiff = x - (ch == from ? fromX : toX);
  4604. // This is a kludge to handle the case where the coordinates
  4605. // are after a line-wrapped line. We should replace it with a
  4606. // more general handling of cursor positions around line
  4607. // breaks. (Issue #4078)
  4608. if (toOutside && !bidi && !/\s/.test(lineObj.text.charAt(ch)) && xDiff > 0 &&
  4609. ch < lineObj.text.length && preparedMeasure.view.measure.heights.length > 1) {
  4610. var charSize = measureCharPrepared(cm, preparedMeasure, ch, "right");
  4611. if (innerOff <= charSize.bottom && innerOff >= charSize.top && Math.abs(x - charSize.right) < xDiff) {
  4612. outside = false
  4613. ch++
  4614. xDiff = x - charSize.right
  4615. }
  4616. }
  4617. while (isExtendingChar(lineObj.text.charAt(ch))) ++ch;
  4618. var pos = PosWithInfo(lineNo, ch, outside, xDiff < -1 ? -1 : xDiff > 1 ? 1 : 0);
  4619. return pos;
  4620. }
  4621. var step = Math.ceil(dist / 2), middle = from + step;
  4622. if (bidi) {
  4623. middle = from;
  4624. for (var i = 0; i < step; ++i) middle = moveVisually(lineObj, middle, 1);
  4625. }
  4626. var middleX = getX(middle);
  4627. if (middleX > x) {to = middle; toX = middleX; if (toOutside = wrongLine) toX += 1000; dist = step;}
  4628. else {from = middle; fromX = middleX; fromOutside = wrongLine; dist -= step;}
  4629. }
  4630. }
  4631. var measureText;
  4632. // Compute the default text height.
  4633. function textHeight(display) {
  4634. if (display.cachedTextHeight != null) return display.cachedTextHeight;
  4635. if (measureText == null) {
  4636. measureText = elt("pre");
  4637. // Measure a bunch of lines, for browsers that compute
  4638. // fractional heights.
  4639. for (var i = 0; i < 49; ++i) {
  4640. measureText.appendChild(document.createTextNode("x"));
  4641. measureText.appendChild(elt("br"));
  4642. }
  4643. measureText.appendChild(document.createTextNode("x"));
  4644. }
  4645. removeChildrenAndAdd(display.measure, measureText);
  4646. var height = measureText.offsetHeight / 50;
  4647. if (height > 3) display.cachedTextHeight = height;
  4648. removeChildren(display.measure);
  4649. return height || 1;
  4650. }
  4651. // Compute the default character width.
  4652. function charWidth(display) {
  4653. if (display.cachedCharWidth != null) return display.cachedCharWidth;
  4654. var anchor = elt("span", "xxxxxxxxxx");
  4655. var pre = elt("pre", [anchor]);
  4656. removeChildrenAndAdd(display.measure, pre);
  4657. var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10;
  4658. if (width > 2) display.cachedCharWidth = width;
  4659. return width || 10;
  4660. }
  4661. // OPERATIONS
  4662. // Operations are used to wrap a series of changes to the editor
  4663. // state in such a way that each change won't have to update the
  4664. // cursor and display (which would be awkward, slow, and
  4665. // error-prone). Instead, display updates are batched and then all
  4666. // combined and executed at once.
  4667. var operationGroup = null;
  4668. var nextOpId = 0;
  4669. // Start a new operation.
  4670. function startOperation(cm) {
  4671. cm.curOp = {
  4672. cm: cm,
  4673. viewChanged: false, // Flag that indicates that lines might need to be redrawn
  4674. startHeight: cm.doc.height, // Used to detect need to update scrollbar
  4675. forceUpdate: false, // Used to force a redraw
  4676. updateInput: null, // Whether to reset the input textarea
  4677. typing: false, // Whether this reset should be careful to leave existing text (for compositing)
  4678. changeObjs: null, // Accumulated changes, for firing change events
  4679. cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on
  4680. cursorActivityCalled: 0, // Tracks which cursorActivity handlers have been called already
  4681. selectionChanged: false, // Whether the selection needs to be redrawn
  4682. updateMaxLine: false, // Set when the widest line needs to be determined anew
  4683. scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet
  4684. scrollToPos: null, // Used to scroll to a specific position
  4685. focus: false,
  4686. id: ++nextOpId // Unique ID
  4687. };
  4688. if (operationGroup) {
  4689. operationGroup.ops.push(cm.curOp);
  4690. } else {
  4691. cm.curOp.ownsGroup = operationGroup = {
  4692. ops: [cm.curOp],
  4693. delayedCallbacks: []
  4694. };
  4695. }
  4696. }
  4697. function fireCallbacksForOps(group) {
  4698. // Calls delayed callbacks and cursorActivity handlers until no
  4699. // new ones appear
  4700. var callbacks = group.delayedCallbacks, i = 0;
  4701. do {
  4702. for (; i < callbacks.length; i++)
  4703. callbacks[i].call(null);
  4704. for (var j = 0; j < group.ops.length; j++) {
  4705. var op = group.ops[j];
  4706. if (op.cursorActivityHandlers)
  4707. while (op.cursorActivityCalled < op.cursorActivityHandlers.length)
  4708. op.cursorActivityHandlers[op.cursorActivityCalled++].call(null, op.cm);
  4709. }
  4710. } while (i < callbacks.length);
  4711. }
  4712. // Finish an operation, updating the display and signalling delayed events
  4713. function endOperation(cm) {
  4714. var op = cm.curOp, group = op.ownsGroup;
  4715. if (!group) return;
  4716. try { fireCallbacksForOps(group); }
  4717. finally {
  4718. operationGroup = null;
  4719. for (var i = 0; i < group.ops.length; i++)
  4720. group.ops[i].cm.curOp = null;
  4721. endOperations(group);
  4722. }
  4723. }
  4724. // The DOM updates done when an operation finishes are batched so
  4725. // that the minimum number of relayouts are required.
  4726. function endOperations(group) {
  4727. var ops = group.ops;
  4728. for (var i = 0; i < ops.length; i++) // Read DOM
  4729. endOperation_R1(ops[i]);
  4730. for (var i = 0; i < ops.length; i++) // Write DOM (maybe)
  4731. endOperation_W1(ops[i]);
  4732. for (var i = 0; i < ops.length; i++) // Read DOM
  4733. endOperation_R2(ops[i]);
  4734. for (var i = 0; i < ops.length; i++) // Write DOM (maybe)
  4735. endOperation_W2(ops[i]);
  4736. for (var i = 0; i < ops.length; i++) // Read DOM
  4737. endOperation_finish(ops[i]);
  4738. }
  4739. function endOperation_R1(op) {
  4740. var cm = op.cm, display = cm.display;
  4741. maybeClipScrollbars(cm);
  4742. if (op.updateMaxLine) findMaxLine(cm);
  4743. op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null ||
  4744. op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom ||
  4745. op.scrollToPos.to.line >= display.viewTo) ||
  4746. display.maxLineChanged && cm.options.lineWrapping;
  4747. op.update = op.mustUpdate &&
  4748. new DisplayUpdate(cm, op.mustUpdate && {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate);
  4749. }
  4750. function endOperation_W1(op) {
  4751. op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update);
  4752. }
  4753. function endOperation_R2(op) {
  4754. var cm = op.cm, display = cm.display;
  4755. if (op.updatedDisplay) updateHeightsInViewport(cm);
  4756. op.barMeasure = measureForScrollbars(cm);
  4757. // If the max line changed since it was last measured, measure it,
  4758. // and ensure the document's width matches it.
  4759. // updateDisplay_W2 will use these properties to do the actual resizing
  4760. if (display.maxLineChanged && !cm.options.lineWrapping) {
  4761. op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3;
  4762. cm.display.sizerWidth = op.adjustWidthTo;
  4763. op.barMeasure.scrollWidth =
  4764. Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth);
  4765. op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm));
  4766. }
  4767. if (op.updatedDisplay || op.selectionChanged)
  4768. op.preparedSelection = display.input.prepareSelection(op.focus);
  4769. }
  4770. function endOperation_W2(op) {
  4771. var cm = op.cm;
  4772. if (op.adjustWidthTo != null) {
  4773. cm.display.sizer.style.minWidth = op.adjustWidthTo + "px";
  4774. if (op.maxScrollLeft < cm.doc.scrollLeft)
  4775. setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true);
  4776. cm.display.maxLineChanged = false;
  4777. }
  4778. var takeFocus = op.focus && op.focus == activeElt() && (!document.hasFocus || document.hasFocus())
  4779. if (op.preparedSelection)
  4780. cm.display.input.showSelection(op.preparedSelection, takeFocus);
  4781. if (op.updatedDisplay || op.startHeight != cm.doc.height)
  4782. updateScrollbars(cm, op.barMeasure);
  4783. if (op.updatedDisplay)
  4784. setDocumentHeight(cm, op.barMeasure);
  4785. if (op.selectionChanged) restartBlink(cm);
  4786. if (cm.state.focused && op.updateInput)
  4787. cm.display.input.reset(op.typing);
  4788. if (takeFocus) ensureFocus(op.cm);
  4789. }
  4790. function endOperation_finish(op) {
  4791. var cm = op.cm, display = cm.display, doc = cm.doc;
  4792. if (op.updatedDisplay) postUpdateDisplay(cm, op.update);
  4793. // Abort mouse wheel delta measurement, when scrolling explicitly
  4794. if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos))
  4795. display.wheelStartX = display.wheelStartY = null;
  4796. // Propagate the scroll position to the actual DOM scroller
  4797. if (op.scrollTop != null && (display.scroller.scrollTop != op.scrollTop || op.forceScroll)) {
  4798. doc.scrollTop = Math.max(0, Math.min(display.scroller.scrollHeight - display.scroller.clientHeight, op.scrollTop));
  4799. display.scrollbars.setScrollTop(doc.scrollTop);
  4800. display.scroller.scrollTop = doc.scrollTop;
  4801. }
  4802. if (op.scrollLeft != null && (display.scroller.scrollLeft != op.scrollLeft || op.forceScroll)) {
  4803. doc.scrollLeft = Math.max(0, Math.min(display.scroller.scrollWidth - display.scroller.clientWidth, op.scrollLeft));
  4804. display.scrollbars.setScrollLeft(doc.scrollLeft);
  4805. display.scroller.scrollLeft = doc.scrollLeft;
  4806. alignHorizontally(cm);
  4807. }
  4808. // If we need to scroll a specific position into view, do so.
  4809. if (op.scrollToPos) {
  4810. var coords = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from),
  4811. clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin);
  4812. if (op.scrollToPos.isCursor && cm.state.focused) maybeScrollWindow(cm, coords);
  4813. }
  4814. // Fire events for markers that are hidden/unidden by editing or
  4815. // undoing
  4816. var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers;
  4817. if (hidden) for (var i = 0; i < hidden.length; ++i)
  4818. if (!hidden[i].lines.length) signal(hidden[i], "hide");
  4819. if (unhidden) for (var i = 0; i < unhidden.length; ++i)
  4820. if (unhidden[i].lines.length) signal(unhidden[i], "unhide");
  4821. if (display.wrapper.offsetHeight)
  4822. doc.scrollTop = cm.display.scroller.scrollTop;
  4823. // Fire change events, and delayed event handlers
  4824. if (op.changeObjs)
  4825. signal(cm, "changes", cm, op.changeObjs);
  4826. if (op.update)
  4827. op.update.finish();
  4828. }
  4829. // Run the given function in an operation
  4830. function runInOp(cm, f) {
  4831. if (cm.curOp) return f();
  4832. startOperation(cm);
  4833. try { return f(); }
  4834. finally { endOperation(cm); }
  4835. }
  4836. // Wraps a function in an operation. Returns the wrapped function.
  4837. function operation(cm, f) {
  4838. return function() {
  4839. if (cm.curOp) return f.apply(cm, arguments);
  4840. startOperation(cm);
  4841. try { return f.apply(cm, arguments); }
  4842. finally { endOperation(cm); }
  4843. };
  4844. }
  4845. // Used to add methods to editor and doc instances, wrapping them in
  4846. // operations.
  4847. function methodOp(f) {
  4848. return function() {
  4849. if (this.curOp) return f.apply(this, arguments);
  4850. startOperation(this);
  4851. try { return f.apply(this, arguments); }
  4852. finally { endOperation(this); }
  4853. };
  4854. }
  4855. function docMethodOp(f) {
  4856. return function() {
  4857. var cm = this.cm;
  4858. if (!cm || cm.curOp) return f.apply(this, arguments);
  4859. startOperation(cm);
  4860. try { return f.apply(this, arguments); }
  4861. finally { endOperation(cm); }
  4862. };
  4863. }
  4864. // VIEW TRACKING
  4865. // These objects are used to represent the visible (currently drawn)
  4866. // part of the document. A LineView may correspond to multiple
  4867. // logical lines, if those are connected by collapsed ranges.
  4868. function LineView(doc, line, lineN) {
  4869. // The starting line
  4870. this.line = line;
  4871. // Continuing lines, if any
  4872. this.rest = visualLineContinued(line);
  4873. // Number of logical lines in this visual line
  4874. this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1;
  4875. this.node = this.text = null;
  4876. this.hidden = lineIsHidden(doc, line);
  4877. }
  4878. // Create a range of LineView objects for the given lines.
  4879. function buildViewArray(cm, from, to) {
  4880. var array = [], nextPos;
  4881. for (var pos = from; pos < to; pos = nextPos) {
  4882. var view = new LineView(cm.doc, getLine(cm.doc, pos), pos);
  4883. nextPos = pos + view.size;
  4884. array.push(view);
  4885. }
  4886. return array;
  4887. }
  4888. // Updates the display.view data structure for a given change to the
  4889. // document. From and to are in pre-change coordinates. Lendiff is
  4890. // the amount of lines added or subtracted by the change. This is
  4891. // used for changes that span multiple lines, or change the way
  4892. // lines are divided into visual lines. regLineChange (below)
  4893. // registers single-line changes.
  4894. function regChange(cm, from, to, lendiff) {
  4895. if (from == null) from = cm.doc.first;
  4896. if (to == null) to = cm.doc.first + cm.doc.size;
  4897. if (!lendiff) lendiff = 0;
  4898. var display = cm.display;
  4899. if (lendiff && to < display.viewTo &&
  4900. (display.updateLineNumbers == null || display.updateLineNumbers > from))
  4901. display.updateLineNumbers = from;
  4902. cm.curOp.viewChanged = true;
  4903. if (from >= display.viewTo) { // Change after
  4904. if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo)
  4905. resetView(cm);
  4906. } else if (to <= display.viewFrom) { // Change before
  4907. if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) {
  4908. resetView(cm);
  4909. } else {
  4910. display.viewFrom += lendiff;
  4911. display.viewTo += lendiff;
  4912. }
  4913. } else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap
  4914. resetView(cm);
  4915. } else if (from <= display.viewFrom) { // Top overlap
  4916. var cut = viewCuttingPoint(cm, to, to + lendiff, 1);
  4917. if (cut) {
  4918. display.view = display.view.slice(cut.index);
  4919. display.viewFrom = cut.lineN;
  4920. display.viewTo += lendiff;
  4921. } else {
  4922. resetView(cm);
  4923. }
  4924. } else if (to >= display.viewTo) { // Bottom overlap
  4925. var cut = viewCuttingPoint(cm, from, from, -1);
  4926. if (cut) {
  4927. display.view = display.view.slice(0, cut.index);
  4928. display.viewTo = cut.lineN;
  4929. } else {
  4930. resetView(cm);
  4931. }
  4932. } else { // Gap in the middle
  4933. var cutTop = viewCuttingPoint(cm, from, from, -1);
  4934. var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1);
  4935. if (cutTop && cutBot) {
  4936. display.view = display.view.slice(0, cutTop.index)
  4937. .concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN))
  4938. .concat(display.view.slice(cutBot.index));
  4939. display.viewTo += lendiff;
  4940. } else {
  4941. resetView(cm);
  4942. }
  4943. }
  4944. var ext = display.externalMeasured;
  4945. if (ext) {
  4946. if (to < ext.lineN)
  4947. ext.lineN += lendiff;
  4948. else if (from < ext.lineN + ext.size)
  4949. display.externalMeasured = null;
  4950. }
  4951. }
  4952. // Register a change to a single line. Type must be one of "text",
  4953. // "gutter", "class", "widget"
  4954. function regLineChange(cm, line, type) {
  4955. cm.curOp.viewChanged = true;
  4956. var display = cm.display, ext = cm.display.externalMeasured;
  4957. if (ext && line >= ext.lineN && line < ext.lineN + ext.size)
  4958. display.externalMeasured = null;
  4959. if (line < display.viewFrom || line >= display.viewTo) return;
  4960. var lineView = display.view[findViewIndex(cm, line)];
  4961. if (lineView.node == null) return;
  4962. var arr = lineView.changes || (lineView.changes = []);
  4963. if (indexOf(arr, type) == -1) arr.push(type);
  4964. }
  4965. // Clear the view.
  4966. function resetView(cm) {
  4967. cm.display.viewFrom = cm.display.viewTo = cm.doc.first;
  4968. cm.display.view = [];
  4969. cm.display.viewOffset = 0;
  4970. }
  4971. // Find the view element corresponding to a given line. Return null
  4972. // when the line isn't visible.
  4973. function findViewIndex(cm, n) {
  4974. if (n >= cm.display.viewTo) return null;
  4975. n -= cm.display.viewFrom;
  4976. if (n < 0) return null;
  4977. var view = cm.display.view;
  4978. for (var i = 0; i < view.length; i++) {
  4979. n -= view[i].size;
  4980. if (n < 0) return i;
  4981. }
  4982. }
  4983. function viewCuttingPoint(cm, oldN, newN, dir) {
  4984. var index = findViewIndex(cm, oldN), diff, view = cm.display.view;
  4985. if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size)
  4986. return {index: index, lineN: newN};
  4987. for (var i = 0, n = cm.display.viewFrom; i < index; i++)
  4988. n += view[i].size;
  4989. if (n != oldN) {
  4990. if (dir > 0) {
  4991. if (index == view.length - 1) return null;
  4992. diff = (n + view[index].size) - oldN;
  4993. index++;
  4994. } else {
  4995. diff = n - oldN;
  4996. }
  4997. oldN += diff; newN += diff;
  4998. }
  4999. while (visualLineNo(cm.doc, newN) != newN) {
  5000. if (index == (dir < 0 ? 0 : view.length - 1)) return null;
  5001. newN += dir * view[index - (dir < 0 ? 1 : 0)].size;
  5002. index += dir;
  5003. }
  5004. return {index: index, lineN: newN};
  5005. }
  5006. // Force the view to cover a given range, adding empty view element
  5007. // or clipping off existing ones as needed.
  5008. function adjustView(cm, from, to) {
  5009. var display = cm.display, view = display.view;
  5010. if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) {
  5011. display.view = buildViewArray(cm, from, to);
  5012. display.viewFrom = from;
  5013. } else {
  5014. if (display.viewFrom > from)
  5015. display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view);
  5016. else if (display.viewFrom < from)
  5017. display.view = display.view.slice(findViewIndex(cm, from));
  5018. display.viewFrom = from;
  5019. if (display.viewTo < to)
  5020. display.view = display.view.concat(buildViewArray(cm, display.viewTo, to));
  5021. else if (display.viewTo > to)
  5022. display.view = display.view.slice(0, findViewIndex(cm, to));
  5023. }
  5024. display.viewTo = to;
  5025. }
  5026. // Count the number of lines in the view whose DOM representation is
  5027. // out of date (or nonexistent).
  5028. function countDirtyView(cm) {
  5029. var view = cm.display.view, dirty = 0;
  5030. for (var i = 0; i < view.length; i++) {
  5031. var lineView = view[i];
  5032. if (!lineView.hidden && (!lineView.node || lineView.changes)) ++dirty;
  5033. }
  5034. return dirty;
  5035. }
  5036. // EVENT HANDLERS
  5037. // Attach the necessary event handlers when initializing the editor
  5038. function registerEventHandlers(cm) {
  5039. var d = cm.display;
  5040. on(d.scroller, "mousedown", operation(cm, onMouseDown));
  5041. // Older IE's will not fire a second mousedown for a double click
  5042. if (ie && ie_version < 11)
  5043. on(d.scroller, "dblclick", operation(cm, function(e) {
  5044. if (signalDOMEvent(cm, e)) return;
  5045. var pos = posFromMouse(cm, e);
  5046. if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) return;
  5047. e_preventDefault(e);
  5048. var word = cm.findWordAt(pos);
  5049. extendSelection(cm.doc, word.anchor, word.head);
  5050. }));
  5051. else
  5052. on(d.scroller, "dblclick", function(e) { signalDOMEvent(cm, e) || e_preventDefault(e); });
  5053. // Some browsers fire contextmenu *after* opening the menu, at
  5054. // which point we can't mess with it anymore. Context menu is
  5055. // handled in onMouseDown for these browsers.
  5056. if (!captureRightClick) on(d.scroller, "contextmenu", function(e) {onContextMenu(cm, e);});
  5057. // Used to suppress mouse event handling when a touch happens
  5058. var touchFinished, prevTouch = {end: 0};
  5059. function finishTouch() {
  5060. if (d.activeTouch) {
  5061. touchFinished = setTimeout(function() {d.activeTouch = null;}, 1000);
  5062. prevTouch = d.activeTouch;
  5063. prevTouch.end = +new Date;
  5064. }
  5065. };
  5066. function isMouseLikeTouchEvent(e) {
  5067. if (e.touches.length != 1) return false;
  5068. var touch = e.touches[0];
  5069. return touch.radiusX <= 1 && touch.radiusY <= 1;
  5070. }
  5071. function farAway(touch, other) {
  5072. if (other.left == null) return true;
  5073. var dx = other.left - touch.left, dy = other.top - touch.top;
  5074. return dx * dx + dy * dy > 20 * 20;
  5075. }
  5076. on(d.scroller, "touchstart", function(e) {
  5077. if (!signalDOMEvent(cm, e) && !isMouseLikeTouchEvent(e)) {
  5078. clearTimeout(touchFinished);
  5079. var now = +new Date;
  5080. d.activeTouch = {start: now, moved: false,
  5081. prev: now - prevTouch.end <= 300 ? prevTouch : null};
  5082. if (e.touches.length == 1) {
  5083. d.activeTouch.left = e.touches[0].pageX;
  5084. d.activeTouch.top = e.touches[0].pageY;
  5085. }
  5086. }
  5087. });
  5088. on(d.scroller, "touchmove", function() {
  5089. if (d.activeTouch) d.activeTouch.moved = true;
  5090. });
  5091. on(d.scroller, "touchend", function(e) {
  5092. var touch = d.activeTouch;
  5093. if (touch && !eventInWidget(d, e) && touch.left != null &&
  5094. !touch.moved && new Date - touch.start < 300) {
  5095. var pos = cm.coordsChar(d.activeTouch, "page"), range;
  5096. if (!touch.prev || farAway(touch, touch.prev)) // Single tap
  5097. range = new Range(pos, pos);
  5098. else if (!touch.prev.prev || farAway(touch, touch.prev.prev)) // Double tap
  5099. range = cm.findWordAt(pos);
  5100. else // Triple tap
  5101. range = new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0)));
  5102. cm.setSelection(range.anchor, range.head);
  5103. cm.focus();
  5104. e_preventDefault(e);
  5105. }
  5106. finishTouch();
  5107. });
  5108. on(d.scroller, "touchcancel", finishTouch);
  5109. // Sync scrolling between fake scrollbars and real scrollable
  5110. // area, ensure viewport is updated when scrolling.
  5111. on(d.scroller, "scroll", function() {
  5112. if (d.scroller.clientHeight) {
  5113. setScrollTop(cm, d.scroller.scrollTop);
  5114. setScrollLeft(cm, d.scroller.scrollLeft, true);
  5115. signal(cm, "scroll", cm);
  5116. }
  5117. });
  5118. // Listen to wheel events in order to try and update the viewport on time.
  5119. on(d.scroller, "mousewheel", function(e){onScrollWheel(cm, e);});
  5120. on(d.scroller, "DOMMouseScroll", function(e){onScrollWheel(cm, e);});
  5121. // Prevent wrapper from ever scrolling
  5122. on(d.wrapper, "scroll", function() { d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; });
  5123. d.dragFunctions = {
  5124. enter: function(e) {if (!signalDOMEvent(cm, e)) e_stop(e);},
  5125. over: function(e) {if (!signalDOMEvent(cm, e)) { onDragOver(cm, e); e_stop(e); }},
  5126. start: function(e){onDragStart(cm, e);},
  5127. drop: operation(cm, onDrop),
  5128. leave: function(e) {if (!signalDOMEvent(cm, e)) { clearDragCursor(cm); }}
  5129. };
  5130. var inp = d.input.getField();
  5131. on(inp, "keyup", function(e) { onKeyUp.call(cm, e); });
  5132. on(inp, "keydown", operation(cm, onKeyDown));
  5133. on(inp, "keypress", operation(cm, onKeyPress));
  5134. on(inp, "focus", bind(onFocus, cm));
  5135. on(inp, "blur", bind(onBlur, cm));
  5136. }
  5137. function dragDropChanged(cm, value, old) {
  5138. var wasOn = old && old != CodeMirror.Init;
  5139. if (!value != !wasOn) {
  5140. var funcs = cm.display.dragFunctions;
  5141. var toggle = value ? on : off;
  5142. toggle(cm.display.scroller, "dragstart", funcs.start);
  5143. toggle(cm.display.scroller, "dragenter", funcs.enter);
  5144. toggle(cm.display.scroller, "dragover", funcs.over);
  5145. toggle(cm.display.scroller, "dragleave", funcs.leave);
  5146. toggle(cm.display.scroller, "drop", funcs.drop);
  5147. }
  5148. }
  5149. // Called when the window resizes
  5150. function onResize(cm) {
  5151. var d = cm.display;
  5152. if (d.lastWrapHeight == d.wrapper.clientHeight && d.lastWrapWidth == d.wrapper.clientWidth)
  5153. return;
  5154. // Might be a text scaling operation, clear size caches.
  5155. d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
  5156. d.scrollbarsClipped = false;
  5157. cm.setSize();
  5158. }
  5159. // MOUSE EVENTS
  5160. // Return true when the given mouse event happened in a widget
  5161. function eventInWidget(display, e) {
  5162. for (var n = e_target(e); n != display.wrapper; n = n.parentNode) {
  5163. if (!n || (n.nodeType == 1 && n.getAttribute("cm-ignore-events") == "true") ||
  5164. (n.parentNode == display.sizer && n != display.mover))
  5165. return true;
  5166. }
  5167. }
  5168. // Given a mouse event, find the corresponding position. If liberal
  5169. // is false, it checks whether a gutter or scrollbar was clicked,
  5170. // and returns null if it was. forRect is used by rectangular
  5171. // selections, and tries to estimate a character position even for
  5172. // coordinates beyond the right of the text.
  5173. function posFromMouse(cm, e, liberal, forRect) {
  5174. var display = cm.display;
  5175. if (!liberal && e_target(e).getAttribute("cm-not-content") == "true") return null;
  5176. var x, y, space = display.lineSpace.getBoundingClientRect();
  5177. // Fails unpredictably on IE[67] when mouse is dragged around quickly.
  5178. try { x = e.clientX - space.left; y = e.clientY - space.top; }
  5179. catch (e) { return null; }
  5180. var coords = coordsChar(cm, x, y), line;
  5181. if (forRect && coords.xRel == 1 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) {
  5182. var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length;
  5183. coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff));
  5184. }
  5185. return coords;
  5186. }
  5187. // A mouse down can be a single click, double click, triple click,
  5188. // start of selection drag, start of text drag, new cursor
  5189. // (ctrl-click), rectangle drag (alt-drag), or xwin
  5190. // middle-click-paste. Or it might be a click on something we should
  5191. // not interfere with, such as a scrollbar or widget.
  5192. function onMouseDown(e) {
  5193. var cm = this, display = cm.display;
  5194. if (signalDOMEvent(cm, e) || display.activeTouch && display.input.supportsTouch()) return;
  5195. display.shift = e.shiftKey;
  5196. if (eventInWidget(display, e)) {
  5197. if (!webkit) {
  5198. // Briefly turn off draggability, to allow widgets to do
  5199. // normal dragging things.
  5200. display.scroller.draggable = false;
  5201. setTimeout(function(){display.scroller.draggable = true;}, 100);
  5202. }
  5203. return;
  5204. }
  5205. if (clickInGutter(cm, e)) return;
  5206. var start = posFromMouse(cm, e);
  5207. window.focus();
  5208. switch (e_button(e)) {
  5209. case 1:
  5210. // #3261: make sure, that we're not starting a second selection
  5211. if (cm.state.selectingText)
  5212. cm.state.selectingText(e);
  5213. else if (start)
  5214. leftButtonDown(cm, e, start);
  5215. else if (e_target(e) == display.scroller)
  5216. e_preventDefault(e);
  5217. break;
  5218. case 2:
  5219. if (webkit) cm.state.lastMiddleDown = +new Date;
  5220. if (start) extendSelection(cm.doc, start);
  5221. setTimeout(function() {display.input.focus();}, 20);
  5222. e_preventDefault(e);
  5223. break;
  5224. case 3:
  5225. if (captureRightClick) onContextMenu(cm, e);
  5226. else delayBlurEvent(cm);
  5227. break;
  5228. }
  5229. }
  5230. var lastClick, lastDoubleClick;
  5231. function leftButtonDown(cm, e, start) {
  5232. if (ie) setTimeout(bind(ensureFocus, cm), 0);
  5233. else cm.curOp.focus = activeElt();
  5234. var now = +new Date, type;
  5235. if (lastDoubleClick && lastDoubleClick.time > now - 400 && cmp(lastDoubleClick.pos, start) == 0) {
  5236. type = "triple";
  5237. } else if (lastClick && lastClick.time > now - 400 && cmp(lastClick.pos, start) == 0) {
  5238. type = "double";
  5239. lastDoubleClick = {time: now, pos: start};
  5240. } else {
  5241. type = "single";
  5242. lastClick = {time: now, pos: start};
  5243. }
  5244. var sel = cm.doc.sel, modifier = mac ? e.metaKey : e.ctrlKey, contained;
  5245. if (cm.options.dragDrop && dragAndDrop && !cm.isReadOnly() &&
  5246. type == "single" && (contained = sel.contains(start)) > -1 &&
  5247. (cmp((contained = sel.ranges[contained]).from(), start) < 0 || start.xRel > 0) &&
  5248. (cmp(contained.to(), start) > 0 || start.xRel < 0))
  5249. leftButtonStartDrag(cm, e, start, modifier);
  5250. else
  5251. leftButtonSelect(cm, e, start, type, modifier);
  5252. }
  5253. // Start a text drag. When it ends, see if any dragging actually
  5254. // happen, and treat as a click if it didn't.
  5255. function leftButtonStartDrag(cm, e, start, modifier) {
  5256. var display = cm.display, startTime = +new Date;
  5257. var dragEnd = operation(cm, function(e2) {
  5258. if (webkit) display.scroller.draggable = false;
  5259. cm.state.draggingText = false;
  5260. off(document, "mouseup", dragEnd);
  5261. off(display.scroller, "drop", dragEnd);
  5262. if (Math.abs(e.clientX - e2.clientX) + Math.abs(e.clientY - e2.clientY) < 10) {
  5263. e_preventDefault(e2);
  5264. if (!modifier && +new Date - 200 < startTime)
  5265. extendSelection(cm.doc, start);
  5266. // Work around unexplainable focus problem in IE9 (#2127) and Chrome (#3081)
  5267. if (webkit || ie && ie_version == 9)
  5268. setTimeout(function() {document.body.focus(); display.input.focus();}, 20);
  5269. else
  5270. display.input.focus();
  5271. }
  5272. });
  5273. // Let the drag handler handle this.
  5274. if (webkit) display.scroller.draggable = true;
  5275. cm.state.draggingText = dragEnd;
  5276. dragEnd.copy = mac ? e.altKey : e.ctrlKey
  5277. // IE's approach to draggable
  5278. if (display.scroller.dragDrop) display.scroller.dragDrop();
  5279. on(document, "mouseup", dragEnd);
  5280. on(display.scroller, "drop", dragEnd);
  5281. }
  5282. // Normal selection, as opposed to text dragging.
  5283. function leftButtonSelect(cm, e, start, type, addNew) {
  5284. var display = cm.display, doc = cm.doc;
  5285. e_preventDefault(e);
  5286. var ourRange, ourIndex, startSel = doc.sel, ranges = startSel.ranges;
  5287. if (addNew && !e.shiftKey) {
  5288. ourIndex = doc.sel.contains(start);
  5289. if (ourIndex > -1)
  5290. ourRange = ranges[ourIndex];
  5291. else
  5292. ourRange = new Range(start, start);
  5293. } else {
  5294. ourRange = doc.sel.primary();
  5295. ourIndex = doc.sel.primIndex;
  5296. }
  5297. if (chromeOS ? e.shiftKey && e.metaKey : e.altKey) {
  5298. type = "rect";
  5299. if (!addNew) ourRange = new Range(start, start);
  5300. start = posFromMouse(cm, e, true, true);
  5301. ourIndex = -1;
  5302. } else if (type == "double") {
  5303. var word = cm.findWordAt(start);
  5304. if (cm.display.shift || doc.extend)
  5305. ourRange = extendRange(doc, ourRange, word.anchor, word.head);
  5306. else
  5307. ourRange = word;
  5308. } else if (type == "triple") {
  5309. var line = new Range(Pos(start.line, 0), clipPos(doc, Pos(start.line + 1, 0)));
  5310. if (cm.display.shift || doc.extend)
  5311. ourRange = extendRange(doc, ourRange, line.anchor, line.head);
  5312. else
  5313. ourRange = line;
  5314. } else {
  5315. ourRange = extendRange(doc, ourRange, start);
  5316. }
  5317. if (!addNew) {
  5318. ourIndex = 0;
  5319. setSelection(doc, new Selection([ourRange], 0), sel_mouse);
  5320. startSel = doc.sel;
  5321. } else if (ourIndex == -1) {
  5322. ourIndex = ranges.length;
  5323. setSelection(doc, normalizeSelection(ranges.concat([ourRange]), ourIndex),
  5324. {scroll: false, origin: "*mouse"});
  5325. } else if (ranges.length > 1 && ranges[ourIndex].empty() && type == "single" && !e.shiftKey) {
  5326. setSelection(doc, normalizeSelection(ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0),
  5327. {scroll: false, origin: "*mouse"});
  5328. startSel = doc.sel;
  5329. } else {
  5330. replaceOneSelection(doc, ourIndex, ourRange, sel_mouse);
  5331. }
  5332. var lastPos = start;
  5333. function extendTo(pos) {
  5334. if (cmp(lastPos, pos) == 0) return;
  5335. lastPos = pos;
  5336. if (type == "rect") {
  5337. var ranges = [], tabSize = cm.options.tabSize;
  5338. var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize);
  5339. var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize);
  5340. var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol);
  5341. for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line));
  5342. line <= end; line++) {
  5343. var text = getLine(doc, line).text, leftPos = findColumn(text, left, tabSize);
  5344. if (left == right)
  5345. ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos)));
  5346. else if (text.length > leftPos)
  5347. ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize))));
  5348. }
  5349. if (!ranges.length) ranges.push(new Range(start, start));
  5350. setSelection(doc, normalizeSelection(startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex),
  5351. {origin: "*mouse", scroll: false});
  5352. cm.scrollIntoView(pos);
  5353. } else {
  5354. var oldRange = ourRange;
  5355. var anchor = oldRange.anchor, head = pos;
  5356. if (type != "single") {
  5357. if (type == "double")
  5358. var range = cm.findWordAt(pos);
  5359. else
  5360. var range = new Range(Pos(pos.line, 0), clipPos(doc, Pos(pos.line + 1, 0)));
  5361. if (cmp(range.anchor, anchor) > 0) {
  5362. head = range.head;
  5363. anchor = minPos(oldRange.from(), range.anchor);
  5364. } else {
  5365. head = range.anchor;
  5366. anchor = maxPos(oldRange.to(), range.head);
  5367. }
  5368. }
  5369. var ranges = startSel.ranges.slice(0);
  5370. ranges[ourIndex] = new Range(clipPos(doc, anchor), head);
  5371. setSelection(doc, normalizeSelection(ranges, ourIndex), sel_mouse);
  5372. }
  5373. }
  5374. var editorSize = display.wrapper.getBoundingClientRect();
  5375. // Used to ensure timeout re-tries don't fire when another extend
  5376. // happened in the meantime (clearTimeout isn't reliable -- at
  5377. // least on Chrome, the timeouts still happen even when cleared,
  5378. // if the clear happens after their scheduled firing time).
  5379. var counter = 0;
  5380. function extend(e) {
  5381. var curCount = ++counter;
  5382. var cur = posFromMouse(cm, e, true, type == "rect");
  5383. if (!cur) return;
  5384. if (cmp(cur, lastPos) != 0) {
  5385. cm.curOp.focus = activeElt();
  5386. extendTo(cur);
  5387. var visible = visibleLines(display, doc);
  5388. if (cur.line >= visible.to || cur.line < visible.from)
  5389. setTimeout(operation(cm, function(){if (counter == curCount) extend(e);}), 150);
  5390. } else {
  5391. var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0;
  5392. if (outside) setTimeout(operation(cm, function() {
  5393. if (counter != curCount) return;
  5394. display.scroller.scrollTop += outside;
  5395. extend(e);
  5396. }), 50);
  5397. }
  5398. }
  5399. function done(e) {
  5400. cm.state.selectingText = false;
  5401. counter = Infinity;
  5402. e_preventDefault(e);
  5403. display.input.focus();
  5404. off(document, "mousemove", move);
  5405. off(document, "mouseup", up);
  5406. doc.history.lastSelOrigin = null;
  5407. }
  5408. var move = operation(cm, function(e) {
  5409. if (!e_button(e)) done(e);
  5410. else extend(e);
  5411. });
  5412. var up = operation(cm, done);
  5413. cm.state.selectingText = up;
  5414. on(document, "mousemove", move);
  5415. on(document, "mouseup", up);
  5416. }
  5417. // Determines whether an event happened in the gutter, and fires the
  5418. // handlers for the corresponding event.
  5419. function gutterEvent(cm, e, type, prevent) {
  5420. try { var mX = e.clientX, mY = e.clientY; }
  5421. catch(e) { return false; }
  5422. if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) return false;
  5423. if (prevent) e_preventDefault(e);
  5424. var display = cm.display;
  5425. var lineBox = display.lineDiv.getBoundingClientRect();
  5426. if (mY > lineBox.bottom || !hasHandler(cm, type)) return e_defaultPrevented(e);
  5427. mY -= lineBox.top - display.viewOffset;
  5428. for (var i = 0; i < cm.options.gutters.length; ++i) {
  5429. var g = display.gutters.childNodes[i];
  5430. if (g && g.getBoundingClientRect().right >= mX) {
  5431. var line = lineAtHeight(cm.doc, mY);
  5432. var gutter = cm.options.gutters[i];
  5433. signal(cm, type, cm, line, gutter, e);
  5434. return e_defaultPrevented(e);
  5435. }
  5436. }
  5437. }
  5438. function clickInGutter(cm, e) {
  5439. return gutterEvent(cm, e, "gutterClick", true);
  5440. }
  5441. // Kludge to work around strange IE behavior where it'll sometimes
  5442. // re-fire a series of drag-related events right after the drop (#1551)
  5443. var lastDrop = 0;
  5444. function onDrop(e) {
  5445. var cm = this;
  5446. clearDragCursor(cm);
  5447. if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e))
  5448. return;
  5449. e_preventDefault(e);
  5450. if (ie) lastDrop = +new Date;
  5451. var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files;
  5452. if (!pos || cm.isReadOnly()) return;
  5453. // Might be a file drop, in which case we simply extract the text
  5454. // and insert it.
  5455. if (files && files.length && window.FileReader && window.File) {
  5456. var n = files.length, text = Array(n), read = 0;
  5457. var loadFile = function(file, i) {
  5458. if (cm.options.allowDropFileTypes &&
  5459. indexOf(cm.options.allowDropFileTypes, file.type) == -1)
  5460. return;
  5461. var reader = new FileReader;
  5462. reader.onload = operation(cm, function() {
  5463. var content = reader.result;
  5464. if (/[\x00-\x08\x0e-\x1f]{2}/.test(content)) content = "";
  5465. text[i] = content;
  5466. if (++read == n) {
  5467. pos = clipPos(cm.doc, pos);
  5468. var change = {from: pos, to: pos,
  5469. text: cm.doc.splitLines(text.join(cm.doc.lineSeparator())),
  5470. origin: "paste"};
  5471. makeChange(cm.doc, change);
  5472. setSelectionReplaceHistory(cm.doc, simpleSelection(pos, changeEnd(change)));
  5473. }
  5474. });
  5475. reader.readAsText(file);
  5476. };
  5477. for (var i = 0; i < n; ++i) loadFile(files[i], i);
  5478. } else { // Normal drop
  5479. // Don't do a replace if the drop happened inside of the selected text.
  5480. if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) {
  5481. cm.state.draggingText(e);
  5482. // Ensure the editor is re-focused
  5483. setTimeout(function() {cm.display.input.focus();}, 20);
  5484. return;
  5485. }
  5486. try {
  5487. var text = e.dataTransfer.getData("Text");
  5488. if (text) {
  5489. if (cm.state.draggingText && !cm.state.draggingText.copy)
  5490. var selected = cm.listSelections();
  5491. setSelectionNoUndo(cm.doc, simpleSelection(pos, pos));
  5492. if (selected) for (var i = 0; i < selected.length; ++i)
  5493. replaceRange(cm.doc, "", selected[i].anchor, selected[i].head, "drag");
  5494. cm.replaceSelection(text, "around", "paste");
  5495. cm.display.input.focus();
  5496. }
  5497. }
  5498. catch(e){}
  5499. }
  5500. }
  5501. function onDragStart(cm, e) {
  5502. if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return; }
  5503. if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) return;
  5504. e.dataTransfer.setData("Text", cm.getSelection());
  5505. e.dataTransfer.effectAllowed = "copyMove"
  5506. // Use dummy image instead of default browsers image.
  5507. // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there.
  5508. if (e.dataTransfer.setDragImage && !safari) {
  5509. var img = elt("img", null, null, "position: fixed; left: 0; top: 0;");
  5510. img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";
  5511. if (presto) {
  5512. img.width = img.height = 1;
  5513. cm.display.wrapper.appendChild(img);
  5514. // Force a relayout, or Opera won't use our image for some obscure reason
  5515. img._top = img.offsetTop;
  5516. }
  5517. e.dataTransfer.setDragImage(img, 0, 0);
  5518. if (presto) img.parentNode.removeChild(img);
  5519. }
  5520. }
  5521. function onDragOver(cm, e) {
  5522. var pos = posFromMouse(cm, e);
  5523. if (!pos) return;
  5524. var frag = document.createDocumentFragment();
  5525. drawSelectionCursor(cm, pos, frag);
  5526. if (!cm.display.dragCursor) {
  5527. cm.display.dragCursor = elt("div", null, "CodeMirror-cursors CodeMirror-dragcursors");
  5528. cm.display.lineSpace.insertBefore(cm.display.dragCursor, cm.display.cursorDiv);
  5529. }
  5530. removeChildrenAndAdd(cm.display.dragCursor, frag);
  5531. }
  5532. function clearDragCursor(cm) {
  5533. if (cm.display.dragCursor) {
  5534. cm.display.lineSpace.removeChild(cm.display.dragCursor);
  5535. cm.display.dragCursor = null;
  5536. }
  5537. }
  5538. // SCROLL EVENTS
  5539. // Sync the scrollable area and scrollbars, ensure the viewport
  5540. // covers the visible area.
  5541. function setScrollTop(cm, val) {
  5542. if (Math.abs(cm.doc.scrollTop - val) < 2) return;
  5543. cm.doc.scrollTop = val;
  5544. if (!gecko) updateDisplaySimple(cm, {top: val});
  5545. if (cm.display.scroller.scrollTop != val) cm.display.scroller.scrollTop = val;
  5546. cm.display.scrollbars.setScrollTop(val);
  5547. if (gecko) updateDisplaySimple(cm);
  5548. startWorker(cm, 100);
  5549. }
  5550. // Sync scroller and scrollbar, ensure the gutter elements are
  5551. // aligned.
  5552. function setScrollLeft(cm, val, isScroller) {
  5553. if (isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) return;
  5554. val = Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth);
  5555. cm.doc.scrollLeft = val;
  5556. alignHorizontally(cm);
  5557. if (cm.display.scroller.scrollLeft != val) cm.display.scroller.scrollLeft = val;
  5558. cm.display.scrollbars.setScrollLeft(val);
  5559. }
  5560. // Since the delta values reported on mouse wheel events are
  5561. // unstandardized between browsers and even browser versions, and
  5562. // generally horribly unpredictable, this code starts by measuring
  5563. // the scroll effect that the first few mouse wheel events have,
  5564. // and, from that, detects the way it can convert deltas to pixel
  5565. // offsets afterwards.
  5566. //
  5567. // The reason we want to know the amount a wheel event will scroll
  5568. // is that it gives us a chance to update the display before the
  5569. // actual scrolling happens, reducing flickering.
  5570. var wheelSamples = 0, wheelPixelsPerUnit = null;
  5571. // Fill in a browser-detected starting value on browsers where we
  5572. // know one. These don't have to be accurate -- the result of them
  5573. // being wrong would just be a slight flicker on the first wheel
  5574. // scroll (if it is large enough).
  5575. if (ie) wheelPixelsPerUnit = -.53;
  5576. else if (gecko) wheelPixelsPerUnit = 15;
  5577. else if (chrome) wheelPixelsPerUnit = -.7;
  5578. else if (safari) wheelPixelsPerUnit = -1/3;
  5579. var wheelEventDelta = function(e) {
  5580. var dx = e.wheelDeltaX, dy = e.wheelDeltaY;
  5581. if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) dx = e.detail;
  5582. if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) dy = e.detail;
  5583. else if (dy == null) dy = e.wheelDelta;
  5584. return {x: dx, y: dy};
  5585. };
  5586. CodeMirror.wheelEventPixels = function(e) {
  5587. var delta = wheelEventDelta(e);
  5588. delta.x *= wheelPixelsPerUnit;
  5589. delta.y *= wheelPixelsPerUnit;
  5590. return delta;
  5591. };
  5592. function onScrollWheel(cm, e) {
  5593. var delta = wheelEventDelta(e), dx = delta.x, dy = delta.y;
  5594. var display = cm.display, scroll = display.scroller;
  5595. // Quit if there's nothing to scroll here
  5596. var canScrollX = scroll.scrollWidth > scroll.clientWidth;
  5597. var canScrollY = scroll.scrollHeight > scroll.clientHeight;
  5598. if (!(dx && canScrollX || dy && canScrollY)) return;
  5599. // Webkit browsers on OS X abort momentum scrolls when the target
  5600. // of the scroll event is removed from the scrollable element.
  5601. // This hack (see related code in patchDisplay) makes sure the
  5602. // element is kept around.
  5603. if (dy && mac && webkit) {
  5604. outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) {
  5605. for (var i = 0; i < view.length; i++) {
  5606. if (view[i].node == cur) {
  5607. cm.display.currentWheelTarget = cur;
  5608. break outer;
  5609. }
  5610. }
  5611. }
  5612. }
  5613. // On some browsers, horizontal scrolling will cause redraws to
  5614. // happen before the gutter has been realigned, causing it to
  5615. // wriggle around in a most unseemly way. When we have an
  5616. // estimated pixels/delta value, we just handle horizontal
  5617. // scrolling entirely here. It'll be slightly off from native, but
  5618. // better than glitching out.
  5619. if (dx && !gecko && !presto && wheelPixelsPerUnit != null) {
  5620. if (dy && canScrollY)
  5621. setScrollTop(cm, Math.max(0, Math.min(scroll.scrollTop + dy * wheelPixelsPerUnit, scroll.scrollHeight - scroll.clientHeight)));
  5622. setScrollLeft(cm, Math.max(0, Math.min(scroll.scrollLeft + dx * wheelPixelsPerUnit, scroll.scrollWidth - scroll.clientWidth)));
  5623. // Only prevent default scrolling if vertical scrolling is
  5624. // actually possible. Otherwise, it causes vertical scroll
  5625. // jitter on OSX trackpads when deltaX is small and deltaY
  5626. // is large (issue #3579)
  5627. if (!dy || (dy && canScrollY))
  5628. e_preventDefault(e);
  5629. display.wheelStartX = null; // Abort measurement, if in progress
  5630. return;
  5631. }
  5632. // 'Project' the visible viewport to cover the area that is being
  5633. // scrolled into view (if we know enough to estimate it).
  5634. if (dy && wheelPixelsPerUnit != null) {
  5635. var pixels = dy * wheelPixelsPerUnit;
  5636. var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight;
  5637. if (pixels < 0) top = Math.max(0, top + pixels - 50);
  5638. else bot = Math.min(cm.doc.height, bot + pixels + 50);
  5639. updateDisplaySimple(cm, {top: top, bottom: bot});
  5640. }
  5641. if (wheelSamples < 20) {
  5642. if (display.wheelStartX == null) {
  5643. display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop;
  5644. display.wheelDX = dx; display.wheelDY = dy;
  5645. setTimeout(function() {
  5646. if (display.wheelStartX == null) return;
  5647. var movedX = scroll.scrollLeft - display.wheelStartX;
  5648. var movedY = scroll.scrollTop - display.wheelStartY;
  5649. var sample = (movedY && display.wheelDY && movedY / display.wheelDY) ||
  5650. (movedX && display.wheelDX && movedX / display.wheelDX);
  5651. display.wheelStartX = display.wheelStartY = null;
  5652. if (!sample) return;
  5653. wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1);
  5654. ++wheelSamples;
  5655. }, 200);
  5656. } else {
  5657. display.wheelDX += dx; display.wheelDY += dy;
  5658. }
  5659. }
  5660. }
  5661. // KEY EVENTS
  5662. // Run a handler that was bound to a key.
  5663. function doHandleBinding(cm, bound, dropShift) {
  5664. if (typeof bound == "string") {
  5665. bound = commands[bound];
  5666. if (!bound) return false;
  5667. }
  5668. // Ensure previous input has been read, so that the handler sees a
  5669. // consistent view of the document
  5670. cm.display.input.ensurePolled();
  5671. var prevShift = cm.display.shift, done = false;
  5672. try {
  5673. if (cm.isReadOnly()) cm.state.suppressEdits = true;
  5674. if (dropShift) cm.display.shift = false;
  5675. done = bound(cm) != Pass;
  5676. } finally {
  5677. cm.display.shift = prevShift;
  5678. cm.state.suppressEdits = false;
  5679. }
  5680. return done;
  5681. }
  5682. function lookupKeyForEditor(cm, name, handle) {
  5683. for (var i = 0; i < cm.state.keyMaps.length; i++) {
  5684. var result = lookupKey(name, cm.state.keyMaps[i], handle, cm);
  5685. if (result) return result;
  5686. }
  5687. return (cm.options.extraKeys && lookupKey(name, cm.options.extraKeys, handle, cm))
  5688. || lookupKey(name, cm.options.keyMap, handle, cm);
  5689. }
  5690. var stopSeq = new Delayed;
  5691. function dispatchKey(cm, name, e, handle) {
  5692. var seq = cm.state.keySeq;
  5693. if (seq) {
  5694. if (isModifierKey(name)) return "handled";
  5695. stopSeq.set(50, function() {
  5696. if (cm.state.keySeq == seq) {
  5697. cm.state.keySeq = null;
  5698. cm.display.input.reset();
  5699. }
  5700. });
  5701. name = seq + " " + name;
  5702. }
  5703. var result = lookupKeyForEditor(cm, name, handle);
  5704. if (result == "multi")
  5705. cm.state.keySeq = name;
  5706. if (result == "handled")
  5707. signalLater(cm, "keyHandled", cm, name, e);
  5708. if (result == "handled" || result == "multi") {
  5709. e_preventDefault(e);
  5710. restartBlink(cm);
  5711. }
  5712. if (seq && !result && /\'$/.test(name)) {
  5713. e_preventDefault(e);
  5714. return true;
  5715. }
  5716. return !!result;
  5717. }
  5718. // Handle a key from the keydown event.
  5719. function handleKeyBinding(cm, e) {
  5720. var name = keyName(e, true);
  5721. if (!name) return false;
  5722. if (e.shiftKey && !cm.state.keySeq) {
  5723. // First try to resolve full name (including 'Shift-'). Failing
  5724. // that, see if there is a cursor-motion command (starting with
  5725. // 'go') bound to the keyname without 'Shift-'.
  5726. return dispatchKey(cm, "Shift-" + name, e, function(b) {return doHandleBinding(cm, b, true);})
  5727. || dispatchKey(cm, name, e, function(b) {
  5728. if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion)
  5729. return doHandleBinding(cm, b);
  5730. });
  5731. } else {
  5732. return dispatchKey(cm, name, e, function(b) { return doHandleBinding(cm, b); });
  5733. }
  5734. }
  5735. // Handle a key from the keypress event
  5736. function handleCharBinding(cm, e, ch) {
  5737. return dispatchKey(cm, "'" + ch + "'", e,
  5738. function(b) { return doHandleBinding(cm, b, true); });
  5739. }
  5740. var lastStoppedKey = null;
  5741. function onKeyDown(e) {
  5742. var cm = this;
  5743. cm.curOp.focus = activeElt();
  5744. if (signalDOMEvent(cm, e)) return;
  5745. // IE does strange things with escape.
  5746. if (ie && ie_version < 11 && e.keyCode == 27) e.returnValue = false;
  5747. var code = e.keyCode;
  5748. cm.display.shift = code == 16 || e.shiftKey;
  5749. var handled = handleKeyBinding(cm, e);
  5750. if (presto) {
  5751. lastStoppedKey = handled ? code : null;
  5752. // Opera has no cut event... we try to at least catch the key combo
  5753. if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey))
  5754. cm.replaceSelection("", null, "cut");
  5755. }
  5756. // Turn mouse into crosshair when Alt is held on Mac.
  5757. if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className))
  5758. showCrossHair(cm);
  5759. }
  5760. function showCrossHair(cm) {
  5761. var lineDiv = cm.display.lineDiv;
  5762. addClass(lineDiv, "CodeMirror-crosshair");
  5763. function up(e) {
  5764. if (e.keyCode == 18 || !e.altKey) {
  5765. rmClass(lineDiv, "CodeMirror-crosshair");
  5766. off(document, "keyup", up);
  5767. off(document, "mouseover", up);
  5768. }
  5769. }
  5770. on(document, "keyup", up);
  5771. on(document, "mouseover", up);
  5772. }
  5773. function onKeyUp(e) {
  5774. if (e.keyCode == 16) this.doc.sel.shift = false;
  5775. signalDOMEvent(this, e);
  5776. }
  5777. function onKeyPress(e) {
  5778. var cm = this;
  5779. if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) return;
  5780. var keyCode = e.keyCode, charCode = e.charCode;
  5781. if (presto && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return;}
  5782. if ((presto && (!e.which || e.which < 10)) && handleKeyBinding(cm, e)) return;
  5783. var ch = String.fromCharCode(charCode == null ? keyCode : charCode);
  5784. if (handleCharBinding(cm, e, ch)) return;
  5785. cm.display.input.onKeyPress(e);
  5786. }
  5787. // FOCUS/BLUR EVENTS
  5788. function delayBlurEvent(cm) {
  5789. cm.state.delayingBlurEvent = true;
  5790. setTimeout(function() {
  5791. if (cm.state.delayingBlurEvent) {
  5792. cm.state.delayingBlurEvent = false;
  5793. onBlur(cm);
  5794. }
  5795. }, 100);
  5796. }
  5797. function onFocus(cm) {
  5798. if (cm.state.delayingBlurEvent) cm.state.delayingBlurEvent = false;
  5799. if (cm.options.readOnly == "nocursor") return;
  5800. if (!cm.state.focused) {
  5801. signal(cm, "focus", cm);
  5802. cm.state.focused = true;
  5803. addClass(cm.display.wrapper, "CodeMirror-focused");
  5804. // This test prevents this from firing when a context
  5805. // menu is closed (since the input reset would kill the
  5806. // select-all detection hack)
  5807. if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) {
  5808. cm.display.input.reset();
  5809. if (webkit) setTimeout(function() { cm.display.input.reset(true); }, 20); // Issue #1730
  5810. }
  5811. cm.display.input.receivedFocus();
  5812. }
  5813. restartBlink(cm);
  5814. }
  5815. function onBlur(cm) {
  5816. if (cm.state.delayingBlurEvent) return;
  5817. if (cm.state.focused) {
  5818. signal(cm, "blur", cm);
  5819. cm.state.focused = false;
  5820. rmClass(cm.display.wrapper, "CodeMirror-focused");
  5821. }
  5822. clearInterval(cm.display.blinker);
  5823. setTimeout(function() {if (!cm.state.focused) cm.display.shift = false;}, 150);
  5824. }
  5825. // CONTEXT MENU HANDLING
  5826. // To make the context menu work, we need to briefly unhide the
  5827. // textarea (making it as unobtrusive as possible) to let the
  5828. // right-click take effect on it.
  5829. function onContextMenu(cm, e) {
  5830. if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) return;
  5831. if (signalDOMEvent(cm, e, "contextmenu")) return;
  5832. cm.display.input.onContextMenu(e);
  5833. }
  5834. function contextMenuInGutter(cm, e) {
  5835. if (!hasHandler(cm, "gutterContextMenu")) return false;
  5836. return gutterEvent(cm, e, "gutterContextMenu", false);
  5837. }
  5838. // UPDATING
  5839. // Compute the position of the end of a change (its 'to' property
  5840. // refers to the pre-change end).
  5841. var changeEnd = CodeMirror.changeEnd = function(change) {
  5842. if (!change.text) return change.to;
  5843. return Pos(change.from.line + change.text.length - 1,
  5844. lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0));
  5845. };
  5846. // Adjust a position to refer to the post-change position of the
  5847. // same text, or the end of the change if the change covers it.
  5848. function adjustForChange(pos, change) {
  5849. if (cmp(pos, change.from) < 0) return pos;
  5850. if (cmp(pos, change.to) <= 0) return changeEnd(change);
  5851. var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch;
  5852. if (pos.line == change.to.line) ch += changeEnd(change).ch - change.to.ch;
  5853. return Pos(line, ch);
  5854. }
  5855. function computeSelAfterChange(doc, change) {
  5856. var out = [];
  5857. for (var i = 0; i < doc.sel.ranges.length; i++) {
  5858. var range = doc.sel.ranges[i];
  5859. out.push(new Range(adjustForChange(range.anchor, change),
  5860. adjustForChange(range.head, change)));
  5861. }
  5862. return normalizeSelection(out, doc.sel.primIndex);
  5863. }
  5864. function offsetPos(pos, old, nw) {
  5865. if (pos.line == old.line)
  5866. return Pos(nw.line, pos.ch - old.ch + nw.ch);
  5867. else
  5868. return Pos(nw.line + (pos.line - old.line), pos.ch);
  5869. }
  5870. // Used by replaceSelections to allow moving the selection to the
  5871. // start or around the replaced test. Hint may be "start" or "around".
  5872. function computeReplacedSel(doc, changes, hint) {
  5873. var out = [];
  5874. var oldPrev = Pos(doc.first, 0), newPrev = oldPrev;
  5875. for (var i = 0; i < changes.length; i++) {
  5876. var change = changes[i];
  5877. var from = offsetPos(change.from, oldPrev, newPrev);
  5878. var to = offsetPos(changeEnd(change), oldPrev, newPrev);
  5879. oldPrev = change.to;
  5880. newPrev = to;
  5881. if (hint == "around") {
  5882. var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) < 0;
  5883. out[i] = new Range(inv ? to : from, inv ? from : to);
  5884. } else {
  5885. out[i] = new Range(from, from);
  5886. }
  5887. }
  5888. return new Selection(out, doc.sel.primIndex);
  5889. }
  5890. // Allow "beforeChange" event handlers to influence a change
  5891. function filterChange(doc, change, update) {
  5892. var obj = {
  5893. canceled: false,
  5894. from: change.from,
  5895. to: change.to,
  5896. text: change.text,
  5897. origin: change.origin,
  5898. cancel: function() { this.canceled = true; }
  5899. };
  5900. if (update) obj.update = function(from, to, text, origin) {
  5901. if (from) this.from = clipPos(doc, from);
  5902. if (to) this.to = clipPos(doc, to);
  5903. if (text) this.text = text;
  5904. if (origin !== undefined) this.origin = origin;
  5905. };
  5906. signal(doc, "beforeChange", doc, obj);
  5907. if (doc.cm) signal(doc.cm, "beforeChange", doc.cm, obj);
  5908. if (obj.canceled) return null;
  5909. return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin};
  5910. }
  5911. // Apply a change to a document, and add it to the document's
  5912. // history, and propagating it to all linked documents.
  5913. function makeChange(doc, change, ignoreReadOnly) {
  5914. if (doc.cm) {
  5915. if (!doc.cm.curOp) return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly);
  5916. if (doc.cm.state.suppressEdits) return;
  5917. }
  5918. if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) {
  5919. change = filterChange(doc, change, true);
  5920. if (!change) return;
  5921. }
  5922. // Possibly split or suppress the update based on the presence
  5923. // of read-only spans in its range.
  5924. var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to);
  5925. if (split) {
  5926. for (var i = split.length - 1; i >= 0; --i)
  5927. makeChangeInner(doc, {from: split[i].from, to: split[i].to, text: i ? [""] : change.text});
  5928. } else {
  5929. makeChangeInner(doc, change);
  5930. }
  5931. }
  5932. function makeChangeInner(doc, change) {
  5933. if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) return;
  5934. var selAfter = computeSelAfterChange(doc, change);
  5935. addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN);
  5936. makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change));
  5937. var rebased = [];
  5938. linkedDocs(doc, function(doc, sharedHist) {
  5939. if (!sharedHist && indexOf(rebased, doc.history) == -1) {
  5940. rebaseHist(doc.history, change);
  5941. rebased.push(doc.history);
  5942. }
  5943. makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change));
  5944. });
  5945. }
  5946. // Revert a change stored in a document's history.
  5947. function makeChangeFromHistory(doc, type, allowSelectionOnly) {
  5948. if (doc.cm && doc.cm.state.suppressEdits && !allowSelectionOnly) return;
  5949. var hist = doc.history, event, selAfter = doc.sel;
  5950. var source = type == "undo" ? hist.done : hist.undone, dest = type == "undo" ? hist.undone : hist.done;
  5951. // Verify that there is a useable event (so that ctrl-z won't
  5952. // needlessly clear selection events)
  5953. for (var i = 0; i < source.length; i++) {
  5954. event = source[i];
  5955. if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges)
  5956. break;
  5957. }
  5958. if (i == source.length) return;
  5959. hist.lastOrigin = hist.lastSelOrigin = null;
  5960. for (;;) {
  5961. event = source.pop();
  5962. if (event.ranges) {
  5963. pushSelectionToHistory(event, dest);
  5964. if (allowSelectionOnly && !event.equals(doc.sel)) {
  5965. setSelection(doc, event, {clearRedo: false});
  5966. return;
  5967. }
  5968. selAfter = event;
  5969. }
  5970. else break;
  5971. }
  5972. // Build up a reverse change object to add to the opposite history
  5973. // stack (redo when undoing, and vice versa).
  5974. var antiChanges = [];
  5975. pushSelectionToHistory(selAfter, dest);
  5976. dest.push({changes: antiChanges, generation: hist.generation});
  5977. hist.generation = event.generation || ++hist.maxGeneration;
  5978. var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange");
  5979. for (var i = event.changes.length - 1; i >= 0; --i) {
  5980. var change = event.changes[i];
  5981. change.origin = type;
  5982. if (filter && !filterChange(doc, change, false)) {
  5983. source.length = 0;
  5984. return;
  5985. }
  5986. antiChanges.push(historyChangeFromChange(doc, change));
  5987. var after = i ? computeSelAfterChange(doc, change) : lst(source);
  5988. makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change));
  5989. if (!i && doc.cm) doc.cm.scrollIntoView({from: change.from, to: changeEnd(change)});
  5990. var rebased = [];
  5991. // Propagate to the linked documents
  5992. linkedDocs(doc, function(doc, sharedHist) {
  5993. if (!sharedHist && indexOf(rebased, doc.history) == -1) {
  5994. rebaseHist(doc.history, change);
  5995. rebased.push(doc.history);
  5996. }
  5997. makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change));
  5998. });
  5999. }
  6000. }
  6001. // Sub-views need their line numbers shifted when text is added
  6002. // above or below them in the parent document.
  6003. function shiftDoc(doc, distance) {
  6004. if (distance == 0) return;
  6005. doc.first += distance;
  6006. doc.sel = new Selection(map(doc.sel.ranges, function(range) {
  6007. return new Range(Pos(range.anchor.line + distance, range.anchor.ch),
  6008. Pos(range.head.line + distance, range.head.ch));
  6009. }), doc.sel.primIndex);
  6010. if (doc.cm) {
  6011. regChange(doc.cm, doc.first, doc.first - distance, distance);
  6012. for (var d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++)
  6013. regLineChange(doc.cm, l, "gutter");
  6014. }
  6015. }
  6016. // More lower-level change function, handling only a single document
  6017. // (not linked ones).
  6018. function makeChangeSingleDoc(doc, change, selAfter, spans) {
  6019. if (doc.cm && !doc.cm.curOp)
  6020. return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans);
  6021. if (change.to.line < doc.first) {
  6022. shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line));
  6023. return;
  6024. }
  6025. if (change.from.line > doc.lastLine()) return;
  6026. // Clip the change to the size of this doc
  6027. if (change.from.line < doc.first) {
  6028. var shift = change.text.length - 1 - (doc.first - change.from.line);
  6029. shiftDoc(doc, shift);
  6030. change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch),
  6031. text: [lst(change.text)], origin: change.origin};
  6032. }
  6033. var last = doc.lastLine();
  6034. if (change.to.line > last) {
  6035. change = {from: change.from, to: Pos(last, getLine(doc, last).text.length),
  6036. text: [change.text[0]], origin: change.origin};
  6037. }
  6038. change.removed = getBetween(doc, change.from, change.to);
  6039. if (!selAfter) selAfter = computeSelAfterChange(doc, change);
  6040. if (doc.cm) makeChangeSingleDocInEditor(doc.cm, change, spans);
  6041. else updateDoc(doc, change, spans);
  6042. setSelectionNoUndo(doc, selAfter, sel_dontScroll);
  6043. }
  6044. // Handle the interaction of a change to a document with the editor
  6045. // that this document is part of.
  6046. function makeChangeSingleDocInEditor(cm, change, spans) {
  6047. var doc = cm.doc, display = cm.display, from = change.from, to = change.to;
  6048. var recomputeMaxLength = false, checkWidthStart = from.line;
  6049. if (!cm.options.lineWrapping) {
  6050. checkWidthStart = lineNo(visualLine(getLine(doc, from.line)));
  6051. doc.iter(checkWidthStart, to.line + 1, function(line) {
  6052. if (line == display.maxLine) {
  6053. recomputeMaxLength = true;
  6054. return true;
  6055. }
  6056. });
  6057. }
  6058. if (doc.sel.contains(change.from, change.to) > -1)
  6059. signalCursorActivity(cm);
  6060. updateDoc(doc, change, spans, estimateHeight(cm));
  6061. if (!cm.options.lineWrapping) {
  6062. doc.iter(checkWidthStart, from.line + change.text.length, function(line) {
  6063. var len = lineLength(line);
  6064. if (len > display.maxLineLength) {
  6065. display.maxLine = line;
  6066. display.maxLineLength = len;
  6067. display.maxLineChanged = true;
  6068. recomputeMaxLength = false;
  6069. }
  6070. });
  6071. if (recomputeMaxLength) cm.curOp.updateMaxLine = true;
  6072. }
  6073. // Adjust frontier, schedule worker
  6074. doc.frontier = Math.min(doc.frontier, from.line);
  6075. startWorker(cm, 400);
  6076. var lendiff = change.text.length - (to.line - from.line) - 1;
  6077. // Remember that these lines changed, for updating the display
  6078. if (change.full)
  6079. regChange(cm);
  6080. else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change))
  6081. regLineChange(cm, from.line, "text");
  6082. else
  6083. regChange(cm, from.line, to.line + 1, lendiff);
  6084. var changesHandler = hasHandler(cm, "changes"), changeHandler = hasHandler(cm, "change");
  6085. if (changeHandler || changesHandler) {
  6086. var obj = {
  6087. from: from, to: to,
  6088. text: change.text,
  6089. removed: change.removed,
  6090. origin: change.origin
  6091. };
  6092. if (changeHandler) signalLater(cm, "change", cm, obj);
  6093. if (changesHandler) (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj);
  6094. }
  6095. cm.display.selForContextMenu = null;
  6096. }
  6097. function replaceRange(doc, code, from, to, origin) {
  6098. if (!to) to = from;
  6099. if (cmp(to, from) < 0) { var tmp = to; to = from; from = tmp; }
  6100. if (typeof code == "string") code = doc.splitLines(code);
  6101. makeChange(doc, {from: from, to: to, text: code, origin: origin});
  6102. }
  6103. // SCROLLING THINGS INTO VIEW
  6104. // If an editor sits on the top or bottom of the window, partially
  6105. // scrolled out of view, this ensures that the cursor is visible.
  6106. function maybeScrollWindow(cm, coords) {
  6107. if (signalDOMEvent(cm, "scrollCursorIntoView")) return;
  6108. var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null;
  6109. if (coords.top + box.top < 0) doScroll = true;
  6110. else if (coords.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) doScroll = false;
  6111. if (doScroll != null && !phantom) {
  6112. var scrollNode = elt("div", "\u200b", null, "position: absolute; top: " +
  6113. (coords.top - display.viewOffset - paddingTop(cm.display)) + "px; height: " +
  6114. (coords.bottom - coords.top + scrollGap(cm) + display.barHeight) + "px; left: " +
  6115. coords.left + "px; width: 2px;");
  6116. cm.display.lineSpace.appendChild(scrollNode);
  6117. scrollNode.scrollIntoView(doScroll);
  6118. cm.display.lineSpace.removeChild(scrollNode);
  6119. }
  6120. }
  6121. // Scroll a given position into view (immediately), verifying that
  6122. // it actually became visible (as line heights are accurately
  6123. // measured, the position of something may 'drift' during drawing).
  6124. function scrollPosIntoView(cm, pos, end, margin) {
  6125. if (margin == null) margin = 0;
  6126. for (var limit = 0; limit < 5; limit++) {
  6127. var changed = false, coords = cursorCoords(cm, pos);
  6128. var endCoords = !end || end == pos ? coords : cursorCoords(cm, end);
  6129. var scrollPos = calculateScrollPos(cm, Math.min(coords.left, endCoords.left),
  6130. Math.min(coords.top, endCoords.top) - margin,
  6131. Math.max(coords.left, endCoords.left),
  6132. Math.max(coords.bottom, endCoords.bottom) + margin);
  6133. var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft;
  6134. if (scrollPos.scrollTop != null) {
  6135. setScrollTop(cm, scrollPos.scrollTop);
  6136. if (Math.abs(cm.doc.scrollTop - startTop) > 1) changed = true;
  6137. }
  6138. if (scrollPos.scrollLeft != null) {
  6139. setScrollLeft(cm, scrollPos.scrollLeft);
  6140. if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) changed = true;
  6141. }
  6142. if (!changed) break;
  6143. }
  6144. return coords;
  6145. }
  6146. // Scroll a given set of coordinates into view (immediately).
  6147. function scrollIntoView(cm, x1, y1, x2, y2) {
  6148. var scrollPos = calculateScrollPos(cm, x1, y1, x2, y2);
  6149. if (scrollPos.scrollTop != null) setScrollTop(cm, scrollPos.scrollTop);
  6150. if (scrollPos.scrollLeft != null) setScrollLeft(cm, scrollPos.scrollLeft);
  6151. }
  6152. // Calculate a new scroll position needed to scroll the given
  6153. // rectangle into view. Returns an object with scrollTop and
  6154. // scrollLeft properties. When these are undefined, the
  6155. // vertical/horizontal position does not need to be adjusted.
  6156. function calculateScrollPos(cm, x1, y1, x2, y2) {
  6157. var display = cm.display, snapMargin = textHeight(cm.display);
  6158. if (y1 < 0) y1 = 0;
  6159. var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop;
  6160. var screen = displayHeight(cm), result = {};
  6161. if (y2 - y1 > screen) y2 = y1 + screen;
  6162. var docBottom = cm.doc.height + paddingVert(display);
  6163. var atTop = y1 < snapMargin, atBottom = y2 > docBottom - snapMargin;
  6164. if (y1 < screentop) {
  6165. result.scrollTop = atTop ? 0 : y1;
  6166. } else if (y2 > screentop + screen) {
  6167. var newTop = Math.min(y1, (atBottom ? docBottom : y2) - screen);
  6168. if (newTop != screentop) result.scrollTop = newTop;
  6169. }
  6170. var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft;
  6171. var screenw = displayWidth(cm) - (cm.options.fixedGutter ? display.gutters.offsetWidth : 0);
  6172. var tooWide = x2 - x1 > screenw;
  6173. if (tooWide) x2 = x1 + screenw;
  6174. if (x1 < 10)
  6175. result.scrollLeft = 0;
  6176. else if (x1 < screenleft)
  6177. result.scrollLeft = Math.max(0, x1 - (tooWide ? 0 : 10));
  6178. else if (x2 > screenw + screenleft - 3)
  6179. result.scrollLeft = x2 + (tooWide ? 0 : 10) - screenw;
  6180. return result;
  6181. }
  6182. // Store a relative adjustment to the scroll position in the current
  6183. // operation (to be applied when the operation finishes).
  6184. function addToScrollPos(cm, left, top) {
  6185. if (left != null || top != null) resolveScrollToPos(cm);
  6186. if (left != null)
  6187. cm.curOp.scrollLeft = (cm.curOp.scrollLeft == null ? cm.doc.scrollLeft : cm.curOp.scrollLeft) + left;
  6188. if (top != null)
  6189. cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top;
  6190. }
  6191. // Make sure that at the end of the operation the current cursor is
  6192. // shown.
  6193. function ensureCursorVisible(cm) {
  6194. resolveScrollToPos(cm);
  6195. var cur = cm.getCursor(), from = cur, to = cur;
  6196. if (!cm.options.lineWrapping) {
  6197. from = cur.ch ? Pos(cur.line, cur.ch - 1) : cur;
  6198. to = Pos(cur.line, cur.ch + 1);
  6199. }
  6200. cm.curOp.scrollToPos = {from: from, to: to, margin: cm.options.cursorScrollMargin, isCursor: true};
  6201. }
  6202. // When an operation has its scrollToPos property set, and another
  6203. // scroll action is applied before the end of the operation, this
  6204. // 'simulates' scrolling that position into view in a cheap way, so
  6205. // that the effect of intermediate scroll commands is not ignored.
  6206. function resolveScrollToPos(cm) {
  6207. var range = cm.curOp.scrollToPos;
  6208. if (range) {
  6209. cm.curOp.scrollToPos = null;
  6210. var from = estimateCoords(cm, range.from), to = estimateCoords(cm, range.to);
  6211. var sPos = calculateScrollPos(cm, Math.min(from.left, to.left),
  6212. Math.min(from.top, to.top) - range.margin,
  6213. Math.max(from.right, to.right),
  6214. Math.max(from.bottom, to.bottom) + range.margin);
  6215. cm.scrollTo(sPos.scrollLeft, sPos.scrollTop);
  6216. }
  6217. }
  6218. // API UTILITIES
  6219. // Indent the given line. The how parameter can be "smart",
  6220. // "add"/null, "subtract", or "prev". When aggressive is false
  6221. // (typically set to true for forced single-line indents), empty
  6222. // lines are not indented, and places where the mode returns Pass
  6223. // are left alone.
  6224. function indentLine(cm, n, how, aggressive) {
  6225. var doc = cm.doc, state;
  6226. if (how == null) how = "add";
  6227. if (how == "smart") {
  6228. // Fall back to "prev" when the mode doesn't have an indentation
  6229. // method.
  6230. if (!doc.mode.indent) how = "prev";
  6231. else state = getStateBefore(cm, n);
  6232. }
  6233. var tabSize = cm.options.tabSize;
  6234. var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize);
  6235. if (line.stateAfter) line.stateAfter = null;
  6236. var curSpaceString = line.text.match(/^\s*/)[0], indentation;
  6237. if (!aggressive && !/\S/.test(line.text)) {
  6238. indentation = 0;
  6239. how = "not";
  6240. } else if (how == "smart") {
  6241. indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text);
  6242. if (indentation == Pass || indentation > 150) {
  6243. if (!aggressive) return;
  6244. how = "prev";
  6245. }
  6246. }
  6247. if (how == "prev") {
  6248. if (n > doc.first) indentation = countColumn(getLine(doc, n-1).text, null, tabSize);
  6249. else indentation = 0;
  6250. } else if (how == "add") {
  6251. indentation = curSpace + cm.options.indentUnit;
  6252. } else if (how == "subtract") {
  6253. indentation = curSpace - cm.options.indentUnit;
  6254. } else if (typeof how == "number") {
  6255. indentation = curSpace + how;
  6256. }
  6257. indentation = Math.max(0, indentation);
  6258. var indentString = "", pos = 0;
  6259. if (cm.options.indentWithTabs)
  6260. for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";}
  6261. if (pos < indentation) indentString += spaceStr(indentation - pos);
  6262. if (indentString != curSpaceString) {
  6263. replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input");
  6264. line.stateAfter = null;
  6265. return true;
  6266. } else {
  6267. // Ensure that, if the cursor was in the whitespace at the start
  6268. // of the line, it is moved to the end of that space.
  6269. for (var i = 0; i < doc.sel.ranges.length; i++) {
  6270. var range = doc.sel.ranges[i];
  6271. if (range.head.line == n && range.head.ch < curSpaceString.length) {
  6272. var pos = Pos(n, curSpaceString.length);
  6273. replaceOneSelection(doc, i, new Range(pos, pos));
  6274. break;
  6275. }
  6276. }
  6277. }
  6278. }
  6279. // Utility for applying a change to a line by handle or number,
  6280. // returning the number and optionally registering the line as
  6281. // changed.
  6282. function changeLine(doc, handle, changeType, op) {
  6283. var no = handle, line = handle;
  6284. if (typeof handle == "number") line = getLine(doc, clipLine(doc, handle));
  6285. else no = lineNo(handle);
  6286. if (no == null) return null;
  6287. if (op(line, no) && doc.cm) regLineChange(doc.cm, no, changeType);
  6288. return line;
  6289. }
  6290. // Helper for deleting text near the selection(s), used to implement
  6291. // backspace, delete, and similar functionality.
  6292. function deleteNearSelection(cm, compute) {
  6293. var ranges = cm.doc.sel.ranges, kill = [];
  6294. // Build up a set of ranges to kill first, merging overlapping
  6295. // ranges.
  6296. for (var i = 0; i < ranges.length; i++) {
  6297. var toKill = compute(ranges[i]);
  6298. while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) {
  6299. var replaced = kill.pop();
  6300. if (cmp(replaced.from, toKill.from) < 0) {
  6301. toKill.from = replaced.from;
  6302. break;
  6303. }
  6304. }
  6305. kill.push(toKill);
  6306. }
  6307. // Next, remove those actual ranges.
  6308. runInOp(cm, function() {
  6309. for (var i = kill.length - 1; i >= 0; i--)
  6310. replaceRange(cm.doc, "", kill[i].from, kill[i].to, "+delete");
  6311. ensureCursorVisible(cm);
  6312. });
  6313. }
  6314. // Used for horizontal relative motion. Dir is -1 or 1 (left or
  6315. // right), unit can be "char", "column" (like char, but doesn't
  6316. // cross line boundaries), "word" (across next word), or "group" (to
  6317. // the start of next group of word or non-word-non-whitespace
  6318. // chars). The visually param controls whether, in right-to-left
  6319. // text, direction 1 means to move towards the next index in the
  6320. // string, or towards the character to the right of the current
  6321. // position. The resulting position will have a hitSide=true
  6322. // property if it reached the end of the document.
  6323. function findPosH(doc, pos, dir, unit, visually) {
  6324. var line = pos.line, ch = pos.ch, origDir = dir;
  6325. var lineObj = getLine(doc, line);
  6326. function findNextLine() {
  6327. var l = line + dir;
  6328. if (l < doc.first || l >= doc.first + doc.size) return false
  6329. line = l;
  6330. return lineObj = getLine(doc, l);
  6331. }
  6332. function moveOnce(boundToLine) {
  6333. var next = (visually ? moveVisually : moveLogically)(lineObj, ch, dir, true);
  6334. if (next == null) {
  6335. if (!boundToLine && findNextLine()) {
  6336. if (visually) ch = (dir < 0 ? lineRight : lineLeft)(lineObj);
  6337. else ch = dir < 0 ? lineObj.text.length : 0;
  6338. } else return false
  6339. } else ch = next;
  6340. return true;
  6341. }
  6342. if (unit == "char") {
  6343. moveOnce()
  6344. } else if (unit == "column") {
  6345. moveOnce(true)
  6346. } else if (unit == "word" || unit == "group") {
  6347. var sawType = null, group = unit == "group";
  6348. var helper = doc.cm && doc.cm.getHelper(pos, "wordChars");
  6349. for (var first = true;; first = false) {
  6350. if (dir < 0 && !moveOnce(!first)) break;
  6351. var cur = lineObj.text.charAt(ch) || "\n";
  6352. var type = isWordChar(cur, helper) ? "w"
  6353. : group && cur == "\n" ? "n"
  6354. : !group || /\s/.test(cur) ? null
  6355. : "p";
  6356. if (group && !first && !type) type = "s";
  6357. if (sawType && sawType != type) {
  6358. if (dir < 0) {dir = 1; moveOnce();}
  6359. break;
  6360. }
  6361. if (type) sawType = type;
  6362. if (dir > 0 && !moveOnce(!first)) break;
  6363. }
  6364. }
  6365. var result = skipAtomic(doc, Pos(line, ch), pos, origDir, true);
  6366. if (!cmp(pos, result)) result.hitSide = true;
  6367. return result;
  6368. }
  6369. // For relative vertical movement. Dir may be -1 or 1. Unit can be
  6370. // "page" or "line". The resulting position will have a hitSide=true
  6371. // property if it reached the end of the document.
  6372. function findPosV(cm, pos, dir, unit) {
  6373. var doc = cm.doc, x = pos.left, y;
  6374. if (unit == "page") {
  6375. var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight);
  6376. y = pos.top + dir * (pageSize - (dir < 0 ? 1.5 : .5) * textHeight(cm.display));
  6377. } else if (unit == "line") {
  6378. y = dir > 0 ? pos.bottom + 3 : pos.top - 3;
  6379. }
  6380. for (;;) {
  6381. var target = coordsChar(cm, x, y);
  6382. if (!target.outside) break;
  6383. if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break; }
  6384. y += dir * 5;
  6385. }
  6386. return target;
  6387. }
  6388. // EDITOR METHODS
  6389. // The publicly visible API. Note that methodOp(f) means
  6390. // 'wrap f in an operation, performed on its `this` parameter'.
  6391. // This is not the complete set of editor methods. Most of the
  6392. // methods defined on the Doc type are also injected into
  6393. // CodeMirror.prototype, for backwards compatibility and
  6394. // convenience.
  6395. CodeMirror.prototype = {
  6396. constructor: CodeMirror,
  6397. focus: function(){window.focus(); this.display.input.focus();},
  6398. setOption: function(option, value) {
  6399. var options = this.options, old = options[option];
  6400. if (options[option] == value && option != "mode") return;
  6401. options[option] = value;
  6402. if (optionHandlers.hasOwnProperty(option))
  6403. operation(this, optionHandlers[option])(this, value, old);
  6404. },
  6405. getOption: function(option) {return this.options[option];},
  6406. getDoc: function() {return this.doc;},
  6407. addKeyMap: function(map, bottom) {
  6408. this.state.keyMaps[bottom ? "push" : "unshift"](getKeyMap(map));
  6409. },
  6410. removeKeyMap: function(map) {
  6411. var maps = this.state.keyMaps;
  6412. for (var i = 0; i < maps.length; ++i)
  6413. if (maps[i] == map || maps[i].name == map) {
  6414. maps.splice(i, 1);
  6415. return true;
  6416. }
  6417. },
  6418. addOverlay: methodOp(function(spec, options) {
  6419. var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec);
  6420. if (mode.startState) throw new Error("Overlays may not be stateful.");
  6421. this.state.overlays.push({mode: mode, modeSpec: spec, opaque: options && options.opaque});
  6422. this.state.modeGen++;
  6423. regChange(this);
  6424. }),
  6425. removeOverlay: methodOp(function(spec) {
  6426. var overlays = this.state.overlays;
  6427. for (var i = 0; i < overlays.length; ++i) {
  6428. var cur = overlays[i].modeSpec;
  6429. if (cur == spec || typeof spec == "string" && cur.name == spec) {
  6430. overlays.splice(i, 1);
  6431. this.state.modeGen++;
  6432. regChange(this);
  6433. return;
  6434. }
  6435. }
  6436. }),
  6437. indentLine: methodOp(function(n, dir, aggressive) {
  6438. if (typeof dir != "string" && typeof dir != "number") {
  6439. if (dir == null) dir = this.options.smartIndent ? "smart" : "prev";
  6440. else dir = dir ? "add" : "subtract";
  6441. }
  6442. if (isLine(this.doc, n)) indentLine(this, n, dir, aggressive);
  6443. }),
  6444. indentSelection: methodOp(function(how) {
  6445. var ranges = this.doc.sel.ranges, end = -1;
  6446. for (var i = 0; i < ranges.length; i++) {
  6447. var range = ranges[i];
  6448. if (!range.empty()) {
  6449. var from = range.from(), to = range.to();
  6450. var start = Math.max(end, from.line);
  6451. end = Math.min(this.lastLine(), to.line - (to.ch ? 0 : 1)) + 1;
  6452. for (var j = start; j < end; ++j)
  6453. indentLine(this, j, how);
  6454. var newRanges = this.doc.sel.ranges;
  6455. if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i].from().ch > 0)
  6456. replaceOneSelection(this.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll);
  6457. } else if (range.head.line > end) {
  6458. indentLine(this, range.head.line, how, true);
  6459. end = range.head.line;
  6460. if (i == this.doc.sel.primIndex) ensureCursorVisible(this);
  6461. }
  6462. }
  6463. }),
  6464. // Fetch the parser token for a given character. Useful for hacks
  6465. // that want to inspect the mode state (say, for completion).
  6466. getTokenAt: function(pos, precise) {
  6467. return takeToken(this, pos, precise);
  6468. },
  6469. getLineTokens: function(line, precise) {
  6470. return takeToken(this, Pos(line), precise, true);
  6471. },
  6472. getTokenTypeAt: function(pos) {
  6473. pos = clipPos(this.doc, pos);
  6474. var styles = getLineStyles(this, getLine(this.doc, pos.line));
  6475. var before = 0, after = (styles.length - 1) / 2, ch = pos.ch;
  6476. var type;
  6477. if (ch == 0) type = styles[2];
  6478. else for (;;) {
  6479. var mid = (before + after) >> 1;
  6480. if ((mid ? styles[mid * 2 - 1] : 0) >= ch) after = mid;
  6481. else if (styles[mid * 2 + 1] < ch) before = mid + 1;
  6482. else { type = styles[mid * 2 + 2]; break; }
  6483. }
  6484. var cut = type ? type.indexOf("cm-overlay ") : -1;
  6485. return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1);
  6486. },
  6487. getModeAt: function(pos) {
  6488. var mode = this.doc.mode;
  6489. if (!mode.innerMode) return mode;
  6490. return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode;
  6491. },
  6492. getHelper: function(pos, type) {
  6493. return this.getHelpers(pos, type)[0];
  6494. },
  6495. getHelpers: function(pos, type) {
  6496. var found = [];
  6497. if (!helpers.hasOwnProperty(type)) return found;
  6498. var help = helpers[type], mode = this.getModeAt(pos);
  6499. if (typeof mode[type] == "string") {
  6500. if (help[mode[type]]) found.push(help[mode[type]]);
  6501. } else if (mode[type]) {
  6502. for (var i = 0; i < mode[type].length; i++) {
  6503. var val = help[mode[type][i]];
  6504. if (val) found.push(val);
  6505. }
  6506. } else if (mode.helperType && help[mode.helperType]) {
  6507. found.push(help[mode.helperType]);
  6508. } else if (help[mode.name]) {
  6509. found.push(help[mode.name]);
  6510. }
  6511. for (var i = 0; i < help._global.length; i++) {
  6512. var cur = help._global[i];
  6513. if (cur.pred(mode, this) && indexOf(found, cur.val) == -1)
  6514. found.push(cur.val);
  6515. }
  6516. return found;
  6517. },
  6518. getStateAfter: function(line, precise) {
  6519. var doc = this.doc;
  6520. line = clipLine(doc, line == null ? doc.first + doc.size - 1: line);
  6521. return getStateBefore(this, line + 1, precise);
  6522. },
  6523. cursorCoords: function(start, mode) {
  6524. var pos, range = this.doc.sel.primary();
  6525. if (start == null) pos = range.head;
  6526. else if (typeof start == "object") pos = clipPos(this.doc, start);
  6527. else pos = start ? range.from() : range.to();
  6528. return cursorCoords(this, pos, mode || "page");
  6529. },
  6530. charCoords: function(pos, mode) {
  6531. return charCoords(this, clipPos(this.doc, pos), mode || "page");
  6532. },
  6533. coordsChar: function(coords, mode) {
  6534. coords = fromCoordSystem(this, coords, mode || "page");
  6535. return coordsChar(this, coords.left, coords.top);
  6536. },
  6537. lineAtHeight: function(height, mode) {
  6538. height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top;
  6539. return lineAtHeight(this.doc, height + this.display.viewOffset);
  6540. },
  6541. heightAtLine: function(line, mode) {
  6542. var end = false, lineObj;
  6543. if (typeof line == "number") {
  6544. var last = this.doc.first + this.doc.size - 1;
  6545. if (line < this.doc.first) line = this.doc.first;
  6546. else if (line > last) { line = last; end = true; }
  6547. lineObj = getLine(this.doc, line);
  6548. } else {
  6549. lineObj = line;
  6550. }
  6551. return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || "page").top +
  6552. (end ? this.doc.height - heightAtLine(lineObj) : 0);
  6553. },
  6554. defaultTextHeight: function() { return textHeight(this.display); },
  6555. defaultCharWidth: function() { return charWidth(this.display); },
  6556. setGutterMarker: methodOp(function(line, gutterID, value) {
  6557. return changeLine(this.doc, line, "gutter", function(line) {
  6558. var markers = line.gutterMarkers || (line.gutterMarkers = {});
  6559. markers[gutterID] = value;
  6560. if (!value && isEmpty(markers)) line.gutterMarkers = null;
  6561. return true;
  6562. });
  6563. }),
  6564. clearGutter: methodOp(function(gutterID) {
  6565. var cm = this, doc = cm.doc, i = doc.first;
  6566. doc.iter(function(line) {
  6567. if (line.gutterMarkers && line.gutterMarkers[gutterID]) {
  6568. line.gutterMarkers[gutterID] = null;
  6569. regLineChange(cm, i, "gutter");
  6570. if (isEmpty(line.gutterMarkers)) line.gutterMarkers = null;
  6571. }
  6572. ++i;
  6573. });
  6574. }),
  6575. lineInfo: function(line) {
  6576. if (typeof line == "number") {
  6577. if (!isLine(this.doc, line)) return null;
  6578. var n = line;
  6579. line = getLine(this.doc, line);
  6580. if (!line) return null;
  6581. } else {
  6582. var n = lineNo(line);
  6583. if (n == null) return null;
  6584. }
  6585. return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers,
  6586. textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass,
  6587. widgets: line.widgets};
  6588. },
  6589. getViewport: function() { return {from: this.display.viewFrom, to: this.display.viewTo};},
  6590. addWidget: function(pos, node, scroll, vert, horiz) {
  6591. var display = this.display;
  6592. pos = cursorCoords(this, clipPos(this.doc, pos));
  6593. var top = pos.bottom, left = pos.left;
  6594. node.style.position = "absolute";
  6595. node.setAttribute("cm-ignore-events", "true");
  6596. this.display.input.setUneditable(node);
  6597. display.sizer.appendChild(node);
  6598. if (vert == "over") {
  6599. top = pos.top;
  6600. } else if (vert == "above" || vert == "near") {
  6601. var vspace = Math.max(display.wrapper.clientHeight, this.doc.height),
  6602. hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth);
  6603. // Default to positioning above (if specified and possible); otherwise default to positioning below
  6604. if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight)
  6605. top = pos.top - node.offsetHeight;
  6606. else if (pos.bottom + node.offsetHeight <= vspace)
  6607. top = pos.bottom;
  6608. if (left + node.offsetWidth > hspace)
  6609. left = hspace - node.offsetWidth;
  6610. }
  6611. node.style.top = top + "px";
  6612. node.style.left = node.style.right = "";
  6613. if (horiz == "right") {
  6614. left = display.sizer.clientWidth - node.offsetWidth;
  6615. node.style.right = "0px";
  6616. } else {
  6617. if (horiz == "left") left = 0;
  6618. else if (horiz == "middle") left = (display.sizer.clientWidth - node.offsetWidth) / 2;
  6619. node.style.left = left + "px";
  6620. }
  6621. if (scroll)
  6622. scrollIntoView(this, left, top, left + node.offsetWidth, top + node.offsetHeight);
  6623. },
  6624. triggerOnKeyDown: methodOp(onKeyDown),
  6625. triggerOnKeyPress: methodOp(onKeyPress),
  6626. triggerOnKeyUp: onKeyUp,
  6627. execCommand: function(cmd) {
  6628. if (commands.hasOwnProperty(cmd))
  6629. return commands[cmd].call(null, this);
  6630. },
  6631. triggerElectric: methodOp(function(text) { triggerElectric(this, text); }),
  6632. findPosH: function(from, amount, unit, visually) {
  6633. var dir = 1;
  6634. if (amount < 0) { dir = -1; amount = -amount; }
  6635. for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) {
  6636. cur = findPosH(this.doc, cur, dir, unit, visually);
  6637. if (cur.hitSide) break;
  6638. }
  6639. return cur;
  6640. },
  6641. moveH: methodOp(function(dir, unit) {
  6642. var cm = this;
  6643. cm.extendSelectionsBy(function(range) {
  6644. if (cm.display.shift || cm.doc.extend || range.empty())
  6645. return findPosH(cm.doc, range.head, dir, unit, cm.options.rtlMoveVisually);
  6646. else
  6647. return dir < 0 ? range.from() : range.to();
  6648. }, sel_move);
  6649. }),
  6650. deleteH: methodOp(function(dir, unit) {
  6651. var sel = this.doc.sel, doc = this.doc;
  6652. if (sel.somethingSelected())
  6653. doc.replaceSelection("", null, "+delete");
  6654. else
  6655. deleteNearSelection(this, function(range) {
  6656. var other = findPosH(doc, range.head, dir, unit, false);
  6657. return dir < 0 ? {from: other, to: range.head} : {from: range.head, to: other};
  6658. });
  6659. }),
  6660. findPosV: function(from, amount, unit, goalColumn) {
  6661. var dir = 1, x = goalColumn;
  6662. if (amount < 0) { dir = -1; amount = -amount; }
  6663. for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) {
  6664. var coords = cursorCoords(this, cur, "div");
  6665. if (x == null) x = coords.left;
  6666. else coords.left = x;
  6667. cur = findPosV(this, coords, dir, unit);
  6668. if (cur.hitSide) break;
  6669. }
  6670. return cur;
  6671. },
  6672. moveV: methodOp(function(dir, unit) {
  6673. var cm = this, doc = this.doc, goals = [];
  6674. var collapse = !cm.display.shift && !doc.extend && doc.sel.somethingSelected();
  6675. doc.extendSelectionsBy(function(range) {
  6676. if (collapse)
  6677. return dir < 0 ? range.from() : range.to();
  6678. var headPos = cursorCoords(cm, range.head, "div");
  6679. if (range.goalColumn != null) headPos.left = range.goalColumn;
  6680. goals.push(headPos.left);
  6681. var pos = findPosV(cm, headPos, dir, unit);
  6682. if (unit == "page" && range == doc.sel.primary())
  6683. addToScrollPos(cm, null, charCoords(cm, pos, "div").top - headPos.top);
  6684. return pos;
  6685. }, sel_move);
  6686. if (goals.length) for (var i = 0; i < doc.sel.ranges.length; i++)
  6687. doc.sel.ranges[i].goalColumn = goals[i];
  6688. }),
  6689. // Find the word at the given position (as returned by coordsChar).
  6690. findWordAt: function(pos) {
  6691. var doc = this.doc, line = getLine(doc, pos.line).text;
  6692. var start = pos.ch, end = pos.ch;
  6693. if (line) {
  6694. var helper = this.getHelper(pos, "wordChars");
  6695. if ((pos.xRel < 0 || end == line.length) && start) --start; else ++end;
  6696. var startChar = line.charAt(start);
  6697. var check = isWordChar(startChar, helper)
  6698. ? function(ch) { return isWordChar(ch, helper); }
  6699. : /\s/.test(startChar) ? function(ch) {return /\s/.test(ch);}
  6700. : function(ch) {return !/\s/.test(ch) && !isWordChar(ch);};
  6701. while (start > 0 && check(line.charAt(start - 1))) --start;
  6702. while (end < line.length && check(line.charAt(end))) ++end;
  6703. }
  6704. return new Range(Pos(pos.line, start), Pos(pos.line, end));
  6705. },
  6706. toggleOverwrite: function(value) {
  6707. if (value != null && value == this.state.overwrite) return;
  6708. if (this.state.overwrite = !this.state.overwrite)
  6709. addClass(this.display.cursorDiv, "CodeMirror-overwrite");
  6710. else
  6711. rmClass(this.display.cursorDiv, "CodeMirror-overwrite");
  6712. signal(this, "overwriteToggle", this, this.state.overwrite);
  6713. },
  6714. hasFocus: function() { return this.display.input.getField() == activeElt(); },
  6715. isReadOnly: function() { return !!(this.options.readOnly || this.doc.cantEdit); },
  6716. scrollTo: methodOp(function(x, y) {
  6717. if (x != null || y != null) resolveScrollToPos(this);
  6718. if (x != null) this.curOp.scrollLeft = x;
  6719. if (y != null) this.curOp.scrollTop = y;
  6720. }),
  6721. getScrollInfo: function() {
  6722. var scroller = this.display.scroller;
  6723. return {left: scroller.scrollLeft, top: scroller.scrollTop,
  6724. height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight,
  6725. width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth,
  6726. clientHeight: displayHeight(this), clientWidth: displayWidth(this)};
  6727. },
  6728. scrollIntoView: methodOp(function(range, margin) {
  6729. if (range == null) {
  6730. range = {from: this.doc.sel.primary().head, to: null};
  6731. if (margin == null) margin = this.options.cursorScrollMargin;
  6732. } else if (typeof range == "number") {
  6733. range = {from: Pos(range, 0), to: null};
  6734. } else if (range.from == null) {
  6735. range = {from: range, to: null};
  6736. }
  6737. if (!range.to) range.to = range.from;
  6738. range.margin = margin || 0;
  6739. if (range.from.line != null) {
  6740. resolveScrollToPos(this);
  6741. this.curOp.scrollToPos = range;
  6742. } else {
  6743. var sPos = calculateScrollPos(this, Math.min(range.from.left, range.to.left),
  6744. Math.min(range.from.top, range.to.top) - range.margin,
  6745. Math.max(range.from.right, range.to.right),
  6746. Math.max(range.from.bottom, range.to.bottom) + range.margin);
  6747. this.scrollTo(sPos.scrollLeft, sPos.scrollTop);
  6748. }
  6749. }),
  6750. setSize: methodOp(function(width, height) {
  6751. var cm = this;
  6752. function interpret(val) {
  6753. return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val;
  6754. }
  6755. if (width != null) cm.display.wrapper.style.width = interpret(width);
  6756. if (height != null) cm.display.wrapper.style.height = interpret(height);
  6757. if (cm.options.lineWrapping) clearLineMeasurementCache(this);
  6758. var lineNo = cm.display.viewFrom;
  6759. cm.doc.iter(lineNo, cm.display.viewTo, function(line) {
  6760. if (line.widgets) for (var i = 0; i < line.widgets.length; i++)
  6761. if (line.widgets[i].noHScroll) { regLineChange(cm, lineNo, "widget"); break; }
  6762. ++lineNo;
  6763. });
  6764. cm.curOp.forceUpdate = true;
  6765. signal(cm, "refresh", this);
  6766. }),
  6767. operation: function(f){return runInOp(this, f);},
  6768. refresh: methodOp(function() {
  6769. var oldHeight = this.display.cachedTextHeight;
  6770. regChange(this);
  6771. this.curOp.forceUpdate = true;
  6772. clearCaches(this);
  6773. this.scrollTo(this.doc.scrollLeft, this.doc.scrollTop);
  6774. updateGutterSpace(this);
  6775. if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5)
  6776. estimateLineHeights(this);
  6777. signal(this, "refresh", this);
  6778. }),
  6779. swapDoc: methodOp(function(doc) {
  6780. var old = this.doc;
  6781. old.cm = null;
  6782. attachDoc(this, doc);
  6783. clearCaches(this);
  6784. this.display.input.reset();
  6785. this.scrollTo(doc.scrollLeft, doc.scrollTop);
  6786. this.curOp.forceScroll = true;
  6787. signalLater(this, "swapDoc", this, old);
  6788. return old;
  6789. }),
  6790. getInputField: function(){return this.display.input.getField();},
  6791. getWrapperElement: function(){return this.display.wrapper;},
  6792. getScrollerElement: function(){return this.display.scroller;},
  6793. getGutterElement: function(){return this.display.gutters;}
  6794. };
  6795. eventMixin(CodeMirror);
  6796. // OPTION DEFAULTS
  6797. // The default configuration options.
  6798. var defaults = CodeMirror.defaults = {};
  6799. // Functions to run when options are changed.
  6800. var optionHandlers = CodeMirror.optionHandlers = {};
  6801. function option(name, deflt, handle, notOnInit) {
  6802. CodeMirror.defaults[name] = deflt;
  6803. if (handle) optionHandlers[name] =
  6804. notOnInit ? function(cm, val, old) {if (old != Init) handle(cm, val, old);} : handle;
  6805. }
  6806. // Passed to option handlers when there is no old value.
  6807. var Init = CodeMirror.Init = {toString: function(){return "CodeMirror.Init";}};
  6808. // These two are, on init, called from the constructor because they
  6809. // have to be initialized before the editor can start at all.
  6810. option("value", "", function(cm, val) {
  6811. cm.setValue(val);
  6812. }, true);
  6813. option("mode", null, function(cm, val) {
  6814. cm.doc.modeOption = val;
  6815. loadMode(cm);
  6816. }, true);
  6817. option("indentUnit", 2, loadMode, true);
  6818. option("indentWithTabs", false);
  6819. option("smartIndent", true);
  6820. option("tabSize", 4, function(cm) {
  6821. resetModeState(cm);
  6822. clearCaches(cm);
  6823. regChange(cm);
  6824. }, true);
  6825. option("lineSeparator", null, function(cm, val) {
  6826. cm.doc.lineSep = val;
  6827. if (!val) return;
  6828. var newBreaks = [], lineNo = cm.doc.first;
  6829. cm.doc.iter(function(line) {
  6830. for (var pos = 0;;) {
  6831. var found = line.text.indexOf(val, pos);
  6832. if (found == -1) break;
  6833. pos = found + val.length;
  6834. newBreaks.push(Pos(lineNo, found));
  6835. }
  6836. lineNo++;
  6837. });
  6838. for (var i = newBreaks.length - 1; i >= 0; i--)
  6839. replaceRange(cm.doc, val, newBreaks[i], Pos(newBreaks[i].line, newBreaks[i].ch + val.length))
  6840. });
  6841. option("specialChars", /[\u0000-\u001f\u007f\u00ad\u200b-\u200f\u2028\u2029\ufeff]/g, function(cm, val, old) {
  6842. cm.state.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g");
  6843. if (old != CodeMirror.Init) cm.refresh();
  6844. });
  6845. option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function(cm) {cm.refresh();}, true);
  6846. option("electricChars", true);
  6847. option("inputStyle", mobile ? "contenteditable" : "textarea", function() {
  6848. throw new Error("inputStyle can not (yet) be changed in a running editor"); // FIXME
  6849. }, true);
  6850. option("rtlMoveVisually", !windows);
  6851. option("wholeLineUpdateBefore", true);
  6852. option("theme", "default", function(cm) {
  6853. themeChanged(cm);
  6854. guttersChanged(cm);
  6855. }, true);
  6856. option("keyMap", "default", function(cm, val, old) {
  6857. var next = getKeyMap(val);
  6858. var prev = old != CodeMirror.Init && getKeyMap(old);
  6859. if (prev && prev.detach) prev.detach(cm, next);
  6860. if (next.attach) next.attach(cm, prev || null);
  6861. });
  6862. option("extraKeys", null);
  6863. option("lineWrapping", false, wrappingChanged, true);
  6864. option("gutters", [], function(cm) {
  6865. setGuttersForLineNumbers(cm.options);
  6866. guttersChanged(cm);
  6867. }, true);
  6868. option("fixedGutter", true, function(cm, val) {
  6869. cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0";
  6870. cm.refresh();
  6871. }, true);
  6872. option("coverGutterNextToScrollbar", false, function(cm) {updateScrollbars(cm);}, true);
  6873. option("scrollbarStyle", "native", function(cm) {
  6874. initScrollbars(cm);
  6875. updateScrollbars(cm);
  6876. cm.display.scrollbars.setScrollTop(cm.doc.scrollTop);
  6877. cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft);
  6878. }, true);
  6879. option("lineNumbers", false, function(cm) {
  6880. setGuttersForLineNumbers(cm.options);
  6881. guttersChanged(cm);
  6882. }, true);
  6883. option("firstLineNumber", 1, guttersChanged, true);
  6884. option("lineNumberFormatter", function(integer) {return integer;}, guttersChanged, true);
  6885. option("showCursorWhenSelecting", false, updateSelection, true);
  6886. option("resetSelectionOnContextMenu", true);
  6887. option("lineWiseCopyCut", true);
  6888. option("readOnly", false, function(cm, val) {
  6889. if (val == "nocursor") {
  6890. onBlur(cm);
  6891. cm.display.input.blur();
  6892. cm.display.disabled = true;
  6893. } else {
  6894. cm.display.disabled = false;
  6895. }
  6896. cm.display.input.readOnlyChanged(val)
  6897. });
  6898. option("disableInput", false, function(cm, val) {if (!val) cm.display.input.reset();}, true);
  6899. option("dragDrop", true, dragDropChanged);
  6900. option("allowDropFileTypes", null);
  6901. option("cursorBlinkRate", 530);
  6902. option("cursorScrollMargin", 0);
  6903. option("cursorHeight", 1, updateSelection, true);
  6904. option("singleCursorHeightPerLine", true, updateSelection, true);
  6905. option("workTime", 100);
  6906. option("workDelay", 100);
  6907. option("flattenSpans", true, resetModeState, true);
  6908. option("addModeClass", false, resetModeState, true);
  6909. option("pollInterval", 100);
  6910. option("undoDepth", 200, function(cm, val){cm.doc.history.undoDepth = val;});
  6911. option("historyEventDelay", 1250);
  6912. option("viewportMargin", 10, function(cm){cm.refresh();}, true);
  6913. option("maxHighlightLength", 10000, resetModeState, true);
  6914. option("moveInputWithCursor", true, function(cm, val) {
  6915. if (!val) cm.display.input.resetPosition();
  6916. });
  6917. option("tabindex", null, function(cm, val) {
  6918. cm.display.input.getField().tabIndex = val || "";
  6919. });
  6920. option("autofocus", null);
  6921. // MODE DEFINITION AND QUERYING
  6922. // Known modes, by name and by MIME
  6923. var modes = CodeMirror.modes = {}, mimeModes = CodeMirror.mimeModes = {};
  6924. // Extra arguments are stored as the mode's dependencies, which is
  6925. // used by (legacy) mechanisms like loadmode.js to automatically
  6926. // load a mode. (Preferred mechanism is the require/define calls.)
  6927. CodeMirror.defineMode = function(name, mode) {
  6928. if (!CodeMirror.defaults.mode && name != "null") CodeMirror.defaults.mode = name;
  6929. if (arguments.length > 2)
  6930. mode.dependencies = Array.prototype.slice.call(arguments, 2);
  6931. modes[name] = mode;
  6932. };
  6933. CodeMirror.defineMIME = function(mime, spec) {
  6934. mimeModes[mime] = spec;
  6935. };
  6936. // Given a MIME type, a {name, ...options} config object, or a name
  6937. // string, return a mode config object.
  6938. CodeMirror.resolveMode = function(spec) {
  6939. if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) {
  6940. spec = mimeModes[spec];
  6941. } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) {
  6942. var found = mimeModes[spec.name];
  6943. if (typeof found == "string") found = {name: found};
  6944. spec = createObj(found, spec);
  6945. spec.name = found.name;
  6946. } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) {
  6947. return CodeMirror.resolveMode("application/xml");
  6948. }
  6949. if (typeof spec == "string") return {name: spec};
  6950. else return spec || {name: "null"};
  6951. };
  6952. // Given a mode spec (anything that resolveMode accepts), find and
  6953. // initialize an actual mode object.
  6954. CodeMirror.getMode = function(options, spec) {
  6955. var spec = CodeMirror.resolveMode(spec);
  6956. var mfactory = modes[spec.name];
  6957. if (!mfactory) return CodeMirror.getMode(options, "text/plain");
  6958. var modeObj = mfactory(options, spec);
  6959. if (modeExtensions.hasOwnProperty(spec.name)) {
  6960. var exts = modeExtensions[spec.name];
  6961. for (var prop in exts) {
  6962. if (!exts.hasOwnProperty(prop)) continue;
  6963. if (modeObj.hasOwnProperty(prop)) modeObj["_" + prop] = modeObj[prop];
  6964. modeObj[prop] = exts[prop];
  6965. }
  6966. }
  6967. modeObj.name = spec.name;
  6968. if (spec.helperType) modeObj.helperType = spec.helperType;
  6969. if (spec.modeProps) for (var prop in spec.modeProps)
  6970. modeObj[prop] = spec.modeProps[prop];
  6971. return modeObj;
  6972. };
  6973. // Minimal default mode.
  6974. CodeMirror.defineMode("null", function() {
  6975. return {token: function(stream) {stream.skipToEnd();}};
  6976. });
  6977. CodeMirror.defineMIME("text/plain", "null");
  6978. // This can be used to attach properties to mode objects from
  6979. // outside the actual mode definition.
  6980. var modeExtensions = CodeMirror.modeExtensions = {};
  6981. CodeMirror.extendMode = function(mode, properties) {
  6982. var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {});
  6983. copyObj(properties, exts);
  6984. };
  6985. // EXTENSIONS
  6986. CodeMirror.defineExtension = function(name, func) {
  6987. CodeMirror.prototype[name] = func;
  6988. };
  6989. CodeMirror.defineDocExtension = function(name, func) {
  6990. Doc.prototype[name] = func;
  6991. };
  6992. CodeMirror.defineOption = option;
  6993. var initHooks = [];
  6994. CodeMirror.defineInitHook = function(f) {initHooks.push(f);};
  6995. var helpers = CodeMirror.helpers = {};
  6996. CodeMirror.registerHelper = function(type, name, value) {
  6997. if (!helpers.hasOwnProperty(type)) helpers[type] = CodeMirror[type] = {_global: []};
  6998. helpers[type][name] = value;
  6999. };
  7000. CodeMirror.registerGlobalHelper = function(type, name, predicate, value) {
  7001. CodeMirror.registerHelper(type, name, value);
  7002. helpers[type]._global.push({pred: predicate, val: value});
  7003. };
  7004. // MODE STATE HANDLING
  7005. // Utility functions for working with state. Exported because nested
  7006. // modes need to do this for their inner modes.
  7007. var copyState = CodeMirror.copyState = function(mode, state) {
  7008. if (state === true) return state;
  7009. if (mode.copyState) return mode.copyState(state);
  7010. var nstate = {};
  7011. for (var n in state) {
  7012. var val = state[n];
  7013. if (val instanceof Array) val = val.concat([]);
  7014. nstate[n] = val;
  7015. }
  7016. return nstate;
  7017. };
  7018. var startState = CodeMirror.startState = function(mode, a1, a2) {
  7019. return mode.startState ? mode.startState(a1, a2) : true;
  7020. };
  7021. // Given a mode and a state (for that mode), find the inner mode and
  7022. // state at the position that the state refers to.
  7023. CodeMirror.innerMode = function(mode, state) {
  7024. while (mode.innerMode) {
  7025. var info = mode.innerMode(state);
  7026. if (!info || info.mode == mode) break;
  7027. state = info.state;
  7028. mode = info.mode;
  7029. }
  7030. return info || {mode: mode, state: state};
  7031. };
  7032. // STANDARD COMMANDS
  7033. // Commands are parameter-less actions that can be performed on an
  7034. // editor, mostly used for keybindings.
  7035. var commands = CodeMirror.commands = {
  7036. selectAll: function(cm) {cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll);},
  7037. singleSelection: function(cm) {
  7038. cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll);
  7039. },
  7040. killLine: function(cm) {
  7041. deleteNearSelection(cm, function(range) {
  7042. if (range.empty()) {
  7043. var len = getLine(cm.doc, range.head.line).text.length;
  7044. if (range.head.ch == len && range.head.line < cm.lastLine())
  7045. return {from: range.head, to: Pos(range.head.line + 1, 0)};
  7046. else
  7047. return {from: range.head, to: Pos(range.head.line, len)};
  7048. } else {
  7049. return {from: range.from(), to: range.to()};
  7050. }
  7051. });
  7052. },
  7053. deleteLine: function(cm) {
  7054. deleteNearSelection(cm, function(range) {
  7055. return {from: Pos(range.from().line, 0),
  7056. to: clipPos(cm.doc, Pos(range.to().line + 1, 0))};
  7057. });
  7058. },
  7059. delLineLeft: function(cm) {
  7060. deleteNearSelection(cm, function(range) {
  7061. return {from: Pos(range.from().line, 0), to: range.from()};
  7062. });
  7063. },
  7064. delWrappedLineLeft: function(cm) {
  7065. deleteNearSelection(cm, function(range) {
  7066. var top = cm.charCoords(range.head, "div").top + 5;
  7067. var leftPos = cm.coordsChar({left: 0, top: top}, "div");
  7068. return {from: leftPos, to: range.from()};
  7069. });
  7070. },
  7071. delWrappedLineRight: function(cm) {
  7072. deleteNearSelection(cm, function(range) {
  7073. var top = cm.charCoords(range.head, "div").top + 5;
  7074. var rightPos = cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div");
  7075. return {from: range.from(), to: rightPos };
  7076. });
  7077. },
  7078. undo: function(cm) {cm.undo();},
  7079. redo: function(cm) {cm.redo();},
  7080. undoSelection: function(cm) {cm.undoSelection();},
  7081. redoSelection: function(cm) {cm.redoSelection();},
  7082. goDocStart: function(cm) {cm.extendSelection(Pos(cm.firstLine(), 0));},
  7083. goDocEnd: function(cm) {cm.extendSelection(Pos(cm.lastLine()));},
  7084. goLineStart: function(cm) {
  7085. cm.extendSelectionsBy(function(range) { return lineStart(cm, range.head.line); },
  7086. {origin: "+move", bias: 1});
  7087. },
  7088. goLineStartSmart: function(cm) {
  7089. cm.extendSelectionsBy(function(range) {
  7090. return lineStartSmart(cm, range.head);
  7091. }, {origin: "+move", bias: 1});
  7092. },
  7093. goLineEnd: function(cm) {
  7094. cm.extendSelectionsBy(function(range) { return lineEnd(cm, range.head.line); },
  7095. {origin: "+move", bias: -1});
  7096. },
  7097. goLineRight: function(cm) {
  7098. cm.extendSelectionsBy(function(range) {
  7099. var top = cm.charCoords(range.head, "div").top + 5;
  7100. return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div");
  7101. }, sel_move);
  7102. },
  7103. goLineLeft: function(cm) {
  7104. cm.extendSelectionsBy(function(range) {
  7105. var top = cm.charCoords(range.head, "div").top + 5;
  7106. return cm.coordsChar({left: 0, top: top}, "div");
  7107. }, sel_move);
  7108. },
  7109. goLineLeftSmart: function(cm) {
  7110. cm.extendSelectionsBy(function(range) {
  7111. var top = cm.charCoords(range.head, "div").top + 5;
  7112. var pos = cm.coordsChar({left: 0, top: top}, "div");
  7113. if (pos.ch < cm.getLine(pos.line).search(/\S/)) return lineStartSmart(cm, range.head);
  7114. return pos;
  7115. }, sel_move);
  7116. },
  7117. goLineUp: function(cm) {cm.moveV(-1, "line");},
  7118. goLineDown: function(cm) {cm.moveV(1, "line");},
  7119. goPageUp: function(cm) {cm.moveV(-1, "page");},
  7120. goPageDown: function(cm) {cm.moveV(1, "page");},
  7121. goCharLeft: function(cm) {cm.moveH(-1, "char");},
  7122. goCharRight: function(cm) {cm.moveH(1, "char");},
  7123. goColumnLeft: function(cm) {cm.moveH(-1, "column");},
  7124. goColumnRight: function(cm) {cm.moveH(1, "column");},
  7125. goWordLeft: function(cm) {cm.moveH(-1, "word");},
  7126. goGroupRight: function(cm) {cm.moveH(1, "group");},
  7127. goGroupLeft: function(cm) {cm.moveH(-1, "group");},
  7128. goWordRight: function(cm) {cm.moveH(1, "word");},
  7129. delCharBefore: function(cm) {cm.deleteH(-1, "char");},
  7130. delCharAfter: function(cm) {cm.deleteH(1, "char");},
  7131. delWordBefore: function(cm) {cm.deleteH(-1, "word");},
  7132. delWordAfter: function(cm) {cm.deleteH(1, "word");},
  7133. delGroupBefore: function(cm) {cm.deleteH(-1, "group");},
  7134. delGroupAfter: function(cm) {cm.deleteH(1, "group");},
  7135. indentAuto: function(cm) {cm.indentSelection("smart");},
  7136. indentMore: function(cm) {cm.indentSelection("add");},
  7137. indentLess: function(cm) {cm.indentSelection("subtract");},
  7138. insertTab: function(cm) {cm.replaceSelection("\t");},
  7139. insertSoftTab: function(cm) {
  7140. var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize;
  7141. for (var i = 0; i < ranges.length; i++) {
  7142. var pos = ranges[i].from();
  7143. var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize);
  7144. spaces.push(spaceStr(tabSize - col % tabSize));
  7145. }
  7146. cm.replaceSelections(spaces);
  7147. },
  7148. defaultTab: function(cm) {
  7149. if (cm.somethingSelected()) cm.indentSelection("add");
  7150. else cm.execCommand("insertTab");
  7151. },
  7152. transposeChars: function(cm) {
  7153. runInOp(cm, function() {
  7154. var ranges = cm.listSelections(), newSel = [];
  7155. for (var i = 0; i < ranges.length; i++) {
  7156. var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text;
  7157. if (line) {
  7158. if (cur.ch == line.length) cur = new Pos(cur.line, cur.ch - 1);
  7159. if (cur.ch > 0) {
  7160. cur = new Pos(cur.line, cur.ch + 1);
  7161. cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2),
  7162. Pos(cur.line, cur.ch - 2), cur, "+transpose");
  7163. } else if (cur.line > cm.doc.first) {
  7164. var prev = getLine(cm.doc, cur.line - 1).text;
  7165. if (prev)
  7166. cm.replaceRange(line.charAt(0) + cm.doc.lineSeparator() +
  7167. prev.charAt(prev.length - 1),
  7168. Pos(cur.line - 1, prev.length - 1), Pos(cur.line, 1), "+transpose");
  7169. }
  7170. }
  7171. newSel.push(new Range(cur, cur));
  7172. }
  7173. cm.setSelections(newSel);
  7174. });
  7175. },
  7176. newlineAndIndent: function(cm) {
  7177. runInOp(cm, function() {
  7178. var len = cm.listSelections().length;
  7179. for (var i = 0; i < len; i++) {
  7180. var range = cm.listSelections()[i];
  7181. cm.replaceRange(cm.doc.lineSeparator(), range.anchor, range.head, "+input");
  7182. cm.indentLine(range.from().line + 1, null, true);
  7183. }
  7184. ensureCursorVisible(cm);
  7185. });
  7186. },
  7187. openLine: function(cm) {cm.replaceSelection("\n", "start")},
  7188. toggleOverwrite: function(cm) {cm.toggleOverwrite();}
  7189. };
  7190. // STANDARD KEYMAPS
  7191. var keyMap = CodeMirror.keyMap = {};
  7192. keyMap.basic = {
  7193. "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown",
  7194. "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown",
  7195. "Delete": "delCharAfter", "Backspace": "delCharBefore", "Shift-Backspace": "delCharBefore",
  7196. "Tab": "defaultTab", "Shift-Tab": "indentAuto",
  7197. "Enter": "newlineAndIndent", "Insert": "toggleOverwrite",
  7198. "Esc": "singleSelection"
  7199. };
  7200. // Note that the save and find-related commands aren't defined by
  7201. // default. User code or addons can define them. Unknown commands
  7202. // are simply ignored.
  7203. keyMap.pcDefault = {
  7204. "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo",
  7205. "Ctrl-Home": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Up": "goLineUp", "Ctrl-Down": "goLineDown",
  7206. "Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd",
  7207. "Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find",
  7208. "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll",
  7209. "Ctrl-[": "indentLess", "Ctrl-]": "indentMore",
  7210. "Ctrl-U": "undoSelection", "Shift-Ctrl-U": "redoSelection", "Alt-U": "redoSelection",
  7211. fallthrough: "basic"
  7212. };
  7213. // Very basic readline/emacs-style bindings, which are standard on Mac.
  7214. keyMap.emacsy = {
  7215. "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown",
  7216. "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd",
  7217. "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp", "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore",
  7218. "Alt-D": "delWordAfter", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars",
  7219. "Ctrl-O": "openLine"
  7220. };
  7221. keyMap.macDefault = {
  7222. "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo",
  7223. "Cmd-Home": "goDocStart", "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft",
  7224. "Alt-Right": "goGroupRight", "Cmd-Left": "goLineLeft", "Cmd-Right": "goLineRight", "Alt-Backspace": "delGroupBefore",
  7225. "Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find",
  7226. "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll",
  7227. "Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delWrappedLineLeft", "Cmd-Delete": "delWrappedLineRight",
  7228. "Cmd-U": "undoSelection", "Shift-Cmd-U": "redoSelection", "Ctrl-Up": "goDocStart", "Ctrl-Down": "goDocEnd",
  7229. fallthrough: ["basic", "emacsy"]
  7230. };
  7231. keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault;
  7232. // KEYMAP DISPATCH
  7233. function normalizeKeyName(name) {
  7234. var parts = name.split(/-(?!$)/), name = parts[parts.length - 1];
  7235. var alt, ctrl, shift, cmd;
  7236. for (var i = 0; i < parts.length - 1; i++) {
  7237. var mod = parts[i];
  7238. if (/^(cmd|meta|m)$/i.test(mod)) cmd = true;
  7239. else if (/^a(lt)?$/i.test(mod)) alt = true;
  7240. else if (/^(c|ctrl|control)$/i.test(mod)) ctrl = true;
  7241. else if (/^s(hift)$/i.test(mod)) shift = true;
  7242. else throw new Error("Unrecognized modifier name: " + mod);
  7243. }
  7244. if (alt) name = "Alt-" + name;
  7245. if (ctrl) name = "Ctrl-" + name;
  7246. if (cmd) name = "Cmd-" + name;
  7247. if (shift) name = "Shift-" + name;
  7248. return name;
  7249. }
  7250. // This is a kludge to keep keymaps mostly working as raw objects
  7251. // (backwards compatibility) while at the same time support features
  7252. // like normalization and multi-stroke key bindings. It compiles a
  7253. // new normalized keymap, and then updates the old object to reflect
  7254. // this.
  7255. CodeMirror.normalizeKeyMap = function(keymap) {
  7256. var copy = {};
  7257. for (var keyname in keymap) if (keymap.hasOwnProperty(keyname)) {
  7258. var value = keymap[keyname];
  7259. if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) continue;
  7260. if (value == "...") { delete keymap[keyname]; continue; }
  7261. var keys = map(keyname.split(" "), normalizeKeyName);
  7262. for (var i = 0; i < keys.length; i++) {
  7263. var val, name;
  7264. if (i == keys.length - 1) {
  7265. name = keys.join(" ");
  7266. val = value;
  7267. } else {
  7268. name = keys.slice(0, i + 1).join(" ");
  7269. val = "...";
  7270. }
  7271. var prev = copy[name];
  7272. if (!prev) copy[name] = val;
  7273. else if (prev != val) throw new Error("Inconsistent bindings for " + name);
  7274. }
  7275. delete keymap[keyname];
  7276. }
  7277. for (var prop in copy) keymap[prop] = copy[prop];
  7278. return keymap;
  7279. };
  7280. var lookupKey = CodeMirror.lookupKey = function(key, map, handle, context) {
  7281. map = getKeyMap(map);
  7282. var found = map.call ? map.call(key, context) : map[key];
  7283. if (found === false) return "nothing";
  7284. if (found === "...") return "multi";
  7285. if (found != null && handle(found)) return "handled";
  7286. if (map.fallthrough) {
  7287. if (Object.prototype.toString.call(map.fallthrough) != "[object Array]")
  7288. return lookupKey(key, map.fallthrough, handle, context);
  7289. for (var i = 0; i < map.fallthrough.length; i++) {
  7290. var result = lookupKey(key, map.fallthrough[i], handle, context);
  7291. if (result) return result;
  7292. }
  7293. }
  7294. };
  7295. // Modifier key presses don't count as 'real' key presses for the
  7296. // purpose of keymap fallthrough.
  7297. var isModifierKey = CodeMirror.isModifierKey = function(value) {
  7298. var name = typeof value == "string" ? value : keyNames[value.keyCode];
  7299. return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod";
  7300. };
  7301. // Look up the name of a key as indicated by an event object.
  7302. var keyName = CodeMirror.keyName = function(event, noShift) {
  7303. if (presto && event.keyCode == 34 && event["char"]) return false;
  7304. var base = keyNames[event.keyCode], name = base;
  7305. if (name == null || event.altGraphKey) return false;
  7306. if (event.altKey && base != "Alt") name = "Alt-" + name;
  7307. if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != "Ctrl") name = "Ctrl-" + name;
  7308. if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != "Cmd") name = "Cmd-" + name;
  7309. if (!noShift && event.shiftKey && base != "Shift") name = "Shift-" + name;
  7310. return name;
  7311. };
  7312. function getKeyMap(val) {
  7313. return typeof val == "string" ? keyMap[val] : val;
  7314. }
  7315. // FROMTEXTAREA
  7316. CodeMirror.fromTextArea = function(textarea, options) {
  7317. options = options ? copyObj(options) : {};
  7318. options.value = textarea.value;
  7319. if (!options.tabindex && textarea.tabIndex)
  7320. options.tabindex = textarea.tabIndex;
  7321. if (!options.placeholder && textarea.placeholder)
  7322. options.placeholder = textarea.placeholder;
  7323. // Set autofocus to true if this textarea is focused, or if it has
  7324. // autofocus and no other element is focused.
  7325. if (options.autofocus == null) {
  7326. var hasFocus = activeElt();
  7327. options.autofocus = hasFocus == textarea ||
  7328. textarea.getAttribute("autofocus") != null && hasFocus == document.body;
  7329. }
  7330. function save() {textarea.value = cm.getValue();}
  7331. if (textarea.form) {
  7332. on(textarea.form, "submit", save);
  7333. // Deplorable hack to make the submit method do the right thing.
  7334. if (!options.leaveSubmitMethodAlone) {
  7335. var form = textarea.form, realSubmit = form.submit;
  7336. try {
  7337. var wrappedSubmit = form.submit = function() {
  7338. save();
  7339. form.submit = realSubmit;
  7340. form.submit();
  7341. form.submit = wrappedSubmit;
  7342. };
  7343. } catch(e) {}
  7344. }
  7345. }
  7346. options.finishInit = function(cm) {
  7347. cm.save = save;
  7348. cm.getTextArea = function() { return textarea; };
  7349. cm.toTextArea = function() {
  7350. cm.toTextArea = isNaN; // Prevent this from being ran twice
  7351. save();
  7352. textarea.parentNode.removeChild(cm.getWrapperElement());
  7353. textarea.style.display = "";
  7354. if (textarea.form) {
  7355. off(textarea.form, "submit", save);
  7356. if (typeof textarea.form.submit == "function")
  7357. textarea.form.submit = realSubmit;
  7358. }
  7359. };
  7360. };
  7361. textarea.style.display = "none";
  7362. var cm = CodeMirror(function(node) {
  7363. textarea.parentNode.insertBefore(node, textarea.nextSibling);
  7364. }, options);
  7365. return cm;
  7366. };
  7367. // STRING STREAM
  7368. // Fed to the mode parsers, provides helper functions to make
  7369. // parsers more succinct.
  7370. var StringStream = CodeMirror.StringStream = function(string, tabSize) {
  7371. this.pos = this.start = 0;
  7372. this.string = string;
  7373. this.tabSize = tabSize || 8;
  7374. this.lastColumnPos = this.lastColumnValue = 0;
  7375. this.lineStart = 0;
  7376. };
  7377. StringStream.prototype = {
  7378. eol: function() {return this.pos >= this.string.length;},
  7379. sol: function() {return this.pos == this.lineStart;},
  7380. peek: function() {return this.string.charAt(this.pos) || undefined;},
  7381. next: function() {
  7382. if (this.pos < this.string.length)
  7383. return this.string.charAt(this.pos++);
  7384. },
  7385. eat: function(match) {
  7386. var ch = this.string.charAt(this.pos);
  7387. if (typeof match == "string") var ok = ch == match;
  7388. else var ok = ch && (match.test ? match.test(ch) : match(ch));
  7389. if (ok) {++this.pos; return ch;}
  7390. },
  7391. eatWhile: function(match) {
  7392. var start = this.pos;
  7393. while (this.eat(match)){}
  7394. return this.pos > start;
  7395. },
  7396. eatSpace: function() {
  7397. var start = this.pos;
  7398. while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) ++this.pos;
  7399. return this.pos > start;
  7400. },
  7401. skipToEnd: function() {this.pos = this.string.length;},
  7402. skipTo: function(ch) {
  7403. var found = this.string.indexOf(ch, this.pos);
  7404. if (found > -1) {this.pos = found; return true;}
  7405. },
  7406. backUp: function(n) {this.pos -= n;},
  7407. column: function() {
  7408. if (this.lastColumnPos < this.start) {
  7409. this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue);
  7410. this.lastColumnPos = this.start;
  7411. }
  7412. return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0);
  7413. },
  7414. indentation: function() {
  7415. return countColumn(this.string, null, this.tabSize) -
  7416. (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0);
  7417. },
  7418. match: function(pattern, consume, caseInsensitive) {
  7419. if (typeof pattern == "string") {
  7420. var cased = function(str) {return caseInsensitive ? str.toLowerCase() : str;};
  7421. var substr = this.string.substr(this.pos, pattern.length);
  7422. if (cased(substr) == cased(pattern)) {
  7423. if (consume !== false) this.pos += pattern.length;
  7424. return true;
  7425. }
  7426. } else {
  7427. var match = this.string.slice(this.pos).match(pattern);
  7428. if (match && match.index > 0) return null;
  7429. if (match && consume !== false) this.pos += match[0].length;
  7430. return match;
  7431. }
  7432. },
  7433. current: function(){return this.string.slice(this.start, this.pos);},
  7434. hideFirstChars: function(n, inner) {
  7435. this.lineStart += n;
  7436. try { return inner(); }
  7437. finally { this.lineStart -= n; }
  7438. }
  7439. };
  7440. // TEXTMARKERS
  7441. // Created with markText and setBookmark methods. A TextMarker is a
  7442. // handle that can be used to clear or find a marked position in the
  7443. // document. Line objects hold arrays (markedSpans) containing
  7444. // {from, to, marker} object pointing to such marker objects, and
  7445. // indicating that such a marker is present on that line. Multiple
  7446. // lines may point to the same marker when it spans across lines.
  7447. // The spans will have null for their from/to properties when the
  7448. // marker continues beyond the start/end of the line. Markers have
  7449. // links back to the lines they currently touch.
  7450. var nextMarkerId = 0;
  7451. var TextMarker = CodeMirror.TextMarker = function(doc, type) {
  7452. this.lines = [];
  7453. this.type = type;
  7454. this.doc = doc;
  7455. this.id = ++nextMarkerId;
  7456. };
  7457. eventMixin(TextMarker);
  7458. // Clear the marker.
  7459. TextMarker.prototype.clear = function() {
  7460. if (this.explicitlyCleared) return;
  7461. var cm = this.doc.cm, withOp = cm && !cm.curOp;
  7462. if (withOp) startOperation(cm);
  7463. if (hasHandler(this, "clear")) {
  7464. var found = this.find();
  7465. if (found) signalLater(this, "clear", found.from, found.to);
  7466. }
  7467. var min = null, max = null;
  7468. for (var i = 0; i < this.lines.length; ++i) {
  7469. var line = this.lines[i];
  7470. var span = getMarkedSpanFor(line.markedSpans, this);
  7471. if (cm && !this.collapsed) regLineChange(cm, lineNo(line), "text");
  7472. else if (cm) {
  7473. if (span.to != null) max = lineNo(line);
  7474. if (span.from != null) min = lineNo(line);
  7475. }
  7476. line.markedSpans = removeMarkedSpan(line.markedSpans, span);
  7477. if (span.from == null && this.collapsed && !lineIsHidden(this.doc, line) && cm)
  7478. updateLineHeight(line, textHeight(cm.display));
  7479. }
  7480. if (cm && this.collapsed && !cm.options.lineWrapping) for (var i = 0; i < this.lines.length; ++i) {
  7481. var visual = visualLine(this.lines[i]), len = lineLength(visual);
  7482. if (len > cm.display.maxLineLength) {
  7483. cm.display.maxLine = visual;
  7484. cm.display.maxLineLength = len;
  7485. cm.display.maxLineChanged = true;
  7486. }
  7487. }
  7488. if (min != null && cm && this.collapsed) regChange(cm, min, max + 1);
  7489. this.lines.length = 0;
  7490. this.explicitlyCleared = true;
  7491. if (this.atomic && this.doc.cantEdit) {
  7492. this.doc.cantEdit = false;
  7493. if (cm) reCheckSelection(cm.doc);
  7494. }
  7495. if (cm) signalLater(cm, "markerCleared", cm, this);
  7496. if (withOp) endOperation(cm);
  7497. if (this.parent) this.parent.clear();
  7498. };
  7499. // Find the position of the marker in the document. Returns a {from,
  7500. // to} object by default. Side can be passed to get a specific side
  7501. // -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the
  7502. // Pos objects returned contain a line object, rather than a line
  7503. // number (used to prevent looking up the same line twice).
  7504. TextMarker.prototype.find = function(side, lineObj) {
  7505. if (side == null && this.type == "bookmark") side = 1;
  7506. var from, to;
  7507. for (var i = 0; i < this.lines.length; ++i) {
  7508. var line = this.lines[i];
  7509. var span = getMarkedSpanFor(line.markedSpans, this);
  7510. if (span.from != null) {
  7511. from = Pos(lineObj ? line : lineNo(line), span.from);
  7512. if (side == -1) return from;
  7513. }
  7514. if (span.to != null) {
  7515. to = Pos(lineObj ? line : lineNo(line), span.to);
  7516. if (side == 1) return to;
  7517. }
  7518. }
  7519. return from && {from: from, to: to};
  7520. };
  7521. // Signals that the marker's widget changed, and surrounding layout
  7522. // should be recomputed.
  7523. TextMarker.prototype.changed = function() {
  7524. var pos = this.find(-1, true), widget = this, cm = this.doc.cm;
  7525. if (!pos || !cm) return;
  7526. runInOp(cm, function() {
  7527. var line = pos.line, lineN = lineNo(pos.line);
  7528. var view = findViewForLine(cm, lineN);
  7529. if (view) {
  7530. clearLineMeasurementCacheFor(view);
  7531. cm.curOp.selectionChanged = cm.curOp.forceUpdate = true;
  7532. }
  7533. cm.curOp.updateMaxLine = true;
  7534. if (!lineIsHidden(widget.doc, line) && widget.height != null) {
  7535. var oldHeight = widget.height;
  7536. widget.height = null;
  7537. var dHeight = widgetHeight(widget) - oldHeight;
  7538. if (dHeight)
  7539. updateLineHeight(line, line.height + dHeight);
  7540. }
  7541. });
  7542. };
  7543. TextMarker.prototype.attachLine = function(line) {
  7544. if (!this.lines.length && this.doc.cm) {
  7545. var op = this.doc.cm.curOp;
  7546. if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1)
  7547. (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this);
  7548. }
  7549. this.lines.push(line);
  7550. };
  7551. TextMarker.prototype.detachLine = function(line) {
  7552. this.lines.splice(indexOf(this.lines, line), 1);
  7553. if (!this.lines.length && this.doc.cm) {
  7554. var op = this.doc.cm.curOp;
  7555. (op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this);
  7556. }
  7557. };
  7558. // Collapsed markers have unique ids, in order to be able to order
  7559. // them, which is needed for uniquely determining an outer marker
  7560. // when they overlap (they may nest, but not partially overlap).
  7561. var nextMarkerId = 0;
  7562. // Create a marker, wire it up to the right lines, and
  7563. function markText(doc, from, to, options, type) {
  7564. // Shared markers (across linked documents) are handled separately
  7565. // (markTextShared will call out to this again, once per
  7566. // document).
  7567. if (options && options.shared) return markTextShared(doc, from, to, options, type);
  7568. // Ensure we are in an operation.
  7569. if (doc.cm && !doc.cm.curOp) return operation(doc.cm, markText)(doc, from, to, options, type);
  7570. var marker = new TextMarker(doc, type), diff = cmp(from, to);
  7571. if (options) copyObj(options, marker, false);
  7572. // Don't connect empty markers unless clearWhenEmpty is false
  7573. if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false)
  7574. return marker;
  7575. if (marker.replacedWith) {
  7576. // Showing up as a widget implies collapsed (widget replaces text)
  7577. marker.collapsed = true;
  7578. marker.widgetNode = elt("span", [marker.replacedWith], "CodeMirror-widget");
  7579. if (!options.handleMouseEvents) marker.widgetNode.setAttribute("cm-ignore-events", "true");
  7580. if (options.insertLeft) marker.widgetNode.insertLeft = true;
  7581. }
  7582. if (marker.collapsed) {
  7583. if (conflictingCollapsedRange(doc, from.line, from, to, marker) ||
  7584. from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker))
  7585. throw new Error("Inserting collapsed marker partially overlapping an existing one");
  7586. sawCollapsedSpans = true;
  7587. }
  7588. if (marker.addToHistory)
  7589. addChangeToHistory(doc, {from: from, to: to, origin: "markText"}, doc.sel, NaN);
  7590. var curLine = from.line, cm = doc.cm, updateMaxLine;
  7591. doc.iter(curLine, to.line + 1, function(line) {
  7592. if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine)
  7593. updateMaxLine = true;
  7594. if (marker.collapsed && curLine != from.line) updateLineHeight(line, 0);
  7595. addMarkedSpan(line, new MarkedSpan(marker,
  7596. curLine == from.line ? from.ch : null,
  7597. curLine == to.line ? to.ch : null));
  7598. ++curLine;
  7599. });
  7600. // lineIsHidden depends on the presence of the spans, so needs a second pass
  7601. if (marker.collapsed) doc.iter(from.line, to.line + 1, function(line) {
  7602. if (lineIsHidden(doc, line)) updateLineHeight(line, 0);
  7603. });
  7604. if (marker.clearOnEnter) on(marker, "beforeCursorEnter", function() { marker.clear(); });
  7605. if (marker.readOnly) {
  7606. sawReadOnlySpans = true;
  7607. if (doc.history.done.length || doc.history.undone.length)
  7608. doc.clearHistory();
  7609. }
  7610. if (marker.collapsed) {
  7611. marker.id = ++nextMarkerId;
  7612. marker.atomic = true;
  7613. }
  7614. if (cm) {
  7615. // Sync editor state
  7616. if (updateMaxLine) cm.curOp.updateMaxLine = true;
  7617. if (marker.collapsed)
  7618. regChange(cm, from.line, to.line + 1);
  7619. else if (marker.className || marker.title || marker.startStyle || marker.endStyle || marker.css)
  7620. for (var i = from.line; i <= to.line; i++) regLineChange(cm, i, "text");
  7621. if (marker.atomic) reCheckSelection(cm.doc);
  7622. signalLater(cm, "markerAdded", cm, marker);
  7623. }
  7624. return marker;
  7625. }
  7626. // SHARED TEXTMARKERS
  7627. // A shared marker spans multiple linked documents. It is
  7628. // implemented as a meta-marker-object controlling multiple normal
  7629. // markers.
  7630. var SharedTextMarker = CodeMirror.SharedTextMarker = function(markers, primary) {
  7631. this.markers = markers;
  7632. this.primary = primary;
  7633. for (var i = 0; i < markers.length; ++i)
  7634. markers[i].parent = this;
  7635. };
  7636. eventMixin(SharedTextMarker);
  7637. SharedTextMarker.prototype.clear = function() {
  7638. if (this.explicitlyCleared) return;
  7639. this.explicitlyCleared = true;
  7640. for (var i = 0; i < this.markers.length; ++i)
  7641. this.markers[i].clear();
  7642. signalLater(this, "clear");
  7643. };
  7644. SharedTextMarker.prototype.find = function(side, lineObj) {
  7645. return this.primary.find(side, lineObj);
  7646. };
  7647. function markTextShared(doc, from, to, options, type) {
  7648. options = copyObj(options);
  7649. options.shared = false;
  7650. var markers = [markText(doc, from, to, options, type)], primary = markers[0];
  7651. var widget = options.widgetNode;
  7652. linkedDocs(doc, function(doc) {
  7653. if (widget) options.widgetNode = widget.cloneNode(true);
  7654. markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type));
  7655. for (var i = 0; i < doc.linked.length; ++i)
  7656. if (doc.linked[i].isParent) return;
  7657. primary = lst(markers);
  7658. });
  7659. return new SharedTextMarker(markers, primary);
  7660. }
  7661. function findSharedMarkers(doc) {
  7662. return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())),
  7663. function(m) { return m.parent; });
  7664. }
  7665. function copySharedMarkers(doc, markers) {
  7666. for (var i = 0; i < markers.length; i++) {
  7667. var marker = markers[i], pos = marker.find();
  7668. var mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to);
  7669. if (cmp(mFrom, mTo)) {
  7670. var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type);
  7671. marker.markers.push(subMark);
  7672. subMark.parent = marker;
  7673. }
  7674. }
  7675. }
  7676. function detachSharedMarkers(markers) {
  7677. for (var i = 0; i < markers.length; i++) {
  7678. var marker = markers[i], linked = [marker.primary.doc];;
  7679. linkedDocs(marker.primary.doc, function(d) { linked.push(d); });
  7680. for (var j = 0; j < marker.markers.length; j++) {
  7681. var subMarker = marker.markers[j];
  7682. if (indexOf(linked, subMarker.doc) == -1) {
  7683. subMarker.parent = null;
  7684. marker.markers.splice(j--, 1);
  7685. }
  7686. }
  7687. }
  7688. }
  7689. // TEXTMARKER SPANS
  7690. function MarkedSpan(marker, from, to) {
  7691. this.marker = marker;
  7692. this.from = from; this.to = to;
  7693. }
  7694. // Search an array of spans for a span matching the given marker.
  7695. function getMarkedSpanFor(spans, marker) {
  7696. if (spans) for (var i = 0; i < spans.length; ++i) {
  7697. var span = spans[i];
  7698. if (span.marker == marker) return span;
  7699. }
  7700. }
  7701. // Remove a span from an array, returning undefined if no spans are
  7702. // left (we don't store arrays for lines without spans).
  7703. function removeMarkedSpan(spans, span) {
  7704. for (var r, i = 0; i < spans.length; ++i)
  7705. if (spans[i] != span) (r || (r = [])).push(spans[i]);
  7706. return r;
  7707. }
  7708. // Add a span to a line.
  7709. function addMarkedSpan(line, span) {
  7710. line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span];
  7711. span.marker.attachLine(line);
  7712. }
  7713. // Used for the algorithm that adjusts markers for a change in the
  7714. // document. These functions cut an array of spans at a given
  7715. // character position, returning an array of remaining chunks (or
  7716. // undefined if nothing remains).
  7717. function markedSpansBefore(old, startCh, isInsert) {
  7718. if (old) for (var i = 0, nw; i < old.length; ++i) {
  7719. var span = old[i], marker = span.marker;
  7720. var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh);
  7721. if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) {
  7722. var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh);
  7723. (nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to));
  7724. }
  7725. }
  7726. return nw;
  7727. }
  7728. function markedSpansAfter(old, endCh, isInsert) {
  7729. if (old) for (var i = 0, nw; i < old.length; ++i) {
  7730. var span = old[i], marker = span.marker;
  7731. var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh);
  7732. if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) {
  7733. var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh);
  7734. (nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh,
  7735. span.to == null ? null : span.to - endCh));
  7736. }
  7737. }
  7738. return nw;
  7739. }
  7740. // Given a change object, compute the new set of marker spans that
  7741. // cover the line in which the change took place. Removes spans
  7742. // entirely within the change, reconnects spans belonging to the
  7743. // same marker that appear on both sides of the change, and cuts off
  7744. // spans partially within the change. Returns an array of span
  7745. // arrays with one element for each line in (after) the change.
  7746. function stretchSpansOverChange(doc, change) {
  7747. if (change.full) return null;
  7748. var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans;
  7749. var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans;
  7750. if (!oldFirst && !oldLast) return null;
  7751. var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0;
  7752. // Get the spans that 'stick out' on both sides
  7753. var first = markedSpansBefore(oldFirst, startCh, isInsert);
  7754. var last = markedSpansAfter(oldLast, endCh, isInsert);
  7755. // Next, merge those two ends
  7756. var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0);
  7757. if (first) {
  7758. // Fix up .to properties of first
  7759. for (var i = 0; i < first.length; ++i) {
  7760. var span = first[i];
  7761. if (span.to == null) {
  7762. var found = getMarkedSpanFor(last, span.marker);
  7763. if (!found) span.to = startCh;
  7764. else if (sameLine) span.to = found.to == null ? null : found.to + offset;
  7765. }
  7766. }
  7767. }
  7768. if (last) {
  7769. // Fix up .from in last (or move them into first in case of sameLine)
  7770. for (var i = 0; i < last.length; ++i) {
  7771. var span = last[i];
  7772. if (span.to != null) span.to += offset;
  7773. if (span.from == null) {
  7774. var found = getMarkedSpanFor(first, span.marker);
  7775. if (!found) {
  7776. span.from = offset;
  7777. if (sameLine) (first || (first = [])).push(span);
  7778. }
  7779. } else {
  7780. span.from += offset;
  7781. if (sameLine) (first || (first = [])).push(span);
  7782. }
  7783. }
  7784. }
  7785. // Make sure we didn't create any zero-length spans
  7786. if (first) first = clearEmptySpans(first);
  7787. if (last && last != first) last = clearEmptySpans(last);
  7788. var newMarkers = [first];
  7789. if (!sameLine) {
  7790. // Fill gap with whole-line-spans
  7791. var gap = change.text.length - 2, gapMarkers;
  7792. if (gap > 0 && first)
  7793. for (var i = 0; i < first.length; ++i)
  7794. if (first[i].to == null)
  7795. (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i].marker, null, null));
  7796. for (var i = 0; i < gap; ++i)
  7797. newMarkers.push(gapMarkers);
  7798. newMarkers.push(last);
  7799. }
  7800. return newMarkers;
  7801. }
  7802. // Remove spans that are empty and don't have a clearWhenEmpty
  7803. // option of false.
  7804. function clearEmptySpans(spans) {
  7805. for (var i = 0; i < spans.length; ++i) {
  7806. var span = spans[i];
  7807. if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false)
  7808. spans.splice(i--, 1);
  7809. }
  7810. if (!spans.length) return null;
  7811. return spans;
  7812. }
  7813. // Used for un/re-doing changes from the history. Combines the
  7814. // result of computing the existing spans with the set of spans that
  7815. // existed in the history (so that deleting around a span and then
  7816. // undoing brings back the span).
  7817. function mergeOldSpans(doc, change) {
  7818. var old = getOldSpans(doc, change);
  7819. var stretched = stretchSpansOverChange(doc, change);
  7820. if (!old) return stretched;
  7821. if (!stretched) return old;
  7822. for (var i = 0; i < old.length; ++i) {
  7823. var oldCur = old[i], stretchCur = stretched[i];
  7824. if (oldCur && stretchCur) {
  7825. spans: for (var j = 0; j < stretchCur.length; ++j) {
  7826. var span = stretchCur[j];
  7827. for (var k = 0; k < oldCur.length; ++k)
  7828. if (oldCur[k].marker == span.marker) continue spans;
  7829. oldCur.push(span);
  7830. }
  7831. } else if (stretchCur) {
  7832. old[i] = stretchCur;
  7833. }
  7834. }
  7835. return old;
  7836. }
  7837. // Used to 'clip' out readOnly ranges when making a change.
  7838. function removeReadOnlyRanges(doc, from, to) {
  7839. var markers = null;
  7840. doc.iter(from.line, to.line + 1, function(line) {
  7841. if (line.markedSpans) for (var i = 0; i < line.markedSpans.length; ++i) {
  7842. var mark = line.markedSpans[i].marker;
  7843. if (mark.readOnly && (!markers || indexOf(markers, mark) == -1))
  7844. (markers || (markers = [])).push(mark);
  7845. }
  7846. });
  7847. if (!markers) return null;
  7848. var parts = [{from: from, to: to}];
  7849. for (var i = 0; i < markers.length; ++i) {
  7850. var mk = markers[i], m = mk.find(0);
  7851. for (var j = 0; j < parts.length; ++j) {
  7852. var p = parts[j];
  7853. if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) continue;
  7854. var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to);
  7855. if (dfrom < 0 || !mk.inclusiveLeft && !dfrom)
  7856. newParts.push({from: p.from, to: m.from});
  7857. if (dto > 0 || !mk.inclusiveRight && !dto)
  7858. newParts.push({from: m.to, to: p.to});
  7859. parts.splice.apply(parts, newParts);
  7860. j += newParts.length - 1;
  7861. }
  7862. }
  7863. return parts;
  7864. }
  7865. // Connect or disconnect spans from a line.
  7866. function detachMarkedSpans(line) {
  7867. var spans = line.markedSpans;
  7868. if (!spans) return;
  7869. for (var i = 0; i < spans.length; ++i)
  7870. spans[i].marker.detachLine(line);
  7871. line.markedSpans = null;
  7872. }
  7873. function attachMarkedSpans(line, spans) {
  7874. if (!spans) return;
  7875. for (var i = 0; i < spans.length; ++i)
  7876. spans[i].marker.attachLine(line);
  7877. line.markedSpans = spans;
  7878. }
  7879. // Helpers used when computing which overlapping collapsed span
  7880. // counts as the larger one.
  7881. function extraLeft(marker) { return marker.inclusiveLeft ? -1 : 0; }
  7882. function extraRight(marker) { return marker.inclusiveRight ? 1 : 0; }
  7883. // Returns a number indicating which of two overlapping collapsed
  7884. // spans is larger (and thus includes the other). Falls back to
  7885. // comparing ids when the spans cover exactly the same range.
  7886. function compareCollapsedMarkers(a, b) {
  7887. var lenDiff = a.lines.length - b.lines.length;
  7888. if (lenDiff != 0) return lenDiff;
  7889. var aPos = a.find(), bPos = b.find();
  7890. var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b);
  7891. if (fromCmp) return -fromCmp;
  7892. var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b);
  7893. if (toCmp) return toCmp;
  7894. return b.id - a.id;
  7895. }
  7896. // Find out whether a line ends or starts in a collapsed span. If
  7897. // so, return the marker for that span.
  7898. function collapsedSpanAtSide(line, start) {
  7899. var sps = sawCollapsedSpans && line.markedSpans, found;
  7900. if (sps) for (var sp, i = 0; i < sps.length; ++i) {
  7901. sp = sps[i];
  7902. if (sp.marker.collapsed && (start ? sp.from : sp.to) == null &&
  7903. (!found || compareCollapsedMarkers(found, sp.marker) < 0))
  7904. found = sp.marker;
  7905. }
  7906. return found;
  7907. }
  7908. function collapsedSpanAtStart(line) { return collapsedSpanAtSide(line, true); }
  7909. function collapsedSpanAtEnd(line) { return collapsedSpanAtSide(line, false); }
  7910. // Test whether there exists a collapsed span that partially
  7911. // overlaps (covers the start or end, but not both) of a new span.
  7912. // Such overlap is not allowed.
  7913. function conflictingCollapsedRange(doc, lineNo, from, to, marker) {
  7914. var line = getLine(doc, lineNo);
  7915. var sps = sawCollapsedSpans && line.markedSpans;
  7916. if (sps) for (var i = 0; i < sps.length; ++i) {
  7917. var sp = sps[i];
  7918. if (!sp.marker.collapsed) continue;
  7919. var found = sp.marker.find(0);
  7920. var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker);
  7921. var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker);
  7922. if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) continue;
  7923. if (fromCmp <= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.to, from) >= 0 : cmp(found.to, from) > 0) ||
  7924. fromCmp >= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.from, to) <= 0 : cmp(found.from, to) < 0))
  7925. return true;
  7926. }
  7927. }
  7928. // A visual line is a line as drawn on the screen. Folding, for
  7929. // example, can cause multiple logical lines to appear on the same
  7930. // visual line. This finds the start of the visual line that the
  7931. // given line is part of (usually that is the line itself).
  7932. function visualLine(line) {
  7933. var merged;
  7934. while (merged = collapsedSpanAtStart(line))
  7935. line = merged.find(-1, true).line;
  7936. return line;
  7937. }
  7938. // Returns an array of logical lines that continue the visual line
  7939. // started by the argument, or undefined if there are no such lines.
  7940. function visualLineContinued(line) {
  7941. var merged, lines;
  7942. while (merged = collapsedSpanAtEnd(line)) {
  7943. line = merged.find(1, true).line;
  7944. (lines || (lines = [])).push(line);
  7945. }
  7946. return lines;
  7947. }
  7948. // Get the line number of the start of the visual line that the
  7949. // given line number is part of.
  7950. function visualLineNo(doc, lineN) {
  7951. var line = getLine(doc, lineN), vis = visualLine(line);
  7952. if (line == vis) return lineN;
  7953. return lineNo(vis);
  7954. }
  7955. // Get the line number of the start of the next visual line after
  7956. // the given line.
  7957. function visualLineEndNo(doc, lineN) {
  7958. if (lineN > doc.lastLine()) return lineN;
  7959. var line = getLine(doc, lineN), merged;
  7960. if (!lineIsHidden(doc, line)) return lineN;
  7961. while (merged = collapsedSpanAtEnd(line))
  7962. line = merged.find(1, true).line;
  7963. return lineNo(line) + 1;
  7964. }
  7965. // Compute whether a line is hidden. Lines count as hidden when they
  7966. // are part of a visual line that starts with another line, or when
  7967. // they are entirely covered by collapsed, non-widget span.
  7968. function lineIsHidden(doc, line) {
  7969. var sps = sawCollapsedSpans && line.markedSpans;
  7970. if (sps) for (var sp, i = 0; i < sps.length; ++i) {
  7971. sp = sps[i];
  7972. if (!sp.marker.collapsed) continue;
  7973. if (sp.from == null) return true;
  7974. if (sp.marker.widgetNode) continue;
  7975. if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp))
  7976. return true;
  7977. }
  7978. }
  7979. function lineIsHiddenInner(doc, line, span) {
  7980. if (span.to == null) {
  7981. var end = span.marker.find(1, true);
  7982. return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker));
  7983. }
  7984. if (span.marker.inclusiveRight && span.to == line.text.length)
  7985. return true;
  7986. for (var sp, i = 0; i < line.markedSpans.length; ++i) {
  7987. sp = line.markedSpans[i];
  7988. if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to &&
  7989. (sp.to == null || sp.to != span.from) &&
  7990. (sp.marker.inclusiveLeft || span.marker.inclusiveRight) &&
  7991. lineIsHiddenInner(doc, line, sp)) return true;
  7992. }
  7993. }
  7994. // LINE WIDGETS
  7995. // Line widgets are block elements displayed above or below a line.
  7996. var LineWidget = CodeMirror.LineWidget = function(doc, node, options) {
  7997. if (options) for (var opt in options) if (options.hasOwnProperty(opt))
  7998. this[opt] = options[opt];
  7999. this.doc = doc;
  8000. this.node = node;
  8001. };
  8002. eventMixin(LineWidget);
  8003. function adjustScrollWhenAboveVisible(cm, line, diff) {
  8004. if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop))
  8005. addToScrollPos(cm, null, diff);
  8006. }
  8007. LineWidget.prototype.clear = function() {
  8008. var cm = this.doc.cm, ws = this.line.widgets, line = this.line, no = lineNo(line);
  8009. if (no == null || !ws) return;
  8010. for (var i = 0; i < ws.length; ++i) if (ws[i] == this) ws.splice(i--, 1);
  8011. if (!ws.length) line.widgets = null;
  8012. var height = widgetHeight(this);
  8013. updateLineHeight(line, Math.max(0, line.height - height));
  8014. if (cm) runInOp(cm, function() {
  8015. adjustScrollWhenAboveVisible(cm, line, -height);
  8016. regLineChange(cm, no, "widget");
  8017. });
  8018. };
  8019. LineWidget.prototype.changed = function() {
  8020. var oldH = this.height, cm = this.doc.cm, line = this.line;
  8021. this.height = null;
  8022. var diff = widgetHeight(this) - oldH;
  8023. if (!diff) return;
  8024. updateLineHeight(line, line.height + diff);
  8025. if (cm) runInOp(cm, function() {
  8026. cm.curOp.forceUpdate = true;
  8027. adjustScrollWhenAboveVisible(cm, line, diff);
  8028. });
  8029. };
  8030. function widgetHeight(widget) {
  8031. if (widget.height != null) return widget.height;
  8032. var cm = widget.doc.cm;
  8033. if (!cm) return 0;
  8034. if (!contains(document.body, widget.node)) {
  8035. var parentStyle = "position: relative;";
  8036. if (widget.coverGutter)
  8037. parentStyle += "margin-left: -" + cm.display.gutters.offsetWidth + "px;";
  8038. if (widget.noHScroll)
  8039. parentStyle += "width: " + cm.display.wrapper.clientWidth + "px;";
  8040. removeChildrenAndAdd(cm.display.measure, elt("div", [widget.node], null, parentStyle));
  8041. }
  8042. return widget.height = widget.node.parentNode.offsetHeight;
  8043. }
  8044. function addLineWidget(doc, handle, node, options) {
  8045. var widget = new LineWidget(doc, node, options);
  8046. var cm = doc.cm;
  8047. if (cm && widget.noHScroll) cm.display.alignWidgets = true;
  8048. changeLine(doc, handle, "widget", function(line) {
  8049. var widgets = line.widgets || (line.widgets = []);
  8050. if (widget.insertAt == null) widgets.push(widget);
  8051. else widgets.splice(Math.min(widgets.length - 1, Math.max(0, widget.insertAt)), 0, widget);
  8052. widget.line = line;
  8053. if (cm && !lineIsHidden(doc, line)) {
  8054. var aboveVisible = heightAtLine(line) < doc.scrollTop;
  8055. updateLineHeight(line, line.height + widgetHeight(widget));
  8056. if (aboveVisible) addToScrollPos(cm, null, widget.height);
  8057. cm.curOp.forceUpdate = true;
  8058. }
  8059. return true;
  8060. });
  8061. return widget;
  8062. }
  8063. // LINE DATA STRUCTURE
  8064. // Line objects. These hold state related to a line, including
  8065. // highlighting info (the styles array).
  8066. var Line = CodeMirror.Line = function(text, markedSpans, estimateHeight) {
  8067. this.text = text;
  8068. attachMarkedSpans(this, markedSpans);
  8069. this.height = estimateHeight ? estimateHeight(this) : 1;
  8070. };
  8071. eventMixin(Line);
  8072. Line.prototype.lineNo = function() { return lineNo(this); };
  8073. // Change the content (text, markers) of a line. Automatically
  8074. // invalidates cached information and tries to re-estimate the
  8075. // line's height.
  8076. function updateLine(line, text, markedSpans, estimateHeight) {
  8077. line.text = text;
  8078. if (line.stateAfter) line.stateAfter = null;
  8079. if (line.styles) line.styles = null;
  8080. if (line.order != null) line.order = null;
  8081. detachMarkedSpans(line);
  8082. attachMarkedSpans(line, markedSpans);
  8083. var estHeight = estimateHeight ? estimateHeight(line) : 1;
  8084. if (estHeight != line.height) updateLineHeight(line, estHeight);
  8085. }
  8086. // Detach a line from the document tree and its markers.
  8087. function cleanUpLine(line) {
  8088. line.parent = null;
  8089. detachMarkedSpans(line);
  8090. }
  8091. function extractLineClasses(type, output) {
  8092. if (type) for (;;) {
  8093. var lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/);
  8094. if (!lineClass) break;
  8095. type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length);
  8096. var prop = lineClass[1] ? "bgClass" : "textClass";
  8097. if (output[prop] == null)
  8098. output[prop] = lineClass[2];
  8099. else if (!(new RegExp("(?:^|\s)" + lineClass[2] + "(?:$|\s)")).test(output[prop]))
  8100. output[prop] += " " + lineClass[2];
  8101. }
  8102. return type;
  8103. }
  8104. function callBlankLine(mode, state) {
  8105. if (mode.blankLine) return mode.blankLine(state);
  8106. if (!mode.innerMode) return;
  8107. var inner = CodeMirror.innerMode(mode, state);
  8108. if (inner.mode.blankLine) return inner.mode.blankLine(inner.state);
  8109. }
  8110. function readToken(mode, stream, state, inner) {
  8111. for (var i = 0; i < 10; i++) {
  8112. if (inner) inner[0] = CodeMirror.innerMode(mode, state).mode;
  8113. var style = mode.token(stream, state);
  8114. if (stream.pos > stream.start) return style;
  8115. }
  8116. throw new Error("Mode " + mode.name + " failed to advance stream.");
  8117. }
  8118. // Utility for getTokenAt and getLineTokens
  8119. function takeToken(cm, pos, precise, asArray) {
  8120. function getObj(copy) {
  8121. return {start: stream.start, end: stream.pos,
  8122. string: stream.current(),
  8123. type: style || null,
  8124. state: copy ? copyState(doc.mode, state) : state};
  8125. }
  8126. var doc = cm.doc, mode = doc.mode, style;
  8127. pos = clipPos(doc, pos);
  8128. var line = getLine(doc, pos.line), state = getStateBefore(cm, pos.line, precise);
  8129. var stream = new StringStream(line.text, cm.options.tabSize), tokens;
  8130. if (asArray) tokens = [];
  8131. while ((asArray || stream.pos < pos.ch) && !stream.eol()) {
  8132. stream.start = stream.pos;
  8133. style = readToken(mode, stream, state);
  8134. if (asArray) tokens.push(getObj(true));
  8135. }
  8136. return asArray ? tokens : getObj();
  8137. }
  8138. // Run the given mode's parser over a line, calling f for each token.
  8139. function runMode(cm, text, mode, state, f, lineClasses, forceToEnd) {
  8140. var flattenSpans = mode.flattenSpans;
  8141. if (flattenSpans == null) flattenSpans = cm.options.flattenSpans;
  8142. var curStart = 0, curStyle = null;
  8143. var stream = new StringStream(text, cm.options.tabSize), style;
  8144. var inner = cm.options.addModeClass && [null];
  8145. if (text == "") extractLineClasses(callBlankLine(mode, state), lineClasses);
  8146. while (!stream.eol()) {
  8147. if (stream.pos > cm.options.maxHighlightLength) {
  8148. flattenSpans = false;
  8149. if (forceToEnd) processLine(cm, text, state, stream.pos);
  8150. stream.pos = text.length;
  8151. style = null;
  8152. } else {
  8153. style = extractLineClasses(readToken(mode, stream, state, inner), lineClasses);
  8154. }
  8155. if (inner) {
  8156. var mName = inner[0].name;
  8157. if (mName) style = "m-" + (style ? mName + " " + style : mName);
  8158. }
  8159. if (!flattenSpans || curStyle != style) {
  8160. while (curStart < stream.start) {
  8161. curStart = Math.min(stream.start, curStart + 50000);
  8162. f(curStart, curStyle);
  8163. }
  8164. curStyle = style;
  8165. }
  8166. stream.start = stream.pos;
  8167. }
  8168. while (curStart < stream.pos) {
  8169. // Webkit seems to refuse to render text nodes longer than 57444 characters
  8170. var pos = Math.min(stream.pos, curStart + 50000);
  8171. f(pos, curStyle);
  8172. curStart = pos;
  8173. }
  8174. }
  8175. // Compute a style array (an array starting with a mode generation
  8176. // -- for invalidation -- followed by pairs of end positions and
  8177. // style strings), which is used to highlight the tokens on the
  8178. // line.
  8179. function highlightLine(cm, line, state, forceToEnd) {
  8180. // A styles array always starts with a number identifying the
  8181. // mode/overlays that it is based on (for easy invalidation).
  8182. var st = [cm.state.modeGen], lineClasses = {};
  8183. // Compute the base array of styles
  8184. runMode(cm, line.text, cm.doc.mode, state, function(end, style) {
  8185. st.push(end, style);
  8186. }, lineClasses, forceToEnd);
  8187. // Run overlays, adjust style array.
  8188. for (var o = 0; o < cm.state.overlays.length; ++o) {
  8189. var overlay = cm.state.overlays[o], i = 1, at = 0;
  8190. runMode(cm, line.text, overlay.mode, true, function(end, style) {
  8191. var start = i;
  8192. // Ensure there's a token end at the current position, and that i points at it
  8193. while (at < end) {
  8194. var i_end = st[i];
  8195. if (i_end > end)
  8196. st.splice(i, 1, end, st[i+1], i_end);
  8197. i += 2;
  8198. at = Math.min(end, i_end);
  8199. }
  8200. if (!style) return;
  8201. if (overlay.opaque) {
  8202. st.splice(start, i - start, end, "cm-overlay " + style);
  8203. i = start + 2;
  8204. } else {
  8205. for (; start < i; start += 2) {
  8206. var cur = st[start+1];
  8207. st[start+1] = (cur ? cur + " " : "") + "cm-overlay " + style;
  8208. }
  8209. }
  8210. }, lineClasses);
  8211. }
  8212. return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null};
  8213. }
  8214. function getLineStyles(cm, line, updateFrontier) {
  8215. if (!line.styles || line.styles[0] != cm.state.modeGen) {
  8216. var state = getStateBefore(cm, lineNo(line));
  8217. var result = highlightLine(cm, line, line.text.length > cm.options.maxHighlightLength ? copyState(cm.doc.mode, state) : state);
  8218. line.stateAfter = state;
  8219. line.styles = result.styles;
  8220. if (result.classes) line.styleClasses = result.classes;
  8221. else if (line.styleClasses) line.styleClasses = null;
  8222. if (updateFrontier === cm.doc.frontier) cm.doc.frontier++;
  8223. }
  8224. return line.styles;
  8225. }
  8226. // Lightweight form of highlight -- proceed over this line and
  8227. // update state, but don't save a style array. Used for lines that
  8228. // aren't currently visible.
  8229. function processLine(cm, text, state, startAt) {
  8230. var mode = cm.doc.mode;
  8231. var stream = new StringStream(text, cm.options.tabSize);
  8232. stream.start = stream.pos = startAt || 0;
  8233. if (text == "") callBlankLine(mode, state);
  8234. while (!stream.eol()) {
  8235. readToken(mode, stream, state);
  8236. stream.start = stream.pos;
  8237. }
  8238. }
  8239. // Convert a style as returned by a mode (either null, or a string
  8240. // containing one or more styles) to a CSS style. This is cached,
  8241. // and also looks for line-wide styles.
  8242. var styleToClassCache = {}, styleToClassCacheWithMode = {};
  8243. function interpretTokenStyle(style, options) {
  8244. if (!style || /^\s*$/.test(style)) return null;
  8245. var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache;
  8246. return cache[style] ||
  8247. (cache[style] = style.replace(/\S+/g, "cm-$&"));
  8248. }
  8249. // Render the DOM representation of the text of a line. Also builds
  8250. // up a 'line map', which points at the DOM nodes that represent
  8251. // specific stretches of text, and is used by the measuring code.
  8252. // The returned object contains the DOM node, this map, and
  8253. // information about line-wide styles that were set by the mode.
  8254. function buildLineContent(cm, lineView) {
  8255. // The padding-right forces the element to have a 'border', which
  8256. // is needed on Webkit to be able to get line-level bounding
  8257. // rectangles for it (in measureChar).
  8258. var content = elt("span", null, null, webkit ? "padding-right: .1px" : null);
  8259. var builder = {pre: elt("pre", [content], "CodeMirror-line"), content: content,
  8260. col: 0, pos: 0, cm: cm,
  8261. trailingSpace: false,
  8262. splitSpaces: (ie || webkit) && cm.getOption("lineWrapping")};
  8263. lineView.measure = {};
  8264. // Iterate over the logical lines that make up this visual line.
  8265. for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) {
  8266. var line = i ? lineView.rest[i - 1] : lineView.line, order;
  8267. builder.pos = 0;
  8268. builder.addToken = buildToken;
  8269. // Optionally wire in some hacks into the token-rendering
  8270. // algorithm, to deal with browser quirks.
  8271. if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line)))
  8272. builder.addToken = buildTokenBadBidi(builder.addToken, order);
  8273. builder.map = [];
  8274. var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line);
  8275. insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate));
  8276. if (line.styleClasses) {
  8277. if (line.styleClasses.bgClass)
  8278. builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || "");
  8279. if (line.styleClasses.textClass)
  8280. builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || "");
  8281. }
  8282. // Ensure at least a single node is present, for measuring.
  8283. if (builder.map.length == 0)
  8284. builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure)));
  8285. // Store the map and a cache object for the current logical line
  8286. if (i == 0) {
  8287. lineView.measure.map = builder.map;
  8288. lineView.measure.cache = {};
  8289. } else {
  8290. (lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map);
  8291. (lineView.measure.caches || (lineView.measure.caches = [])).push({});
  8292. }
  8293. }
  8294. // See issue #2901
  8295. if (webkit) {
  8296. var last = builder.content.lastChild
  8297. if (/\bcm-tab\b/.test(last.className) || (last.querySelector && last.querySelector(".cm-tab")))
  8298. builder.content.className = "cm-tab-wrap-hack";
  8299. }
  8300. signal(cm, "renderLine", cm, lineView.line, builder.pre);
  8301. if (builder.pre.className)
  8302. builder.textClass = joinClasses(builder.pre.className, builder.textClass || "");
  8303. return builder;
  8304. }
  8305. function defaultSpecialCharPlaceholder(ch) {
  8306. var token = elt("span", "\u2022", "cm-invalidchar");
  8307. token.title = "\\u" + ch.charCodeAt(0).toString(16);
  8308. token.setAttribute("aria-label", token.title);
  8309. return token;
  8310. }
  8311. // Build up the DOM representation for a single token, and add it to
  8312. // the line map. Takes care to render special characters separately.
  8313. function buildToken(builder, text, style, startStyle, endStyle, title, css) {
  8314. if (!text) return;
  8315. var displayText = builder.splitSpaces ? splitSpaces(text, builder.trailingSpace) : text
  8316. var special = builder.cm.state.specialChars, mustWrap = false;
  8317. if (!special.test(text)) {
  8318. builder.col += text.length;
  8319. var content = document.createTextNode(displayText);
  8320. builder.map.push(builder.pos, builder.pos + text.length, content);
  8321. if (ie && ie_version < 9) mustWrap = true;
  8322. builder.pos += text.length;
  8323. } else {
  8324. var content = document.createDocumentFragment(), pos = 0;
  8325. while (true) {
  8326. special.lastIndex = pos;
  8327. var m = special.exec(text);
  8328. var skipped = m ? m.index - pos : text.length - pos;
  8329. if (skipped) {
  8330. var txt = document.createTextNode(displayText.slice(pos, pos + skipped));
  8331. if (ie && ie_version < 9) content.appendChild(elt("span", [txt]));
  8332. else content.appendChild(txt);
  8333. builder.map.push(builder.pos, builder.pos + skipped, txt);
  8334. builder.col += skipped;
  8335. builder.pos += skipped;
  8336. }
  8337. if (!m) break;
  8338. pos += skipped + 1;
  8339. if (m[0] == "\t") {
  8340. var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize;
  8341. var txt = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab"));
  8342. txt.setAttribute("role", "presentation");
  8343. txt.setAttribute("cm-text", "\t");
  8344. builder.col += tabWidth;
  8345. } else if (m[0] == "\r" || m[0] == "\n") {
  8346. var txt = content.appendChild(elt("span", m[0] == "\r" ? "\u240d" : "\u2424", "cm-invalidchar"));
  8347. txt.setAttribute("cm-text", m[0]);
  8348. builder.col += 1;
  8349. } else {
  8350. var txt = builder.cm.options.specialCharPlaceholder(m[0]);
  8351. txt.setAttribute("cm-text", m[0]);
  8352. if (ie && ie_version < 9) content.appendChild(elt("span", [txt]));
  8353. else content.appendChild(txt);
  8354. builder.col += 1;
  8355. }
  8356. builder.map.push(builder.pos, builder.pos + 1, txt);
  8357. builder.pos++;
  8358. }
  8359. }
  8360. builder.trailingSpace = displayText.charCodeAt(text.length - 1) == 32
  8361. if (style || startStyle || endStyle || mustWrap || css) {
  8362. var fullStyle = style || "";
  8363. if (startStyle) fullStyle += startStyle;
  8364. if (endStyle) fullStyle += endStyle;
  8365. var token = elt("span", [content], fullStyle, css);
  8366. if (title) token.title = title;
  8367. return builder.content.appendChild(token);
  8368. }
  8369. builder.content.appendChild(content);
  8370. }
  8371. function splitSpaces(text, trailingBefore) {
  8372. if (text.length > 1 && !/ /.test(text)) return text
  8373. var spaceBefore = trailingBefore, result = ""
  8374. for (var i = 0; i < text.length; i++) {
  8375. var ch = text.charAt(i)
  8376. if (ch == " " && spaceBefore && (i == text.length - 1 || text.charCodeAt(i + 1) == 32))
  8377. ch = "\u00a0"
  8378. result += ch
  8379. spaceBefore = ch == " "
  8380. }
  8381. return result
  8382. }
  8383. // Work around nonsense dimensions being reported for stretches of
  8384. // right-to-left text.
  8385. function buildTokenBadBidi(inner, order) {
  8386. return function(builder, text, style, startStyle, endStyle, title, css) {
  8387. style = style ? style + " cm-force-border" : "cm-force-border";
  8388. var start = builder.pos, end = start + text.length;
  8389. for (;;) {
  8390. // Find the part that overlaps with the start of this text
  8391. for (var i = 0; i < order.length; i++) {
  8392. var part = order[i];
  8393. if (part.to > start && part.from <= start) break;
  8394. }
  8395. if (part.to >= end) return inner(builder, text, style, startStyle, endStyle, title, css);
  8396. inner(builder, text.slice(0, part.to - start), style, startStyle, null, title, css);
  8397. startStyle = null;
  8398. text = text.slice(part.to - start);
  8399. start = part.to;
  8400. }
  8401. };
  8402. }
  8403. function buildCollapsedSpan(builder, size, marker, ignoreWidget) {
  8404. var widget = !ignoreWidget && marker.widgetNode;
  8405. if (widget) builder.map.push(builder.pos, builder.pos + size, widget);
  8406. if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) {
  8407. if (!widget)
  8408. widget = builder.content.appendChild(document.createElement("span"));
  8409. widget.setAttribute("cm-marker", marker.id);
  8410. }
  8411. if (widget) {
  8412. builder.cm.display.input.setUneditable(widget);
  8413. builder.content.appendChild(widget);
  8414. }
  8415. builder.pos += size;
  8416. builder.trailingSpace = false
  8417. }
  8418. // Outputs a number of spans to make up a line, taking highlighting
  8419. // and marked text into account.
  8420. function insertLineContent(line, builder, styles) {
  8421. var spans = line.markedSpans, allText = line.text, at = 0;
  8422. if (!spans) {
  8423. for (var i = 1; i < styles.length; i+=2)
  8424. builder.addToken(builder, allText.slice(at, at = styles[i]), interpretTokenStyle(styles[i+1], builder.cm.options));
  8425. return;
  8426. }
  8427. var len = allText.length, pos = 0, i = 1, text = "", style, css;
  8428. var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, title, collapsed;
  8429. for (;;) {
  8430. if (nextChange == pos) { // Update current marker set
  8431. spanStyle = spanEndStyle = spanStartStyle = title = css = "";
  8432. collapsed = null; nextChange = Infinity;
  8433. var foundBookmarks = [], endStyles
  8434. for (var j = 0; j < spans.length; ++j) {
  8435. var sp = spans[j], m = sp.marker;
  8436. if (m.type == "bookmark" && sp.from == pos && m.widgetNode) {
  8437. foundBookmarks.push(m);
  8438. } else if (sp.from <= pos && (sp.to == null || sp.to > pos || m.collapsed && sp.to == pos && sp.from == pos)) {
  8439. if (sp.to != null && sp.to != pos && nextChange > sp.to) {
  8440. nextChange = sp.to;
  8441. spanEndStyle = "";
  8442. }
  8443. if (m.className) spanStyle += " " + m.className;
  8444. if (m.css) css = (css ? css + ";" : "") + m.css;
  8445. if (m.startStyle && sp.from == pos) spanStartStyle += " " + m.startStyle;
  8446. if (m.endStyle && sp.to == nextChange) (endStyles || (endStyles = [])).push(m.endStyle, sp.to)
  8447. if (m.title && !title) title = m.title;
  8448. if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0))
  8449. collapsed = sp;
  8450. } else if (sp.from > pos && nextChange > sp.from) {
  8451. nextChange = sp.from;
  8452. }
  8453. }
  8454. if (endStyles) for (var j = 0; j < endStyles.length; j += 2)
  8455. if (endStyles[j + 1] == nextChange) spanEndStyle += " " + endStyles[j]
  8456. if (!collapsed || collapsed.from == pos) for (var j = 0; j < foundBookmarks.length; ++j)
  8457. buildCollapsedSpan(builder, 0, foundBookmarks[j]);
  8458. if (collapsed && (collapsed.from || 0) == pos) {
  8459. buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos,
  8460. collapsed.marker, collapsed.from == null);
  8461. if (collapsed.to == null) return;
  8462. if (collapsed.to == pos) collapsed = false;
  8463. }
  8464. }
  8465. if (pos >= len) break;
  8466. var upto = Math.min(len, nextChange);
  8467. while (true) {
  8468. if (text) {
  8469. var end = pos + text.length;
  8470. if (!collapsed) {
  8471. var tokenText = end > upto ? text.slice(0, upto - pos) : text;
  8472. builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle,
  8473. spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", title, css);
  8474. }
  8475. if (end >= upto) {text = text.slice(upto - pos); pos = upto; break;}
  8476. pos = end;
  8477. spanStartStyle = "";
  8478. }
  8479. text = allText.slice(at, at = styles[i++]);
  8480. style = interpretTokenStyle(styles[i++], builder.cm.options);
  8481. }
  8482. }
  8483. }
  8484. // DOCUMENT DATA STRUCTURE
  8485. // By default, updates that start and end at the beginning of a line
  8486. // are treated specially, in order to make the association of line
  8487. // widgets and marker elements with the text behave more intuitive.
  8488. function isWholeLineUpdate(doc, change) {
  8489. return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" &&
  8490. (!doc.cm || doc.cm.options.wholeLineUpdateBefore);
  8491. }
  8492. // Perform a change on the document data structure.
  8493. function updateDoc(doc, change, markedSpans, estimateHeight) {
  8494. function spansFor(n) {return markedSpans ? markedSpans[n] : null;}
  8495. function update(line, text, spans) {
  8496. updateLine(line, text, spans, estimateHeight);
  8497. signalLater(line, "change", line, change);
  8498. }
  8499. function linesFor(start, end) {
  8500. for (var i = start, result = []; i < end; ++i)
  8501. result.push(new Line(text[i], spansFor(i), estimateHeight));
  8502. return result;
  8503. }
  8504. var from = change.from, to = change.to, text = change.text;
  8505. var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line);
  8506. var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line;
  8507. // Adjust the line structure
  8508. if (change.full) {
  8509. doc.insert(0, linesFor(0, text.length));
  8510. doc.remove(text.length, doc.size - text.length);
  8511. } else if (isWholeLineUpdate(doc, change)) {
  8512. // This is a whole-line replace. Treated specially to make
  8513. // sure line objects move the way they are supposed to.
  8514. var added = linesFor(0, text.length - 1);
  8515. update(lastLine, lastLine.text, lastSpans);
  8516. if (nlines) doc.remove(from.line, nlines);
  8517. if (added.length) doc.insert(from.line, added);
  8518. } else if (firstLine == lastLine) {
  8519. if (text.length == 1) {
  8520. update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans);
  8521. } else {
  8522. var added = linesFor(1, text.length - 1);
  8523. added.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight));
  8524. update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
  8525. doc.insert(from.line + 1, added);
  8526. }
  8527. } else if (text.length == 1) {
  8528. update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0));
  8529. doc.remove(from.line + 1, nlines);
  8530. } else {
  8531. update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
  8532. update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans);
  8533. var added = linesFor(1, text.length - 1);
  8534. if (nlines > 1) doc.remove(from.line + 1, nlines - 1);
  8535. doc.insert(from.line + 1, added);
  8536. }
  8537. signalLater(doc, "change", doc, change);
  8538. }
  8539. // The document is represented as a BTree consisting of leaves, with
  8540. // chunk of lines in them, and branches, with up to ten leaves or
  8541. // other branch nodes below them. The top node is always a branch
  8542. // node, and is the document object itself (meaning it has
  8543. // additional methods and properties).
  8544. //
  8545. // All nodes have parent links. The tree is used both to go from
  8546. // line numbers to line objects, and to go from objects to numbers.
  8547. // It also indexes by height, and is used to convert between height
  8548. // and line object, and to find the total height of the document.
  8549. //
  8550. // See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html
  8551. function LeafChunk(lines) {
  8552. this.lines = lines;
  8553. this.parent = null;
  8554. for (var i = 0, height = 0; i < lines.length; ++i) {
  8555. lines[i].parent = this;
  8556. height += lines[i].height;
  8557. }
  8558. this.height = height;
  8559. }
  8560. LeafChunk.prototype = {
  8561. chunkSize: function() { return this.lines.length; },
  8562. // Remove the n lines at offset 'at'.
  8563. removeInner: function(at, n) {
  8564. for (var i = at, e = at + n; i < e; ++i) {
  8565. var line = this.lines[i];
  8566. this.height -= line.height;
  8567. cleanUpLine(line);
  8568. signalLater(line, "delete");
  8569. }
  8570. this.lines.splice(at, n);
  8571. },
  8572. // Helper used to collapse a small branch into a single leaf.
  8573. collapse: function(lines) {
  8574. lines.push.apply(lines, this.lines);
  8575. },
  8576. // Insert the given array of lines at offset 'at', count them as
  8577. // having the given height.
  8578. insertInner: function(at, lines, height) {
  8579. this.height += height;
  8580. this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at));
  8581. for (var i = 0; i < lines.length; ++i) lines[i].parent = this;
  8582. },
  8583. // Used to iterate over a part of the tree.
  8584. iterN: function(at, n, op) {
  8585. for (var e = at + n; at < e; ++at)
  8586. if (op(this.lines[at])) return true;
  8587. }
  8588. };
  8589. function BranchChunk(children) {
  8590. this.children = children;
  8591. var size = 0, height = 0;
  8592. for (var i = 0; i < children.length; ++i) {
  8593. var ch = children[i];
  8594. size += ch.chunkSize(); height += ch.height;
  8595. ch.parent = this;
  8596. }
  8597. this.size = size;
  8598. this.height = height;
  8599. this.parent = null;
  8600. }
  8601. BranchChunk.prototype = {
  8602. chunkSize: function() { return this.size; },
  8603. removeInner: function(at, n) {
  8604. this.size -= n;
  8605. for (var i = 0; i < this.children.length; ++i) {
  8606. var child = this.children[i], sz = child.chunkSize();
  8607. if (at < sz) {
  8608. var rm = Math.min(n, sz - at), oldHeight = child.height;
  8609. child.removeInner(at, rm);
  8610. this.height -= oldHeight - child.height;
  8611. if (sz == rm) { this.children.splice(i--, 1); child.parent = null; }
  8612. if ((n -= rm) == 0) break;
  8613. at = 0;
  8614. } else at -= sz;
  8615. }
  8616. // If the result is smaller than 25 lines, ensure that it is a
  8617. // single leaf node.
  8618. if (this.size - n < 25 &&
  8619. (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) {
  8620. var lines = [];
  8621. this.collapse(lines);
  8622. this.children = [new LeafChunk(lines)];
  8623. this.children[0].parent = this;
  8624. }
  8625. },
  8626. collapse: function(lines) {
  8627. for (var i = 0; i < this.children.length; ++i) this.children[i].collapse(lines);
  8628. },
  8629. insertInner: function(at, lines, height) {
  8630. this.size += lines.length;
  8631. this.height += height;
  8632. for (var i = 0; i < this.children.length; ++i) {
  8633. var child = this.children[i], sz = child.chunkSize();
  8634. if (at <= sz) {
  8635. child.insertInner(at, lines, height);
  8636. if (child.lines && child.lines.length > 50) {
  8637. // To avoid memory thrashing when child.lines is huge (e.g. first view of a large file), it's never spliced.
  8638. // Instead, small slices are taken. They're taken in order because sequential memory accesses are fastest.
  8639. var remaining = child.lines.length % 25 + 25
  8640. for (var pos = remaining; pos < child.lines.length;) {
  8641. var leaf = new LeafChunk(child.lines.slice(pos, pos += 25));
  8642. child.height -= leaf.height;
  8643. this.children.splice(++i, 0, leaf);
  8644. leaf.parent = this;
  8645. }
  8646. child.lines = child.lines.slice(0, remaining);
  8647. this.maybeSpill();
  8648. }
  8649. break;
  8650. }
  8651. at -= sz;
  8652. }
  8653. },
  8654. // When a node has grown, check whether it should be split.
  8655. maybeSpill: function() {
  8656. if (this.children.length <= 10) return;
  8657. var me = this;
  8658. do {
  8659. var spilled = me.children.splice(me.children.length - 5, 5);
  8660. var sibling = new BranchChunk(spilled);
  8661. if (!me.parent) { // Become the parent node
  8662. var copy = new BranchChunk(me.children);
  8663. copy.parent = me;
  8664. me.children = [copy, sibling];
  8665. me = copy;
  8666. } else {
  8667. me.size -= sibling.size;
  8668. me.height -= sibling.height;
  8669. var myIndex = indexOf(me.parent.children, me);
  8670. me.parent.children.splice(myIndex + 1, 0, sibling);
  8671. }
  8672. sibling.parent = me.parent;
  8673. } while (me.children.length > 10);
  8674. me.parent.maybeSpill();
  8675. },
  8676. iterN: function(at, n, op) {
  8677. for (var i = 0; i < this.children.length; ++i) {
  8678. var child = this.children[i], sz = child.chunkSize();
  8679. if (at < sz) {
  8680. var used = Math.min(n, sz - at);
  8681. if (child.iterN(at, used, op)) return true;
  8682. if ((n -= used) == 0) break;
  8683. at = 0;
  8684. } else at -= sz;
  8685. }
  8686. }
  8687. };
  8688. var nextDocId = 0;
  8689. var Doc = CodeMirror.Doc = function(text, mode, firstLine, lineSep) {
  8690. if (!(this instanceof Doc)) return new Doc(text, mode, firstLine, lineSep);
  8691. if (firstLine == null) firstLine = 0;
  8692. BranchChunk.call(this, [new LeafChunk([new Line("", null)])]);
  8693. this.first = firstLine;
  8694. this.scrollTop = this.scrollLeft = 0;
  8695. this.cantEdit = false;
  8696. this.cleanGeneration = 1;
  8697. this.frontier = firstLine;
  8698. var start = Pos(firstLine, 0);
  8699. this.sel = simpleSelection(start);
  8700. this.history = new History(null);
  8701. this.id = ++nextDocId;
  8702. this.modeOption = mode;
  8703. this.lineSep = lineSep;
  8704. this.extend = false;
  8705. if (typeof text == "string") text = this.splitLines(text);
  8706. updateDoc(this, {from: start, to: start, text: text});
  8707. setSelection(this, simpleSelection(start), sel_dontScroll);
  8708. };
  8709. Doc.prototype = createObj(BranchChunk.prototype, {
  8710. constructor: Doc,
  8711. // Iterate over the document. Supports two forms -- with only one
  8712. // argument, it calls that for each line in the document. With
  8713. // three, it iterates over the range given by the first two (with
  8714. // the second being non-inclusive).
  8715. iter: function(from, to, op) {
  8716. if (op) this.iterN(from - this.first, to - from, op);
  8717. else this.iterN(this.first, this.first + this.size, from);
  8718. },
  8719. // Non-public interface for adding and removing lines.
  8720. insert: function(at, lines) {
  8721. var height = 0;
  8722. for (var i = 0; i < lines.length; ++i) height += lines[i].height;
  8723. this.insertInner(at - this.first, lines, height);
  8724. },
  8725. remove: function(at, n) { this.removeInner(at - this.first, n); },
  8726. // From here, the methods are part of the public interface. Most
  8727. // are also available from CodeMirror (editor) instances.
  8728. getValue: function(lineSep) {
  8729. var lines = getLines(this, this.first, this.first + this.size);
  8730. if (lineSep === false) return lines;
  8731. return lines.join(lineSep || this.lineSeparator());
  8732. },
  8733. setValue: docMethodOp(function(code) {
  8734. var top = Pos(this.first, 0), last = this.first + this.size - 1;
  8735. makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length),
  8736. text: this.splitLines(code), origin: "setValue", full: true}, true);
  8737. setSelection(this, simpleSelection(top));
  8738. }),
  8739. replaceRange: function(code, from, to, origin) {
  8740. from = clipPos(this, from);
  8741. to = to ? clipPos(this, to) : from;
  8742. replaceRange(this, code, from, to, origin);
  8743. },
  8744. getRange: function(from, to, lineSep) {
  8745. var lines = getBetween(this, clipPos(this, from), clipPos(this, to));
  8746. if (lineSep === false) return lines;
  8747. return lines.join(lineSep || this.lineSeparator());
  8748. },
  8749. getLine: function(line) {var l = this.getLineHandle(line); return l && l.text;},
  8750. getLineHandle: function(line) {if (isLine(this, line)) return getLine(this, line);},
  8751. getLineNumber: function(line) {return lineNo(line);},
  8752. getLineHandleVisualStart: function(line) {
  8753. if (typeof line == "number") line = getLine(this, line);
  8754. return visualLine(line);
  8755. },
  8756. lineCount: function() {return this.size;},
  8757. firstLine: function() {return this.first;},
  8758. lastLine: function() {return this.first + this.size - 1;},
  8759. clipPos: function(pos) {return clipPos(this, pos);},
  8760. getCursor: function(start) {
  8761. var range = this.sel.primary(), pos;
  8762. if (start == null || start == "head") pos = range.head;
  8763. else if (start == "anchor") pos = range.anchor;
  8764. else if (start == "end" || start == "to" || start === false) pos = range.to();
  8765. else pos = range.from();
  8766. return pos;
  8767. },
  8768. listSelections: function() { return this.sel.ranges; },
  8769. somethingSelected: function() {return this.sel.somethingSelected();},
  8770. setCursor: docMethodOp(function(line, ch, options) {
  8771. setSimpleSelection(this, clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line), null, options);
  8772. }),
  8773. setSelection: docMethodOp(function(anchor, head, options) {
  8774. setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options);
  8775. }),
  8776. extendSelection: docMethodOp(function(head, other, options) {
  8777. extendSelection(this, clipPos(this, head), other && clipPos(this, other), options);
  8778. }),
  8779. extendSelections: docMethodOp(function(heads, options) {
  8780. extendSelections(this, clipPosArray(this, heads), options);
  8781. }),
  8782. extendSelectionsBy: docMethodOp(function(f, options) {
  8783. var heads = map(this.sel.ranges, f);
  8784. extendSelections(this, clipPosArray(this, heads), options);
  8785. }),
  8786. setSelections: docMethodOp(function(ranges, primary, options) {
  8787. if (!ranges.length) return;
  8788. for (var i = 0, out = []; i < ranges.length; i++)
  8789. out[i] = new Range(clipPos(this, ranges[i].anchor),
  8790. clipPos(this, ranges[i].head));
  8791. if (primary == null) primary = Math.min(ranges.length - 1, this.sel.primIndex);
  8792. setSelection(this, normalizeSelection(out, primary), options);
  8793. }),
  8794. addSelection: docMethodOp(function(anchor, head, options) {
  8795. var ranges = this.sel.ranges.slice(0);
  8796. ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor)));
  8797. setSelection(this, normalizeSelection(ranges, ranges.length - 1), options);
  8798. }),
  8799. getSelection: function(lineSep) {
  8800. var ranges = this.sel.ranges, lines;
  8801. for (var i = 0; i < ranges.length; i++) {
  8802. var sel = getBetween(this, ranges[i].from(), ranges[i].to());
  8803. lines = lines ? lines.concat(sel) : sel;
  8804. }
  8805. if (lineSep === false) return lines;
  8806. else return lines.join(lineSep || this.lineSeparator());
  8807. },
  8808. getSelections: function(lineSep) {
  8809. var parts = [], ranges = this.sel.ranges;
  8810. for (var i = 0; i < ranges.length; i++) {
  8811. var sel = getBetween(this, ranges[i].from(), ranges[i].to());
  8812. if (lineSep !== false) sel = sel.join(lineSep || this.lineSeparator());
  8813. parts[i] = sel;
  8814. }
  8815. return parts;
  8816. },
  8817. replaceSelection: function(code, collapse, origin) {
  8818. var dup = [];
  8819. for (var i = 0; i < this.sel.ranges.length; i++)
  8820. dup[i] = code;
  8821. this.replaceSelections(dup, collapse, origin || "+input");
  8822. },
  8823. replaceSelections: docMethodOp(function(code, collapse, origin) {
  8824. var changes = [], sel = this.sel;
  8825. for (var i = 0; i < sel.ranges.length; i++) {
  8826. var range = sel.ranges[i];
  8827. changes[i] = {from: range.from(), to: range.to(), text: this.splitLines(code[i]), origin: origin};
  8828. }
  8829. var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse);
  8830. for (var i = changes.length - 1; i >= 0; i--)
  8831. makeChange(this, changes[i]);
  8832. if (newSel) setSelectionReplaceHistory(this, newSel);
  8833. else if (this.cm) ensureCursorVisible(this.cm);
  8834. }),
  8835. undo: docMethodOp(function() {makeChangeFromHistory(this, "undo");}),
  8836. redo: docMethodOp(function() {makeChangeFromHistory(this, "redo");}),
  8837. undoSelection: docMethodOp(function() {makeChangeFromHistory(this, "undo", true);}),
  8838. redoSelection: docMethodOp(function() {makeChangeFromHistory(this, "redo", true);}),
  8839. setExtending: function(val) {this.extend = val;},
  8840. getExtending: function() {return this.extend;},
  8841. historySize: function() {
  8842. var hist = this.history, done = 0, undone = 0;
  8843. for (var i = 0; i < hist.done.length; i++) if (!hist.done[i].ranges) ++done;
  8844. for (var i = 0; i < hist.undone.length; i++) if (!hist.undone[i].ranges) ++undone;
  8845. return {undo: done, redo: undone};
  8846. },
  8847. clearHistory: function() {this.history = new History(this.history.maxGeneration);},
  8848. markClean: function() {
  8849. this.cleanGeneration = this.changeGeneration(true);
  8850. },
  8851. changeGeneration: function(forceSplit) {
  8852. if (forceSplit)
  8853. this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null;
  8854. return this.history.generation;
  8855. },
  8856. isClean: function (gen) {
  8857. return this.history.generation == (gen || this.cleanGeneration);
  8858. },
  8859. getHistory: function() {
  8860. return {done: copyHistoryArray(this.history.done),
  8861. undone: copyHistoryArray(this.history.undone)};
  8862. },
  8863. setHistory: function(histData) {
  8864. var hist = this.history = new History(this.history.maxGeneration);
  8865. hist.done = copyHistoryArray(histData.done.slice(0), null, true);
  8866. hist.undone = copyHistoryArray(histData.undone.slice(0), null, true);
  8867. },
  8868. addLineClass: docMethodOp(function(handle, where, cls) {
  8869. return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function(line) {
  8870. var prop = where == "text" ? "textClass"
  8871. : where == "background" ? "bgClass"
  8872. : where == "gutter" ? "gutterClass" : "wrapClass";
  8873. if (!line[prop]) line[prop] = cls;
  8874. else if (classTest(cls).test(line[prop])) return false;
  8875. else line[prop] += " " + cls;
  8876. return true;
  8877. });
  8878. }),
  8879. removeLineClass: docMethodOp(function(handle, where, cls) {
  8880. return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function(line) {
  8881. var prop = where == "text" ? "textClass"
  8882. : where == "background" ? "bgClass"
  8883. : where == "gutter" ? "gutterClass" : "wrapClass";
  8884. var cur = line[prop];
  8885. if (!cur) return false;
  8886. else if (cls == null) line[prop] = null;
  8887. else {
  8888. var found = cur.match(classTest(cls));
  8889. if (!found) return false;
  8890. var end = found.index + found[0].length;
  8891. line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null;
  8892. }
  8893. return true;
  8894. });
  8895. }),
  8896. addLineWidget: docMethodOp(function(handle, node, options) {
  8897. return addLineWidget(this, handle, node, options);
  8898. }),
  8899. removeLineWidget: function(widget) { widget.clear(); },
  8900. markText: function(from, to, options) {
  8901. return markText(this, clipPos(this, from), clipPos(this, to), options, options && options.type || "range");
  8902. },
  8903. setBookmark: function(pos, options) {
  8904. var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options),
  8905. insertLeft: options && options.insertLeft,
  8906. clearWhenEmpty: false, shared: options && options.shared,
  8907. handleMouseEvents: options && options.handleMouseEvents};
  8908. pos = clipPos(this, pos);
  8909. return markText(this, pos, pos, realOpts, "bookmark");
  8910. },
  8911. findMarksAt: function(pos) {
  8912. pos = clipPos(this, pos);
  8913. var markers = [], spans = getLine(this, pos.line).markedSpans;
  8914. if (spans) for (var i = 0; i < spans.length; ++i) {
  8915. var span = spans[i];
  8916. if ((span.from == null || span.from <= pos.ch) &&
  8917. (span.to == null || span.to >= pos.ch))
  8918. markers.push(span.marker.parent || span.marker);
  8919. }
  8920. return markers;
  8921. },
  8922. findMarks: function(from, to, filter) {
  8923. from = clipPos(this, from); to = clipPos(this, to);
  8924. var found = [], lineNo = from.line;
  8925. this.iter(from.line, to.line + 1, function(line) {
  8926. var spans = line.markedSpans;
  8927. if (spans) for (var i = 0; i < spans.length; i++) {
  8928. var span = spans[i];
  8929. if (!(span.to != null && lineNo == from.line && from.ch >= span.to ||
  8930. span.from == null && lineNo != from.line ||
  8931. span.from != null && lineNo == to.line && span.from >= to.ch) &&
  8932. (!filter || filter(span.marker)))
  8933. found.push(span.marker.parent || span.marker);
  8934. }
  8935. ++lineNo;
  8936. });
  8937. return found;
  8938. },
  8939. getAllMarks: function() {
  8940. var markers = [];
  8941. this.iter(function(line) {
  8942. var sps = line.markedSpans;
  8943. if (sps) for (var i = 0; i < sps.length; ++i)
  8944. if (sps[i].from != null) markers.push(sps[i].marker);
  8945. });
  8946. return markers;
  8947. },
  8948. posFromIndex: function(off) {
  8949. var ch, lineNo = this.first, sepSize = this.lineSeparator().length;
  8950. this.iter(function(line) {
  8951. var sz = line.text.length + sepSize;
  8952. if (sz > off) { ch = off; return true; }
  8953. off -= sz;
  8954. ++lineNo;
  8955. });
  8956. return clipPos(this, Pos(lineNo, ch));
  8957. },
  8958. indexFromPos: function (coords) {
  8959. coords = clipPos(this, coords);
  8960. var index = coords.ch;
  8961. if (coords.line < this.first || coords.ch < 0) return 0;
  8962. var sepSize = this.lineSeparator().length;
  8963. this.iter(this.first, coords.line, function (line) {
  8964. index += line.text.length + sepSize;
  8965. });
  8966. return index;
  8967. },
  8968. copy: function(copyHistory) {
  8969. var doc = new Doc(getLines(this, this.first, this.first + this.size),
  8970. this.modeOption, this.first, this.lineSep);
  8971. doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft;
  8972. doc.sel = this.sel;
  8973. doc.extend = false;
  8974. if (copyHistory) {
  8975. doc.history.undoDepth = this.history.undoDepth;
  8976. doc.setHistory(this.getHistory());
  8977. }
  8978. return doc;
  8979. },
  8980. linkedDoc: function(options) {
  8981. if (!options) options = {};
  8982. var from = this.first, to = this.first + this.size;
  8983. if (options.from != null && options.from > from) from = options.from;
  8984. if (options.to != null && options.to < to) to = options.to;
  8985. var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from, this.lineSep);
  8986. if (options.sharedHist) copy.history = this.history;
  8987. (this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist});
  8988. copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}];
  8989. copySharedMarkers(copy, findSharedMarkers(this));
  8990. return copy;
  8991. },
  8992. unlinkDoc: function(other) {
  8993. if (other instanceof CodeMirror) other = other.doc;
  8994. if (this.linked) for (var i = 0; i < this.linked.length; ++i) {
  8995. var link = this.linked[i];
  8996. if (link.doc != other) continue;
  8997. this.linked.splice(i, 1);
  8998. other.unlinkDoc(this);
  8999. detachSharedMarkers(findSharedMarkers(this));
  9000. break;
  9001. }
  9002. // If the histories were shared, split them again
  9003. if (other.history == this.history) {
  9004. var splitIds = [other.id];
  9005. linkedDocs(other, function(doc) {splitIds.push(doc.id);}, true);
  9006. other.history = new History(null);
  9007. other.history.done = copyHistoryArray(this.history.done, splitIds);
  9008. other.history.undone = copyHistoryArray(this.history.undone, splitIds);
  9009. }
  9010. },
  9011. iterLinkedDocs: function(f) {linkedDocs(this, f);},
  9012. getMode: function() {return this.mode;},
  9013. getEditor: function() {return this.cm;},
  9014. splitLines: function(str) {
  9015. if (this.lineSep) return str.split(this.lineSep);
  9016. return splitLinesAuto(str);
  9017. },
  9018. lineSeparator: function() { return this.lineSep || "\n"; }
  9019. });
  9020. // Public alias.
  9021. Doc.prototype.eachLine = Doc.prototype.iter;
  9022. // Set up methods on CodeMirror's prototype to redirect to the editor's document.
  9023. var dontDelegate = "iter insert remove copy getEditor constructor".split(" ");
  9024. for (var prop in Doc.prototype) if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0)
  9025. CodeMirror.prototype[prop] = (function(method) {
  9026. return function() {return method.apply(this.doc, arguments);};
  9027. })(Doc.prototype[prop]);
  9028. eventMixin(Doc);
  9029. // Call f for all linked documents.
  9030. function linkedDocs(doc, f, sharedHistOnly) {
  9031. function propagate(doc, skip, sharedHist) {
  9032. if (doc.linked) for (var i = 0; i < doc.linked.length; ++i) {
  9033. var rel = doc.linked[i];
  9034. if (rel.doc == skip) continue;
  9035. var shared = sharedHist && rel.sharedHist;
  9036. if (sharedHistOnly && !shared) continue;
  9037. f(rel.doc, shared);
  9038. propagate(rel.doc, doc, shared);
  9039. }
  9040. }
  9041. propagate(doc, null, true);
  9042. }
  9043. // Attach a document to an editor.
  9044. function attachDoc(cm, doc) {
  9045. if (doc.cm) throw new Error("This document is already in use.");
  9046. cm.doc = doc;
  9047. doc.cm = cm;
  9048. estimateLineHeights(cm);
  9049. loadMode(cm);
  9050. if (!cm.options.lineWrapping) findMaxLine(cm);
  9051. cm.options.mode = doc.modeOption;
  9052. regChange(cm);
  9053. }
  9054. // LINE UTILITIES
  9055. // Find the line object corresponding to the given line number.
  9056. function getLine(doc, n) {
  9057. n -= doc.first;
  9058. if (n < 0 || n >= doc.size) throw new Error("There is no line " + (n + doc.first) + " in the document.");
  9059. for (var chunk = doc; !chunk.lines;) {
  9060. for (var i = 0;; ++i) {
  9061. var child = chunk.children[i], sz = child.chunkSize();
  9062. if (n < sz) { chunk = child; break; }
  9063. n -= sz;
  9064. }
  9065. }
  9066. return chunk.lines[n];
  9067. }
  9068. // Get the part of a document between two positions, as an array of
  9069. // strings.
  9070. function getBetween(doc, start, end) {
  9071. var out = [], n = start.line;
  9072. doc.iter(start.line, end.line + 1, function(line) {
  9073. var text = line.text;
  9074. if (n == end.line) text = text.slice(0, end.ch);
  9075. if (n == start.line) text = text.slice(start.ch);
  9076. out.push(text);
  9077. ++n;
  9078. });
  9079. return out;
  9080. }
  9081. // Get the lines between from and to, as array of strings.
  9082. function getLines(doc, from, to) {
  9083. var out = [];
  9084. doc.iter(from, to, function(line) { out.push(line.text); });
  9085. return out;
  9086. }
  9087. // Update the height of a line, propagating the height change
  9088. // upwards to parent nodes.
  9089. function updateLineHeight(line, height) {
  9090. var diff = height - line.height;
  9091. if (diff) for (var n = line; n; n = n.parent) n.height += diff;
  9092. }
  9093. // Given a line object, find its line number by walking up through
  9094. // its parent links.
  9095. function lineNo(line) {
  9096. if (line.parent == null) return null;
  9097. var cur = line.parent, no = indexOf(cur.lines, line);
  9098. for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) {
  9099. for (var i = 0;; ++i) {
  9100. if (chunk.children[i] == cur) break;
  9101. no += chunk.children[i].chunkSize();
  9102. }
  9103. }
  9104. return no + cur.first;
  9105. }
  9106. // Find the line at the given vertical position, using the height
  9107. // information in the document tree.
  9108. function lineAtHeight(chunk, h) {
  9109. var n = chunk.first;
  9110. outer: do {
  9111. for (var i = 0; i < chunk.children.length; ++i) {
  9112. var child = chunk.children[i], ch = child.height;
  9113. if (h < ch) { chunk = child; continue outer; }
  9114. h -= ch;
  9115. n += child.chunkSize();
  9116. }
  9117. return n;
  9118. } while (!chunk.lines);
  9119. for (var i = 0; i < chunk.lines.length; ++i) {
  9120. var line = chunk.lines[i], lh = line.height;
  9121. if (h < lh) break;
  9122. h -= lh;
  9123. }
  9124. return n + i;
  9125. }
  9126. // Find the height above the given line.
  9127. function heightAtLine(lineObj) {
  9128. lineObj = visualLine(lineObj);
  9129. var h = 0, chunk = lineObj.parent;
  9130. for (var i = 0; i < chunk.lines.length; ++i) {
  9131. var line = chunk.lines[i];
  9132. if (line == lineObj) break;
  9133. else h += line.height;
  9134. }
  9135. for (var p = chunk.parent; p; chunk = p, p = chunk.parent) {
  9136. for (var i = 0; i < p.children.length; ++i) {
  9137. var cur = p.children[i];
  9138. if (cur == chunk) break;
  9139. else h += cur.height;
  9140. }
  9141. }
  9142. return h;
  9143. }
  9144. // Get the bidi ordering for the given line (and cache it). Returns
  9145. // false for lines that are fully left-to-right, and an array of
  9146. // BidiSpan objects otherwise.
  9147. function getOrder(line) {
  9148. var order = line.order;
  9149. if (order == null) order = line.order = bidiOrdering(line.text);
  9150. return order;
  9151. }
  9152. // HISTORY
  9153. function History(startGen) {
  9154. // Arrays of change events and selections. Doing something adds an
  9155. // event to done and clears undo. Undoing moves events from done
  9156. // to undone, redoing moves them in the other direction.
  9157. this.done = []; this.undone = [];
  9158. this.undoDepth = Infinity;
  9159. // Used to track when changes can be merged into a single undo
  9160. // event
  9161. this.lastModTime = this.lastSelTime = 0;
  9162. this.lastOp = this.lastSelOp = null;
  9163. this.lastOrigin = this.lastSelOrigin = null;
  9164. // Used by the isClean() method
  9165. this.generation = this.maxGeneration = startGen || 1;
  9166. }
  9167. // Create a history change event from an updateDoc-style change
  9168. // object.
  9169. function historyChangeFromChange(doc, change) {
  9170. var histChange = {from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to)};
  9171. attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);
  9172. linkedDocs(doc, function(doc) {attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);}, true);
  9173. return histChange;
  9174. }
  9175. // Pop all selection events off the end of a history array. Stop at
  9176. // a change event.
  9177. function clearSelectionEvents(array) {
  9178. while (array.length) {
  9179. var last = lst(array);
  9180. if (last.ranges) array.pop();
  9181. else break;
  9182. }
  9183. }
  9184. // Find the top change event in the history. Pop off selection
  9185. // events that are in the way.
  9186. function lastChangeEvent(hist, force) {
  9187. if (force) {
  9188. clearSelectionEvents(hist.done);
  9189. return lst(hist.done);
  9190. } else if (hist.done.length && !lst(hist.done).ranges) {
  9191. return lst(hist.done);
  9192. } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) {
  9193. hist.done.pop();
  9194. return lst(hist.done);
  9195. }
  9196. }
  9197. // Register a change in the history. Merges changes that are within
  9198. // a single operation, ore are close together with an origin that
  9199. // allows merging (starting with "+") into a single event.
  9200. function addChangeToHistory(doc, change, selAfter, opId) {
  9201. var hist = doc.history;
  9202. hist.undone.length = 0;
  9203. var time = +new Date, cur;
  9204. if ((hist.lastOp == opId ||
  9205. hist.lastOrigin == change.origin && change.origin &&
  9206. ((change.origin.charAt(0) == "+" && doc.cm && hist.lastModTime > time - doc.cm.options.historyEventDelay) ||
  9207. change.origin.charAt(0) == "*")) &&
  9208. (cur = lastChangeEvent(hist, hist.lastOp == opId))) {
  9209. // Merge this change into the last event
  9210. var last = lst(cur.changes);
  9211. if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) {
  9212. // Optimized case for simple insertion -- don't want to add
  9213. // new changesets for every character typed
  9214. last.to = changeEnd(change);
  9215. } else {
  9216. // Add new sub-event
  9217. cur.changes.push(historyChangeFromChange(doc, change));
  9218. }
  9219. } else {
  9220. // Can not be merged, start a new event.
  9221. var before = lst(hist.done);
  9222. if (!before || !before.ranges)
  9223. pushSelectionToHistory(doc.sel, hist.done);
  9224. cur = {changes: [historyChangeFromChange(doc, change)],
  9225. generation: hist.generation};
  9226. hist.done.push(cur);
  9227. while (hist.done.length > hist.undoDepth) {
  9228. hist.done.shift();
  9229. if (!hist.done[0].ranges) hist.done.shift();
  9230. }
  9231. }
  9232. hist.done.push(selAfter);
  9233. hist.generation = ++hist.maxGeneration;
  9234. hist.lastModTime = hist.lastSelTime = time;
  9235. hist.lastOp = hist.lastSelOp = opId;
  9236. hist.lastOrigin = hist.lastSelOrigin = change.origin;
  9237. if (!last) signal(doc, "historyAdded");
  9238. }
  9239. function selectionEventCanBeMerged(doc, origin, prev, sel) {
  9240. var ch = origin.charAt(0);
  9241. return ch == "*" ||
  9242. ch == "+" &&
  9243. prev.ranges.length == sel.ranges.length &&
  9244. prev.somethingSelected() == sel.somethingSelected() &&
  9245. new Date - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500);
  9246. }
  9247. // Called whenever the selection changes, sets the new selection as
  9248. // the pending selection in the history, and pushes the old pending
  9249. // selection into the 'done' array when it was significantly
  9250. // different (in number of selected ranges, emptiness, or time).
  9251. function addSelectionToHistory(doc, sel, opId, options) {
  9252. var hist = doc.history, origin = options && options.origin;
  9253. // A new event is started when the previous origin does not match
  9254. // the current, or the origins don't allow matching. Origins
  9255. // starting with * are always merged, those starting with + are
  9256. // merged when similar and close together in time.
  9257. if (opId == hist.lastSelOp ||
  9258. (origin && hist.lastSelOrigin == origin &&
  9259. (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin ||
  9260. selectionEventCanBeMerged(doc, origin, lst(hist.done), sel))))
  9261. hist.done[hist.done.length - 1] = sel;
  9262. else
  9263. pushSelectionToHistory(sel, hist.done);
  9264. hist.lastSelTime = +new Date;
  9265. hist.lastSelOrigin = origin;
  9266. hist.lastSelOp = opId;
  9267. if (options && options.clearRedo !== false)
  9268. clearSelectionEvents(hist.undone);
  9269. }
  9270. function pushSelectionToHistory(sel, dest) {
  9271. var top = lst(dest);
  9272. if (!(top && top.ranges && top.equals(sel)))
  9273. dest.push(sel);
  9274. }
  9275. // Used to store marked span information in the history.
  9276. function attachLocalSpans(doc, change, from, to) {
  9277. var existing = change["spans_" + doc.id], n = 0;
  9278. doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function(line) {
  9279. if (line.markedSpans)
  9280. (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans;
  9281. ++n;
  9282. });
  9283. }
  9284. // When un/re-doing restores text containing marked spans, those
  9285. // that have been explicitly cleared should not be restored.
  9286. function removeClearedSpans(spans) {
  9287. if (!spans) return null;
  9288. for (var i = 0, out; i < spans.length; ++i) {
  9289. if (spans[i].marker.explicitlyCleared) { if (!out) out = spans.slice(0, i); }
  9290. else if (out) out.push(spans[i]);
  9291. }
  9292. return !out ? spans : out.length ? out : null;
  9293. }
  9294. // Retrieve and filter the old marked spans stored in a change event.
  9295. function getOldSpans(doc, change) {
  9296. var found = change["spans_" + doc.id];
  9297. if (!found) return null;
  9298. for (var i = 0, nw = []; i < change.text.length; ++i)
  9299. nw.push(removeClearedSpans(found[i]));
  9300. return nw;
  9301. }
  9302. // Used both to provide a JSON-safe object in .getHistory, and, when
  9303. // detaching a document, to split the history in two
  9304. function copyHistoryArray(events, newGroup, instantiateSel) {
  9305. for (var i = 0, copy = []; i < events.length; ++i) {
  9306. var event = events[i];
  9307. if (event.ranges) {
  9308. copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event);
  9309. continue;
  9310. }
  9311. var changes = event.changes, newChanges = [];
  9312. copy.push({changes: newChanges});
  9313. for (var j = 0; j < changes.length; ++j) {
  9314. var change = changes[j], m;
  9315. newChanges.push({from: change.from, to: change.to, text: change.text});
  9316. if (newGroup) for (var prop in change) if (m = prop.match(/^spans_(\d+)$/)) {
  9317. if (indexOf(newGroup, Number(m[1])) > -1) {
  9318. lst(newChanges)[prop] = change[prop];
  9319. delete change[prop];
  9320. }
  9321. }
  9322. }
  9323. }
  9324. return copy;
  9325. }
  9326. // Rebasing/resetting history to deal with externally-sourced changes
  9327. function rebaseHistSelSingle(pos, from, to, diff) {
  9328. if (to < pos.line) {
  9329. pos.line += diff;
  9330. } else if (from < pos.line) {
  9331. pos.line = from;
  9332. pos.ch = 0;
  9333. }
  9334. }
  9335. // Tries to rebase an array of history events given a change in the
  9336. // document. If the change touches the same lines as the event, the
  9337. // event, and everything 'behind' it, is discarded. If the change is
  9338. // before the event, the event's positions are updated. Uses a
  9339. // copy-on-write scheme for the positions, to avoid having to
  9340. // reallocate them all on every rebase, but also avoid problems with
  9341. // shared position objects being unsafely updated.
  9342. function rebaseHistArray(array, from, to, diff) {
  9343. for (var i = 0; i < array.length; ++i) {
  9344. var sub = array[i], ok = true;
  9345. if (sub.ranges) {
  9346. if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true; }
  9347. for (var j = 0; j < sub.ranges.length; j++) {
  9348. rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff);
  9349. rebaseHistSelSingle(sub.ranges[j].head, from, to, diff);
  9350. }
  9351. continue;
  9352. }
  9353. for (var j = 0; j < sub.changes.length; ++j) {
  9354. var cur = sub.changes[j];
  9355. if (to < cur.from.line) {
  9356. cur.from = Pos(cur.from.line + diff, cur.from.ch);
  9357. cur.to = Pos(cur.to.line + diff, cur.to.ch);
  9358. } else if (from <= cur.to.line) {
  9359. ok = false;
  9360. break;
  9361. }
  9362. }
  9363. if (!ok) {
  9364. array.splice(0, i + 1);
  9365. i = 0;
  9366. }
  9367. }
  9368. }
  9369. function rebaseHist(hist, change) {
  9370. var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1;
  9371. rebaseHistArray(hist.done, from, to, diff);
  9372. rebaseHistArray(hist.undone, from, to, diff);
  9373. }
  9374. // EVENT UTILITIES
  9375. // Due to the fact that we still support jurassic IE versions, some
  9376. // compatibility wrappers are needed.
  9377. var e_preventDefault = CodeMirror.e_preventDefault = function(e) {
  9378. if (e.preventDefault) e.preventDefault();
  9379. else e.returnValue = false;
  9380. };
  9381. var e_stopPropagation = CodeMirror.e_stopPropagation = function(e) {
  9382. if (e.stopPropagation) e.stopPropagation();
  9383. else e.cancelBubble = true;
  9384. };
  9385. function e_defaultPrevented(e) {
  9386. return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false;
  9387. }
  9388. var e_stop = CodeMirror.e_stop = function(e) {e_preventDefault(e); e_stopPropagation(e);};
  9389. function e_target(e) {return e.target || e.srcElement;}
  9390. function e_button(e) {
  9391. var b = e.which;
  9392. if (b == null) {
  9393. if (e.button & 1) b = 1;
  9394. else if (e.button & 2) b = 3;
  9395. else if (e.button & 4) b = 2;
  9396. }
  9397. if (mac && e.ctrlKey && b == 1) b = 3;
  9398. return b;
  9399. }
  9400. // EVENT HANDLING
  9401. // Lightweight event framework. on/off also work on DOM nodes,
  9402. // registering native DOM handlers.
  9403. var on = CodeMirror.on = function(emitter, type, f) {
  9404. if (emitter.addEventListener)
  9405. emitter.addEventListener(type, f, false);
  9406. else if (emitter.attachEvent)
  9407. emitter.attachEvent("on" + type, f);
  9408. else {
  9409. var map = emitter._handlers || (emitter._handlers = {});
  9410. var arr = map[type] || (map[type] = []);
  9411. arr.push(f);
  9412. }
  9413. };
  9414. var noHandlers = []
  9415. function getHandlers(emitter, type, copy) {
  9416. var arr = emitter._handlers && emitter._handlers[type]
  9417. if (copy) return arr && arr.length > 0 ? arr.slice() : noHandlers
  9418. else return arr || noHandlers
  9419. }
  9420. var off = CodeMirror.off = function(emitter, type, f) {
  9421. if (emitter.removeEventListener)
  9422. emitter.removeEventListener(type, f, false);
  9423. else if (emitter.detachEvent)
  9424. emitter.detachEvent("on" + type, f);
  9425. else {
  9426. var handlers = getHandlers(emitter, type, false)
  9427. for (var i = 0; i < handlers.length; ++i)
  9428. if (handlers[i] == f) { handlers.splice(i, 1); break; }
  9429. }
  9430. };
  9431. var signal = CodeMirror.signal = function(emitter, type /*, values...*/) {
  9432. var handlers = getHandlers(emitter, type, true)
  9433. if (!handlers.length) return;
  9434. var args = Array.prototype.slice.call(arguments, 2);
  9435. for (var i = 0; i < handlers.length; ++i) handlers[i].apply(null, args);
  9436. };
  9437. var orphanDelayedCallbacks = null;
  9438. // Often, we want to signal events at a point where we are in the
  9439. // middle of some work, but don't want the handler to start calling
  9440. // other methods on the editor, which might be in an inconsistent
  9441. // state or simply not expect any other events to happen.
  9442. // signalLater looks whether there are any handlers, and schedules
  9443. // them to be executed when the last operation ends, or, if no
  9444. // operation is active, when a timeout fires.
  9445. function signalLater(emitter, type /*, values...*/) {
  9446. var arr = getHandlers(emitter, type, false)
  9447. if (!arr.length) return;
  9448. var args = Array.prototype.slice.call(arguments, 2), list;
  9449. if (operationGroup) {
  9450. list = operationGroup.delayedCallbacks;
  9451. } else if (orphanDelayedCallbacks) {
  9452. list = orphanDelayedCallbacks;
  9453. } else {
  9454. list = orphanDelayedCallbacks = [];
  9455. setTimeout(fireOrphanDelayed, 0);
  9456. }
  9457. function bnd(f) {return function(){f.apply(null, args);};};
  9458. for (var i = 0; i < arr.length; ++i)
  9459. list.push(bnd(arr[i]));
  9460. }
  9461. function fireOrphanDelayed() {
  9462. var delayed = orphanDelayedCallbacks;
  9463. orphanDelayedCallbacks = null;
  9464. for (var i = 0; i < delayed.length; ++i) delayed[i]();
  9465. }
  9466. // The DOM events that CodeMirror handles can be overridden by
  9467. // registering a (non-DOM) handler on the editor for the event name,
  9468. // and preventDefault-ing the event in that handler.
  9469. function signalDOMEvent(cm, e, override) {
  9470. if (typeof e == "string")
  9471. e = {type: e, preventDefault: function() { this.defaultPrevented = true; }};
  9472. signal(cm, override || e.type, cm, e);
  9473. return e_defaultPrevented(e) || e.codemirrorIgnore;
  9474. }
  9475. function signalCursorActivity(cm) {
  9476. var arr = cm._handlers && cm._handlers.cursorActivity;
  9477. if (!arr) return;
  9478. var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = []);
  9479. for (var i = 0; i < arr.length; ++i) if (indexOf(set, arr[i]) == -1)
  9480. set.push(arr[i]);
  9481. }
  9482. function hasHandler(emitter, type) {
  9483. return getHandlers(emitter, type).length > 0
  9484. }
  9485. // Add on and off methods to a constructor's prototype, to make
  9486. // registering events on such objects more convenient.
  9487. function eventMixin(ctor) {
  9488. ctor.prototype.on = function(type, f) {on(this, type, f);};
  9489. ctor.prototype.off = function(type, f) {off(this, type, f);};
  9490. }
  9491. // MISC UTILITIES
  9492. // Number of pixels added to scroller and sizer to hide scrollbar
  9493. var scrollerGap = 30;
  9494. // Returned or thrown by various protocols to signal 'I'm not
  9495. // handling this'.
  9496. var Pass = CodeMirror.Pass = {toString: function(){return "CodeMirror.Pass";}};
  9497. // Reused option objects for setSelection & friends
  9498. var sel_dontScroll = {scroll: false}, sel_mouse = {origin: "*mouse"}, sel_move = {origin: "+move"};
  9499. function Delayed() {this.id = null;}
  9500. Delayed.prototype.set = function(ms, f) {
  9501. clearTimeout(this.id);
  9502. this.id = setTimeout(f, ms);
  9503. };
  9504. // Counts the column offset in a string, taking tabs into account.
  9505. // Used mostly to find indentation.
  9506. var countColumn = CodeMirror.countColumn = function(string, end, tabSize, startIndex, startValue) {
  9507. if (end == null) {
  9508. end = string.search(/[^\s\u00a0]/);
  9509. if (end == -1) end = string.length;
  9510. }
  9511. for (var i = startIndex || 0, n = startValue || 0;;) {
  9512. var nextTab = string.indexOf("\t", i);
  9513. if (nextTab < 0 || nextTab >= end)
  9514. return n + (end - i);
  9515. n += nextTab - i;
  9516. n += tabSize - (n % tabSize);
  9517. i = nextTab + 1;
  9518. }
  9519. };
  9520. // The inverse of countColumn -- find the offset that corresponds to
  9521. // a particular column.
  9522. var findColumn = CodeMirror.findColumn = function(string, goal, tabSize) {
  9523. for (var pos = 0, col = 0;;) {
  9524. var nextTab = string.indexOf("\t", pos);
  9525. if (nextTab == -1) nextTab = string.length;
  9526. var skipped = nextTab - pos;
  9527. if (nextTab == string.length || col + skipped >= goal)
  9528. return pos + Math.min(skipped, goal - col);
  9529. col += nextTab - pos;
  9530. col += tabSize - (col % tabSize);
  9531. pos = nextTab + 1;
  9532. if (col >= goal) return pos;
  9533. }
  9534. }
  9535. var spaceStrs = [""];
  9536. function spaceStr(n) {
  9537. while (spaceStrs.length <= n)
  9538. spaceStrs.push(lst(spaceStrs) + " ");
  9539. return spaceStrs[n];
  9540. }
  9541. function lst(arr) { return arr[arr.length-1]; }
  9542. var selectInput = function(node) { node.select(); };
  9543. if (ios) // Mobile Safari apparently has a bug where select() is broken.
  9544. selectInput = function(node) { node.selectionStart = 0; node.selectionEnd = node.value.length; };
  9545. else if (ie) // Suppress mysterious IE10 errors
  9546. selectInput = function(node) { try { node.select(); } catch(_e) {} };
  9547. function indexOf(array, elt) {
  9548. for (var i = 0; i < array.length; ++i)
  9549. if (array[i] == elt) return i;
  9550. return -1;
  9551. }
  9552. function map(array, f) {
  9553. var out = [];
  9554. for (var i = 0; i < array.length; i++) out[i] = f(array[i], i);
  9555. return out;
  9556. }
  9557. function nothing() {}
  9558. function createObj(base, props) {
  9559. var inst;
  9560. if (Object.create) {
  9561. inst = Object.create(base);
  9562. } else {
  9563. nothing.prototype = base;
  9564. inst = new nothing();
  9565. }
  9566. if (props) copyObj(props, inst);
  9567. return inst;
  9568. };
  9569. function copyObj(obj, target, overwrite) {
  9570. if (!target) target = {};
  9571. for (var prop in obj)
  9572. if (obj.hasOwnProperty(prop) && (overwrite !== false || !target.hasOwnProperty(prop)))
  9573. target[prop] = obj[prop];
  9574. return target;
  9575. }
  9576. function bind(f) {
  9577. var args = Array.prototype.slice.call(arguments, 1);
  9578. return function(){return f.apply(null, args);};
  9579. }
  9580. var nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;
  9581. var isWordCharBasic = CodeMirror.isWordChar = function(ch) {
  9582. return /\w/.test(ch) || ch > "\x80" &&
  9583. (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch));
  9584. };
  9585. function isWordChar(ch, helper) {
  9586. if (!helper) return isWordCharBasic(ch);
  9587. if (helper.source.indexOf("\\w") > -1 && isWordCharBasic(ch)) return true;
  9588. return helper.test(ch);
  9589. }
  9590. function isEmpty(obj) {
  9591. for (var n in obj) if (obj.hasOwnProperty(n) && obj[n]) return false;
  9592. return true;
  9593. }
  9594. // Extending unicode characters. A series of a non-extending char +
  9595. // any number of extending chars is treated as a single unit as far
  9596. // as editing and measuring is concerned. This is not fully correct,
  9597. // since some scripts/fonts/browsers also treat other configurations
  9598. // of code points as a group.
  9599. 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]/;
  9600. function isExtendingChar(ch) { return ch.charCodeAt(0) >= 768 && extendingChars.test(ch); }
  9601. // DOM UTILITIES
  9602. function elt(tag, content, className, style) {
  9603. var e = document.createElement(tag);
  9604. if (className) e.className = className;
  9605. if (style) e.style.cssText = style;
  9606. if (typeof content == "string") e.appendChild(document.createTextNode(content));
  9607. else if (content) for (var i = 0; i < content.length; ++i) e.appendChild(content[i]);
  9608. return e;
  9609. }
  9610. var range;
  9611. if (document.createRange) range = function(node, start, end, endNode) {
  9612. var r = document.createRange();
  9613. r.setEnd(endNode || node, end);
  9614. r.setStart(node, start);
  9615. return r;
  9616. };
  9617. else range = function(node, start, end) {
  9618. var r = document.body.createTextRange();
  9619. try { r.moveToElementText(node.parentNode); }
  9620. catch(e) { return r; }
  9621. r.collapse(true);
  9622. r.moveEnd("character", end);
  9623. r.moveStart("character", start);
  9624. return r;
  9625. };
  9626. function removeChildren(e) {
  9627. for (var count = e.childNodes.length; count > 0; --count)
  9628. e.removeChild(e.firstChild);
  9629. return e;
  9630. }
  9631. function removeChildrenAndAdd(parent, e) {
  9632. return removeChildren(parent).appendChild(e);
  9633. }
  9634. var contains = CodeMirror.contains = function(parent, child) {
  9635. if (child.nodeType == 3) // Android browser always returns false when child is a textnode
  9636. child = child.parentNode;
  9637. if (parent.contains)
  9638. return parent.contains(child);
  9639. do {
  9640. if (child.nodeType == 11) child = child.host;
  9641. if (child == parent) return true;
  9642. } while (child = child.parentNode);
  9643. };
  9644. function activeElt() {
  9645. var activeElement = document.activeElement;
  9646. while (activeElement && activeElement.root && activeElement.root.activeElement)
  9647. activeElement = activeElement.root.activeElement;
  9648. return activeElement;
  9649. }
  9650. // Older versions of IE throws unspecified error when touching
  9651. // document.activeElement in some cases (during loading, in iframe)
  9652. if (ie && ie_version < 11) activeElt = function() {
  9653. try { return document.activeElement; }
  9654. catch(e) { return document.body; }
  9655. };
  9656. function classTest(cls) { return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*"); }
  9657. var rmClass = CodeMirror.rmClass = function(node, cls) {
  9658. var current = node.className;
  9659. var match = classTest(cls).exec(current);
  9660. if (match) {
  9661. var after = current.slice(match.index + match[0].length);
  9662. node.className = current.slice(0, match.index) + (after ? match[1] + after : "");
  9663. }
  9664. };
  9665. var addClass = CodeMirror.addClass = function(node, cls) {
  9666. var current = node.className;
  9667. if (!classTest(cls).test(current)) node.className += (current ? " " : "") + cls;
  9668. };
  9669. function joinClasses(a, b) {
  9670. var as = a.split(" ");
  9671. for (var i = 0; i < as.length; i++)
  9672. if (as[i] && !classTest(as[i]).test(b)) b += " " + as[i];
  9673. return b;
  9674. }
  9675. // WINDOW-WIDE EVENTS
  9676. // These must be handled carefully, because naively registering a
  9677. // handler for each editor will cause the editors to never be
  9678. // garbage collected.
  9679. function forEachCodeMirror(f) {
  9680. if (!document.body.getElementsByClassName) return;
  9681. var byClass = document.body.getElementsByClassName("CodeMirror");
  9682. for (var i = 0; i < byClass.length; i++) {
  9683. var cm = byClass[i].CodeMirror;
  9684. if (cm) f(cm);
  9685. }
  9686. }
  9687. var globalsRegistered = false;
  9688. function ensureGlobalHandlers() {
  9689. if (globalsRegistered) return;
  9690. registerGlobalHandlers();
  9691. globalsRegistered = true;
  9692. }
  9693. function registerGlobalHandlers() {
  9694. // When the window resizes, we need to refresh active editors.
  9695. var resizeTimer;
  9696. on(window, "resize", function() {
  9697. if (resizeTimer == null) resizeTimer = setTimeout(function() {
  9698. resizeTimer = null;
  9699. forEachCodeMirror(onResize);
  9700. }, 100);
  9701. });
  9702. // When the window loses focus, we want to show the editor as blurred
  9703. on(window, "blur", function() {
  9704. forEachCodeMirror(onBlur);
  9705. });
  9706. }
  9707. // FEATURE DETECTION
  9708. // Detect drag-and-drop
  9709. var dragAndDrop = function() {
  9710. // There is *some* kind of drag-and-drop support in IE6-8, but I
  9711. // couldn't get it to work yet.
  9712. if (ie && ie_version < 9) return false;
  9713. var div = elt('div');
  9714. return "draggable" in div || "dragDrop" in div;
  9715. }();
  9716. var zwspSupported;
  9717. function zeroWidthElement(measure) {
  9718. if (zwspSupported == null) {
  9719. var test = elt("span", "\u200b");
  9720. removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")]));
  9721. if (measure.firstChild.offsetHeight != 0)
  9722. zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8);
  9723. }
  9724. var node = zwspSupported ? elt("span", "\u200b") :
  9725. elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px");
  9726. node.setAttribute("cm-text", "");
  9727. return node;
  9728. }
  9729. // Feature-detect IE's crummy client rect reporting for bidi text
  9730. var badBidiRects;
  9731. function hasBadBidiRects(measure) {
  9732. if (badBidiRects != null) return badBidiRects;
  9733. var txt = removeChildrenAndAdd(measure, document.createTextNode("A\u062eA"));
  9734. var r0 = range(txt, 0, 1).getBoundingClientRect();
  9735. var r1 = range(txt, 1, 2).getBoundingClientRect();
  9736. removeChildren(measure);
  9737. if (!r0 || r0.left == r0.right) return false; // Safari returns null in some cases (#2780)
  9738. return badBidiRects = (r1.right - r0.right < 3);
  9739. }
  9740. // See if "".split is the broken IE version, if so, provide an
  9741. // alternative way to split lines.
  9742. var splitLinesAuto = CodeMirror.splitLines = "\n\nb".split(/\n/).length != 3 ? function(string) {
  9743. var pos = 0, result = [], l = string.length;
  9744. while (pos <= l) {
  9745. var nl = string.indexOf("\n", pos);
  9746. if (nl == -1) nl = string.length;
  9747. var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl);
  9748. var rt = line.indexOf("\r");
  9749. if (rt != -1) {
  9750. result.push(line.slice(0, rt));
  9751. pos += rt + 1;
  9752. } else {
  9753. result.push(line);
  9754. pos = nl + 1;
  9755. }
  9756. }
  9757. return result;
  9758. } : function(string){return string.split(/\r\n?|\n/);};
  9759. var hasSelection = window.getSelection ? function(te) {
  9760. try { return te.selectionStart != te.selectionEnd; }
  9761. catch(e) { return false; }
  9762. } : function(te) {
  9763. try {var range = te.ownerDocument.selection.createRange();}
  9764. catch(e) {}
  9765. if (!range || range.parentElement() != te) return false;
  9766. return range.compareEndPoints("StartToEnd", range) != 0;
  9767. };
  9768. var hasCopyEvent = (function() {
  9769. var e = elt("div");
  9770. if ("oncopy" in e) return true;
  9771. e.setAttribute("oncopy", "return;");
  9772. return typeof e.oncopy == "function";
  9773. })();
  9774. var badZoomedRects = null;
  9775. function hasBadZoomedRects(measure) {
  9776. if (badZoomedRects != null) return badZoomedRects;
  9777. var node = removeChildrenAndAdd(measure, elt("span", "x"));
  9778. var normal = node.getBoundingClientRect();
  9779. var fromRange = range(node, 0, 1).getBoundingClientRect();
  9780. return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1;
  9781. }
  9782. // KEY NAMES
  9783. var keyNames = CodeMirror.keyNames = {
  9784. 3: "Enter", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt",
  9785. 19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End",
  9786. 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert",
  9787. 46: "Delete", 59: ";", 61: "=", 91: "Mod", 92: "Mod", 93: "Mod",
  9788. 106: "*", 107: "=", 109: "-", 110: ".", 111: "/", 127: "Delete",
  9789. 173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\",
  9790. 221: "]", 222: "'", 63232: "Up", 63233: "Down", 63234: "Left", 63235: "Right", 63272: "Delete",
  9791. 63273: "Home", 63275: "End", 63276: "PageUp", 63277: "PageDown", 63302: "Insert"
  9792. };
  9793. (function() {
  9794. // Number keys
  9795. for (var i = 0; i < 10; i++) keyNames[i + 48] = keyNames[i + 96] = String(i);
  9796. // Alphabetic keys
  9797. for (var i = 65; i <= 90; i++) keyNames[i] = String.fromCharCode(i);
  9798. // Function keys
  9799. for (var i = 1; i <= 12; i++) keyNames[i + 111] = keyNames[i + 63235] = "F" + i;
  9800. })();
  9801. // BIDI HELPERS
  9802. function iterateBidiSections(order, from, to, f) {
  9803. if (!order) return f(from, to, "ltr");
  9804. var found = false;
  9805. for (var i = 0; i < order.length; ++i) {
  9806. var part = order[i];
  9807. if (part.from < to && part.to > from || from == to && part.to == from) {
  9808. f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr");
  9809. found = true;
  9810. }
  9811. }
  9812. if (!found) f(from, to, "ltr");
  9813. }
  9814. function bidiLeft(part) { return part.level % 2 ? part.to : part.from; }
  9815. function bidiRight(part) { return part.level % 2 ? part.from : part.to; }
  9816. function lineLeft(line) { var order = getOrder(line); return order ? bidiLeft(order[0]) : 0; }
  9817. function lineRight(line) {
  9818. var order = getOrder(line);
  9819. if (!order) return line.text.length;
  9820. return bidiRight(lst(order));
  9821. }
  9822. function lineStart(cm, lineN) {
  9823. var line = getLine(cm.doc, lineN);
  9824. var visual = visualLine(line);
  9825. if (visual != line) lineN = lineNo(visual);
  9826. var order = getOrder(visual);
  9827. var ch = !order ? 0 : order[0].level % 2 ? lineRight(visual) : lineLeft(visual);
  9828. return Pos(lineN, ch);
  9829. }
  9830. function lineEnd(cm, lineN) {
  9831. var merged, line = getLine(cm.doc, lineN);
  9832. while (merged = collapsedSpanAtEnd(line)) {
  9833. line = merged.find(1, true).line;
  9834. lineN = null;
  9835. }
  9836. var order = getOrder(line);
  9837. var ch = !order ? line.text.length : order[0].level % 2 ? lineLeft(line) : lineRight(line);
  9838. return Pos(lineN == null ? lineNo(line) : lineN, ch);
  9839. }
  9840. function lineStartSmart(cm, pos) {
  9841. var start = lineStart(cm, pos.line);
  9842. var line = getLine(cm.doc, start.line);
  9843. var order = getOrder(line);
  9844. if (!order || order[0].level == 0) {
  9845. var firstNonWS = Math.max(0, line.text.search(/\S/));
  9846. var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch;
  9847. return Pos(start.line, inWS ? 0 : firstNonWS);
  9848. }
  9849. return start;
  9850. }
  9851. function compareBidiLevel(order, a, b) {
  9852. var linedir = order[0].level;
  9853. if (a == linedir) return true;
  9854. if (b == linedir) return false;
  9855. return a < b;
  9856. }
  9857. var bidiOther;
  9858. function getBidiPartAt(order, pos) {
  9859. bidiOther = null;
  9860. for (var i = 0, found; i < order.length; ++i) {
  9861. var cur = order[i];
  9862. if (cur.from < pos && cur.to > pos) return i;
  9863. if ((cur.from == pos || cur.to == pos)) {
  9864. if (found == null) {
  9865. found = i;
  9866. } else if (compareBidiLevel(order, cur.level, order[found].level)) {
  9867. if (cur.from != cur.to) bidiOther = found;
  9868. return i;
  9869. } else {
  9870. if (cur.from != cur.to) bidiOther = i;
  9871. return found;
  9872. }
  9873. }
  9874. }
  9875. return found;
  9876. }
  9877. function moveInLine(line, pos, dir, byUnit) {
  9878. if (!byUnit) return pos + dir;
  9879. do pos += dir;
  9880. while (pos > 0 && isExtendingChar(line.text.charAt(pos)));
  9881. return pos;
  9882. }
  9883. // This is needed in order to move 'visually' through bi-directional
  9884. // text -- i.e., pressing left should make the cursor go left, even
  9885. // when in RTL text. The tricky part is the 'jumps', where RTL and
  9886. // LTR text touch each other. This often requires the cursor offset
  9887. // to move more than one unit, in order to visually move one unit.
  9888. function moveVisually(line, start, dir, byUnit) {
  9889. var bidi = getOrder(line);
  9890. if (!bidi) return moveLogically(line, start, dir, byUnit);
  9891. var pos = getBidiPartAt(bidi, start), part = bidi[pos];
  9892. var target = moveInLine(line, start, part.level % 2 ? -dir : dir, byUnit);
  9893. for (;;) {
  9894. if (target > part.from && target < part.to) return target;
  9895. if (target == part.from || target == part.to) {
  9896. if (getBidiPartAt(bidi, target) == pos) return target;
  9897. part = bidi[pos += dir];
  9898. return (dir > 0) == part.level % 2 ? part.to : part.from;
  9899. } else {
  9900. part = bidi[pos += dir];
  9901. if (!part) return null;
  9902. if ((dir > 0) == part.level % 2)
  9903. target = moveInLine(line, part.to, -1, byUnit);
  9904. else
  9905. target = moveInLine(line, part.from, 1, byUnit);
  9906. }
  9907. }
  9908. }
  9909. function moveLogically(line, start, dir, byUnit) {
  9910. var target = start + dir;
  9911. if (byUnit) while (target > 0 && isExtendingChar(line.text.charAt(target))) target += dir;
  9912. return target < 0 || target > line.text.length ? null : target;
  9913. }
  9914. // Bidirectional ordering algorithm
  9915. // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm
  9916. // that this (partially) implements.
  9917. // One-char codes used for character types:
  9918. // L (L): Left-to-Right
  9919. // R (R): Right-to-Left
  9920. // r (AL): Right-to-Left Arabic
  9921. // 1 (EN): European Number
  9922. // + (ES): European Number Separator
  9923. // % (ET): European Number Terminator
  9924. // n (AN): Arabic Number
  9925. // , (CS): Common Number Separator
  9926. // m (NSM): Non-Spacing Mark
  9927. // b (BN): Boundary Neutral
  9928. // s (B): Paragraph Separator
  9929. // t (S): Segment Separator
  9930. // w (WS): Whitespace
  9931. // N (ON): Other Neutrals
  9932. // Returns null if characters are ordered as they appear
  9933. // (left-to-right), or an array of sections ({from, to, level}
  9934. // objects) in the order in which they occur visually.
  9935. var bidiOrdering = (function() {
  9936. // Character types for codepoints 0 to 0xff
  9937. var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN";
  9938. // Character types for codepoints 0x600 to 0x6ff
  9939. var arabicTypes = "rrrrrrrrrrrr,rNNmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmrrrrrrrnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmNmmmm";
  9940. function charType(code) {
  9941. if (code <= 0xf7) return lowTypes.charAt(code);
  9942. else if (0x590 <= code && code <= 0x5f4) return "R";
  9943. else if (0x600 <= code && code <= 0x6ed) return arabicTypes.charAt(code - 0x600);
  9944. else if (0x6ee <= code && code <= 0x8ac) return "r";
  9945. else if (0x2000 <= code && code <= 0x200b) return "w";
  9946. else if (code == 0x200c) return "b";
  9947. else return "L";
  9948. }
  9949. var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/;
  9950. var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/;
  9951. // Browsers seem to always treat the boundaries of block elements as being L.
  9952. var outerType = "L";
  9953. function BidiSpan(level, from, to) {
  9954. this.level = level;
  9955. this.from = from; this.to = to;
  9956. }
  9957. return function(str) {
  9958. if (!bidiRE.test(str)) return false;
  9959. var len = str.length, types = [];
  9960. for (var i = 0, type; i < len; ++i)
  9961. types.push(type = charType(str.charCodeAt(i)));
  9962. // W1. Examine each non-spacing mark (NSM) in the level run, and
  9963. // change the type of the NSM to the type of the previous
  9964. // character. If the NSM is at the start of the level run, it will
  9965. // get the type of sor.
  9966. for (var i = 0, prev = outerType; i < len; ++i) {
  9967. var type = types[i];
  9968. if (type == "m") types[i] = prev;
  9969. else prev = type;
  9970. }
  9971. // W2. Search backwards from each instance of a European number
  9972. // until the first strong type (R, L, AL, or sor) is found. If an
  9973. // AL is found, change the type of the European number to Arabic
  9974. // number.
  9975. // W3. Change all ALs to R.
  9976. for (var i = 0, cur = outerType; i < len; ++i) {
  9977. var type = types[i];
  9978. if (type == "1" && cur == "r") types[i] = "n";
  9979. else if (isStrong.test(type)) { cur = type; if (type == "r") types[i] = "R"; }
  9980. }
  9981. // W4. A single European separator between two European numbers
  9982. // changes to a European number. A single common separator between
  9983. // two numbers of the same type changes to that type.
  9984. for (var i = 1, prev = types[0]; i < len - 1; ++i) {
  9985. var type = types[i];
  9986. if (type == "+" && prev == "1" && types[i+1] == "1") types[i] = "1";
  9987. else if (type == "," && prev == types[i+1] &&
  9988. (prev == "1" || prev == "n")) types[i] = prev;
  9989. prev = type;
  9990. }
  9991. // W5. A sequence of European terminators adjacent to European
  9992. // numbers changes to all European numbers.
  9993. // W6. Otherwise, separators and terminators change to Other
  9994. // Neutral.
  9995. for (var i = 0; i < len; ++i) {
  9996. var type = types[i];
  9997. if (type == ",") types[i] = "N";
  9998. else if (type == "%") {
  9999. for (var end = i + 1; end < len && types[end] == "%"; ++end) {}
  10000. var replace = (i && types[i-1] == "!") || (end < len && types[end] == "1") ? "1" : "N";
  10001. for (var j = i; j < end; ++j) types[j] = replace;
  10002. i = end - 1;
  10003. }
  10004. }
  10005. // W7. Search backwards from each instance of a European number
  10006. // until the first strong type (R, L, or sor) is found. If an L is
  10007. // found, then change the type of the European number to L.
  10008. for (var i = 0, cur = outerType; i < len; ++i) {
  10009. var type = types[i];
  10010. if (cur == "L" && type == "1") types[i] = "L";
  10011. else if (isStrong.test(type)) cur = type;
  10012. }
  10013. // N1. A sequence of neutrals takes the direction of the
  10014. // surrounding strong text if the text on both sides has the same
  10015. // direction. European and Arabic numbers act as if they were R in
  10016. // terms of their influence on neutrals. Start-of-level-run (sor)
  10017. // and end-of-level-run (eor) are used at level run boundaries.
  10018. // N2. Any remaining neutrals take the embedding direction.
  10019. for (var i = 0; i < len; ++i) {
  10020. if (isNeutral.test(types[i])) {
  10021. for (var end = i + 1; end < len && isNeutral.test(types[end]); ++end) {}
  10022. var before = (i ? types[i-1] : outerType) == "L";
  10023. var after = (end < len ? types[end] : outerType) == "L";
  10024. var replace = before || after ? "L" : "R";
  10025. for (var j = i; j < end; ++j) types[j] = replace;
  10026. i = end - 1;
  10027. }
  10028. }
  10029. // Here we depart from the documented algorithm, in order to avoid
  10030. // building up an actual levels array. Since there are only three
  10031. // levels (0, 1, 2) in an implementation that doesn't take
  10032. // explicit embedding into account, we can build up the order on
  10033. // the fly, without following the level-based algorithm.
  10034. var order = [], m;
  10035. for (var i = 0; i < len;) {
  10036. if (countsAsLeft.test(types[i])) {
  10037. var start = i;
  10038. for (++i; i < len && countsAsLeft.test(types[i]); ++i) {}
  10039. order.push(new BidiSpan(0, start, i));
  10040. } else {
  10041. var pos = i, at = order.length;
  10042. for (++i; i < len && types[i] != "L"; ++i) {}
  10043. for (var j = pos; j < i;) {
  10044. if (countsAsNum.test(types[j])) {
  10045. if (pos < j) order.splice(at, 0, new BidiSpan(1, pos, j));
  10046. var nstart = j;
  10047. for (++j; j < i && countsAsNum.test(types[j]); ++j) {}
  10048. order.splice(at, 0, new BidiSpan(2, nstart, j));
  10049. pos = j;
  10050. } else ++j;
  10051. }
  10052. if (pos < i) order.splice(at, 0, new BidiSpan(1, pos, i));
  10053. }
  10054. }
  10055. if (order[0].level == 1 && (m = str.match(/^\s+/))) {
  10056. order[0].from = m[0].length;
  10057. order.unshift(new BidiSpan(0, 0, m[0].length));
  10058. }
  10059. if (lst(order).level == 1 && (m = str.match(/\s+$/))) {
  10060. lst(order).to -= m[0].length;
  10061. order.push(new BidiSpan(0, len - m[0].length, len));
  10062. }
  10063. if (order[0].level == 2)
  10064. order.unshift(new BidiSpan(1, order[0].to, order[0].to));
  10065. if (order[0].level != lst(order).level)
  10066. order.push(new BidiSpan(order[0].level, len, len));
  10067. return order;
  10068. };
  10069. })();
  10070. // THE END
  10071. CodeMirror.version = "5.17.0";
  10072. return CodeMirror;
  10073. });
  10074. },{}],11:[function(require,module,exports){
  10075. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  10076. // Distributed under an MIT license: http://codemirror.net/LICENSE
  10077. (function(mod) {
  10078. if (typeof exports == "object" && typeof module == "object") // CommonJS
  10079. mod(require("../../lib/codemirror"), require("../markdown/markdown"), require("../../addon/mode/overlay"));
  10080. else if (typeof define == "function" && define.amd) // AMD
  10081. define(["../../lib/codemirror", "../markdown/markdown", "../../addon/mode/overlay"], mod);
  10082. else // Plain browser env
  10083. mod(CodeMirror);
  10084. })(function(CodeMirror) {
  10085. "use strict";
  10086. 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
  10087. CodeMirror.defineMode("gfm", function(config, modeConfig) {
  10088. var codeDepth = 0;
  10089. function blankLine(state) {
  10090. state.code = false;
  10091. return null;
  10092. }
  10093. var gfmOverlay = {
  10094. startState: function() {
  10095. return {
  10096. code: false,
  10097. codeBlock: false,
  10098. ateSpace: false
  10099. };
  10100. },
  10101. copyState: function(s) {
  10102. return {
  10103. code: s.code,
  10104. codeBlock: s.codeBlock,
  10105. ateSpace: s.ateSpace
  10106. };
  10107. },
  10108. token: function(stream, state) {
  10109. state.combineTokens = null;
  10110. // Hack to prevent formatting override inside code blocks (block and inline)
  10111. if (state.codeBlock) {
  10112. if (stream.match(/^```+/)) {
  10113. state.codeBlock = false;
  10114. return null;
  10115. }
  10116. stream.skipToEnd();
  10117. return null;
  10118. }
  10119. if (stream.sol()) {
  10120. state.code = false;
  10121. }
  10122. if (stream.sol() && stream.match(/^```+/)) {
  10123. stream.skipToEnd();
  10124. state.codeBlock = true;
  10125. return null;
  10126. }
  10127. // If this block is changed, it may need to be updated in Markdown mode
  10128. if (stream.peek() === '`') {
  10129. stream.next();
  10130. var before = stream.pos;
  10131. stream.eatWhile('`');
  10132. var difference = 1 + stream.pos - before;
  10133. if (!state.code) {
  10134. codeDepth = difference;
  10135. state.code = true;
  10136. } else {
  10137. if (difference === codeDepth) { // Must be exact
  10138. state.code = false;
  10139. }
  10140. }
  10141. return null;
  10142. } else if (state.code) {
  10143. stream.next();
  10144. return null;
  10145. }
  10146. // Check if space. If so, links can be formatted later on
  10147. if (stream.eatSpace()) {
  10148. state.ateSpace = true;
  10149. return null;
  10150. }
  10151. if (stream.sol() || state.ateSpace) {
  10152. state.ateSpace = false;
  10153. if (modeConfig.gitHubSpice !== false) {
  10154. if(stream.match(/^(?:[a-zA-Z0-9\-_]+\/)?(?:[a-zA-Z0-9\-_]+@)?(?:[a-f0-9]{7,40}\b)/)) {
  10155. // User/Project@SHA
  10156. // User@SHA
  10157. // SHA
  10158. state.combineTokens = true;
  10159. return "link";
  10160. } else if (stream.match(/^(?:[a-zA-Z0-9\-_]+\/)?(?:[a-zA-Z0-9\-_]+)?#[0-9]+\b/)) {
  10161. // User/Project#Num
  10162. // User#Num
  10163. // #Num
  10164. state.combineTokens = true;
  10165. return "link";
  10166. }
  10167. }
  10168. }
  10169. if (stream.match(urlRE) &&
  10170. stream.string.slice(stream.start - 2, stream.start) != "](" &&
  10171. (stream.start == 0 || /\W/.test(stream.string.charAt(stream.start - 1)))) {
  10172. // URLs
  10173. // Taken from http://daringfireball.net/2010/07/improved_regex_for_matching_urls
  10174. // And then (issue #1160) simplified to make it not crash the Chrome Regexp engine
  10175. // And then limited url schemes to the CommonMark list, so foo:bar isn't matched as a URL
  10176. state.combineTokens = true;
  10177. return "link";
  10178. }
  10179. stream.next();
  10180. return null;
  10181. },
  10182. blankLine: blankLine
  10183. };
  10184. var markdownConfig = {
  10185. underscoresBreakWords: false,
  10186. taskLists: true,
  10187. fencedCodeBlocks: '```',
  10188. strikethrough: true
  10189. };
  10190. for (var attr in modeConfig) {
  10191. markdownConfig[attr] = modeConfig[attr];
  10192. }
  10193. markdownConfig.name = "markdown";
  10194. return CodeMirror.overlayMode(CodeMirror.getMode(config, markdownConfig), gfmOverlay);
  10195. }, "markdown");
  10196. CodeMirror.defineMIME("text/x-gfm", "gfm");
  10197. });
  10198. },{"../../addon/mode/overlay":8,"../../lib/codemirror":10,"../markdown/markdown":12}],12:[function(require,module,exports){
  10199. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  10200. // Distributed under an MIT license: http://codemirror.net/LICENSE
  10201. (function(mod) {
  10202. if (typeof exports == "object" && typeof module == "object") // CommonJS
  10203. mod(require("../../lib/codemirror"), require("../xml/xml"), require("../meta"));
  10204. else if (typeof define == "function" && define.amd) // AMD
  10205. define(["../../lib/codemirror", "../xml/xml", "../meta"], mod);
  10206. else // Plain browser env
  10207. mod(CodeMirror);
  10208. })(function(CodeMirror) {
  10209. "use strict";
  10210. CodeMirror.defineMode("markdown", function(cmCfg, modeCfg) {
  10211. var htmlMode = CodeMirror.getMode(cmCfg, "text/html");
  10212. var htmlModeMissing = htmlMode.name == "null"
  10213. function getMode(name) {
  10214. if (CodeMirror.findModeByName) {
  10215. var found = CodeMirror.findModeByName(name);
  10216. if (found) name = found.mime || found.mimes[0];
  10217. }
  10218. var mode = CodeMirror.getMode(cmCfg, name);
  10219. return mode.name == "null" ? null : mode;
  10220. }
  10221. // Should characters that affect highlighting be highlighted separate?
  10222. // Does not include characters that will be output (such as `1.` and `-` for lists)
  10223. if (modeCfg.highlightFormatting === undefined)
  10224. modeCfg.highlightFormatting = false;
  10225. // Maximum number of nested blockquotes. Set to 0 for infinite nesting.
  10226. // Excess `>` will emit `error` token.
  10227. if (modeCfg.maxBlockquoteDepth === undefined)
  10228. modeCfg.maxBlockquoteDepth = 0;
  10229. // Should underscores in words open/close em/strong?
  10230. if (modeCfg.underscoresBreakWords === undefined)
  10231. modeCfg.underscoresBreakWords = true;
  10232. // Use `fencedCodeBlocks` to configure fenced code blocks. false to
  10233. // disable, string to specify a precise regexp that the fence should
  10234. // match, and true to allow three or more backticks or tildes (as
  10235. // per CommonMark).
  10236. // Turn on task lists? ("- [ ] " and "- [x] ")
  10237. if (modeCfg.taskLists === undefined) modeCfg.taskLists = false;
  10238. // Turn on strikethrough syntax
  10239. if (modeCfg.strikethrough === undefined)
  10240. modeCfg.strikethrough = false;
  10241. // Allow token types to be overridden by user-provided token types.
  10242. if (modeCfg.tokenTypeOverrides === undefined)
  10243. modeCfg.tokenTypeOverrides = {};
  10244. var tokenTypes = {
  10245. header: "header",
  10246. code: "comment",
  10247. quote: "quote",
  10248. list1: "variable-2",
  10249. list2: "variable-3",
  10250. list3: "keyword",
  10251. hr: "hr",
  10252. image: "image",
  10253. imageAltText: "image-alt-text",
  10254. imageMarker: "image-marker",
  10255. formatting: "formatting",
  10256. linkInline: "link",
  10257. linkEmail: "link",
  10258. linkText: "link",
  10259. linkHref: "string",
  10260. em: "em",
  10261. strong: "strong",
  10262. strikethrough: "strikethrough"
  10263. };
  10264. for (var tokenType in tokenTypes) {
  10265. if (tokenTypes.hasOwnProperty(tokenType) && modeCfg.tokenTypeOverrides[tokenType]) {
  10266. tokenTypes[tokenType] = modeCfg.tokenTypeOverrides[tokenType];
  10267. }
  10268. }
  10269. var hrRE = /^([*\-_])(?:\s*\1){2,}\s*$/
  10270. , ulRE = /^[*\-+]\s+/
  10271. , olRE = /^[0-9]+([.)])\s+/
  10272. , taskListRE = /^\[(x| )\](?=\s)/ // Must follow ulRE or olRE
  10273. , atxHeaderRE = modeCfg.allowAtxHeaderWithoutSpace ? /^(#+)/ : /^(#+)(?: |$)/
  10274. , setextHeaderRE = /^ *(?:\={1,}|-{1,})\s*$/
  10275. , textRE = /^[^#!\[\]*_\\<>` "'(~]+/
  10276. , fencedCodeRE = new RegExp("^(" + (modeCfg.fencedCodeBlocks === true ? "~~~+|```+" : modeCfg.fencedCodeBlocks) +
  10277. ")[ \\t]*([\\w+#\-]*)");
  10278. function switchInline(stream, state, f) {
  10279. state.f = state.inline = f;
  10280. return f(stream, state);
  10281. }
  10282. function switchBlock(stream, state, f) {
  10283. state.f = state.block = f;
  10284. return f(stream, state);
  10285. }
  10286. function lineIsEmpty(line) {
  10287. return !line || !/\S/.test(line.string)
  10288. }
  10289. // Blocks
  10290. function blankLine(state) {
  10291. // Reset linkTitle state
  10292. state.linkTitle = false;
  10293. // Reset EM state
  10294. state.em = false;
  10295. // Reset STRONG state
  10296. state.strong = false;
  10297. // Reset strikethrough state
  10298. state.strikethrough = false;
  10299. // Reset state.quote
  10300. state.quote = 0;
  10301. // Reset state.indentedCode
  10302. state.indentedCode = false;
  10303. if (htmlModeMissing && state.f == htmlBlock) {
  10304. state.f = inlineNormal;
  10305. state.block = blockNormal;
  10306. }
  10307. // Reset state.trailingSpace
  10308. state.trailingSpace = 0;
  10309. state.trailingSpaceNewLine = false;
  10310. // Mark this line as blank
  10311. state.prevLine = state.thisLine
  10312. state.thisLine = null
  10313. return null;
  10314. }
  10315. function blockNormal(stream, state) {
  10316. var sol = stream.sol();
  10317. var prevLineIsList = state.list !== false,
  10318. prevLineIsIndentedCode = state.indentedCode;
  10319. state.indentedCode = false;
  10320. if (prevLineIsList) {
  10321. if (state.indentationDiff >= 0) { // Continued list
  10322. if (state.indentationDiff < 4) { // Only adjust indentation if *not* a code block
  10323. state.indentation -= state.indentationDiff;
  10324. }
  10325. state.list = null;
  10326. } else if (state.indentation > 0) {
  10327. state.list = null;
  10328. } else { // No longer a list
  10329. state.list = false;
  10330. }
  10331. }
  10332. var match = null;
  10333. if (state.indentationDiff >= 4) {
  10334. stream.skipToEnd();
  10335. if (prevLineIsIndentedCode || lineIsEmpty(state.prevLine)) {
  10336. state.indentation -= 4;
  10337. state.indentedCode = true;
  10338. return tokenTypes.code;
  10339. } else {
  10340. return null;
  10341. }
  10342. } else if (stream.eatSpace()) {
  10343. return null;
  10344. } else if ((match = stream.match(atxHeaderRE)) && match[1].length <= 6) {
  10345. state.header = match[1].length;
  10346. if (modeCfg.highlightFormatting) state.formatting = "header";
  10347. state.f = state.inline;
  10348. return getType(state);
  10349. } else if (!lineIsEmpty(state.prevLine) && !state.quote && !prevLineIsList &&
  10350. !prevLineIsIndentedCode && (match = stream.match(setextHeaderRE))) {
  10351. state.header = match[0].charAt(0) == '=' ? 1 : 2;
  10352. if (modeCfg.highlightFormatting) state.formatting = "header";
  10353. state.f = state.inline;
  10354. return getType(state);
  10355. } else if (stream.eat('>')) {
  10356. state.quote = sol ? 1 : state.quote + 1;
  10357. if (modeCfg.highlightFormatting) state.formatting = "quote";
  10358. stream.eatSpace();
  10359. return getType(state);
  10360. } else if (stream.peek() === '[') {
  10361. return switchInline(stream, state, footnoteLink);
  10362. } else if (stream.match(hrRE, true)) {
  10363. state.hr = true;
  10364. return tokenTypes.hr;
  10365. } else if ((lineIsEmpty(state.prevLine) || prevLineIsList) && (stream.match(ulRE, false) || stream.match(olRE, false))) {
  10366. var listType = null;
  10367. if (stream.match(ulRE, true)) {
  10368. listType = 'ul';
  10369. } else {
  10370. stream.match(olRE, true);
  10371. listType = 'ol';
  10372. }
  10373. state.indentation = stream.column() + stream.current().length;
  10374. state.list = true;
  10375. // While this list item's marker's indentation
  10376. // is less than the deepest list item's content's indentation,
  10377. // pop the deepest list item indentation off the stack.
  10378. while (state.listStack && stream.column() < state.listStack[state.listStack.length - 1]) {
  10379. state.listStack.pop();
  10380. }
  10381. // Add this list item's content's indentation to the stack
  10382. state.listStack.push(state.indentation);
  10383. if (modeCfg.taskLists && stream.match(taskListRE, false)) {
  10384. state.taskList = true;
  10385. }
  10386. state.f = state.inline;
  10387. if (modeCfg.highlightFormatting) state.formatting = ["list", "list-" + listType];
  10388. return getType(state);
  10389. } else if (modeCfg.fencedCodeBlocks && (match = stream.match(fencedCodeRE, true))) {
  10390. state.fencedChars = match[1]
  10391. // try switching mode
  10392. state.localMode = getMode(match[2]);
  10393. if (state.localMode) state.localState = CodeMirror.startState(state.localMode);
  10394. state.f = state.block = local;
  10395. if (modeCfg.highlightFormatting) state.formatting = "code-block";
  10396. state.code = -1
  10397. return getType(state);
  10398. }
  10399. return switchInline(stream, state, state.inline);
  10400. }
  10401. function htmlBlock(stream, state) {
  10402. var style = htmlMode.token(stream, state.htmlState);
  10403. if (!htmlModeMissing) {
  10404. var inner = CodeMirror.innerMode(htmlMode, state.htmlState)
  10405. if ((inner.mode.name == "xml" && inner.state.tagStart === null &&
  10406. (!inner.state.context && inner.state.tokenize.isInText)) ||
  10407. (state.md_inside && stream.current().indexOf(">") > -1)) {
  10408. state.f = inlineNormal;
  10409. state.block = blockNormal;
  10410. state.htmlState = null;
  10411. }
  10412. }
  10413. return style;
  10414. }
  10415. function local(stream, state) {
  10416. if (state.fencedChars && stream.match(state.fencedChars, false)) {
  10417. state.localMode = state.localState = null;
  10418. state.f = state.block = leavingLocal;
  10419. return null;
  10420. } else if (state.localMode) {
  10421. return state.localMode.token(stream, state.localState);
  10422. } else {
  10423. stream.skipToEnd();
  10424. return tokenTypes.code;
  10425. }
  10426. }
  10427. function leavingLocal(stream, state) {
  10428. stream.match(state.fencedChars);
  10429. state.block = blockNormal;
  10430. state.f = inlineNormal;
  10431. state.fencedChars = null;
  10432. if (modeCfg.highlightFormatting) state.formatting = "code-block";
  10433. state.code = 1
  10434. var returnType = getType(state);
  10435. state.code = 0
  10436. return returnType;
  10437. }
  10438. // Inline
  10439. function getType(state) {
  10440. var styles = [];
  10441. if (state.formatting) {
  10442. styles.push(tokenTypes.formatting);
  10443. if (typeof state.formatting === "string") state.formatting = [state.formatting];
  10444. for (var i = 0; i < state.formatting.length; i++) {
  10445. styles.push(tokenTypes.formatting + "-" + state.formatting[i]);
  10446. if (state.formatting[i] === "header") {
  10447. styles.push(tokenTypes.formatting + "-" + state.formatting[i] + "-" + state.header);
  10448. }
  10449. // Add `formatting-quote` and `formatting-quote-#` for blockquotes
  10450. // Add `error` instead if the maximum blockquote nesting depth is passed
  10451. if (state.formatting[i] === "quote") {
  10452. if (!modeCfg.maxBlockquoteDepth || modeCfg.maxBlockquoteDepth >= state.quote) {
  10453. styles.push(tokenTypes.formatting + "-" + state.formatting[i] + "-" + state.quote);
  10454. } else {
  10455. styles.push("error");
  10456. }
  10457. }
  10458. }
  10459. }
  10460. if (state.taskOpen) {
  10461. styles.push("meta");
  10462. return styles.length ? styles.join(' ') : null;
  10463. }
  10464. if (state.taskClosed) {
  10465. styles.push("property");
  10466. return styles.length ? styles.join(' ') : null;
  10467. }
  10468. if (state.linkHref) {
  10469. styles.push(tokenTypes.linkHref, "url");
  10470. } else { // Only apply inline styles to non-url text
  10471. if (state.strong) { styles.push(tokenTypes.strong); }
  10472. if (state.em) { styles.push(tokenTypes.em); }
  10473. if (state.strikethrough) { styles.push(tokenTypes.strikethrough); }
  10474. if (state.linkText) { styles.push(tokenTypes.linkText); }
  10475. if (state.code) { styles.push(tokenTypes.code); }
  10476. if (state.image) { styles.push(tokenTypes.image); }
  10477. if (state.imageAltText) { styles.push(tokenTypes.imageAltText, "link"); }
  10478. if (state.imageMarker) { styles.push(tokenTypes.imageMarker); }
  10479. }
  10480. if (state.header) { styles.push(tokenTypes.header, tokenTypes.header + "-" + state.header); }
  10481. if (state.quote) {
  10482. styles.push(tokenTypes.quote);
  10483. // Add `quote-#` where the maximum for `#` is modeCfg.maxBlockquoteDepth
  10484. if (!modeCfg.maxBlockquoteDepth || modeCfg.maxBlockquoteDepth >= state.quote) {
  10485. styles.push(tokenTypes.quote + "-" + state.quote);
  10486. } else {
  10487. styles.push(tokenTypes.quote + "-" + modeCfg.maxBlockquoteDepth);
  10488. }
  10489. }
  10490. if (state.list !== false) {
  10491. var listMod = (state.listStack.length - 1) % 3;
  10492. if (!listMod) {
  10493. styles.push(tokenTypes.list1);
  10494. } else if (listMod === 1) {
  10495. styles.push(tokenTypes.list2);
  10496. } else {
  10497. styles.push(tokenTypes.list3);
  10498. }
  10499. }
  10500. if (state.trailingSpaceNewLine) {
  10501. styles.push("trailing-space-new-line");
  10502. } else if (state.trailingSpace) {
  10503. styles.push("trailing-space-" + (state.trailingSpace % 2 ? "a" : "b"));
  10504. }
  10505. return styles.length ? styles.join(' ') : null;
  10506. }
  10507. function handleText(stream, state) {
  10508. if (stream.match(textRE, true)) {
  10509. return getType(state);
  10510. }
  10511. return undefined;
  10512. }
  10513. function inlineNormal(stream, state) {
  10514. var style = state.text(stream, state);
  10515. if (typeof style !== 'undefined')
  10516. return style;
  10517. if (state.list) { // List marker (*, +, -, 1., etc)
  10518. state.list = null;
  10519. return getType(state);
  10520. }
  10521. if (state.taskList) {
  10522. var taskOpen = stream.match(taskListRE, true)[1] !== "x";
  10523. if (taskOpen) state.taskOpen = true;
  10524. else state.taskClosed = true;
  10525. if (modeCfg.highlightFormatting) state.formatting = "task";
  10526. state.taskList = false;
  10527. return getType(state);
  10528. }
  10529. state.taskOpen = false;
  10530. state.taskClosed = false;
  10531. if (state.header && stream.match(/^#+$/, true)) {
  10532. if (modeCfg.highlightFormatting) state.formatting = "header";
  10533. return getType(state);
  10534. }
  10535. // Get sol() value now, before character is consumed
  10536. var sol = stream.sol();
  10537. var ch = stream.next();
  10538. // Matches link titles present on next line
  10539. if (state.linkTitle) {
  10540. state.linkTitle = false;
  10541. var matchCh = ch;
  10542. if (ch === '(') {
  10543. matchCh = ')';
  10544. }
  10545. matchCh = (matchCh+'').replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1");
  10546. var regex = '^\\s*(?:[^' + matchCh + '\\\\]+|\\\\\\\\|\\\\.)' + matchCh;
  10547. if (stream.match(new RegExp(regex), true)) {
  10548. return tokenTypes.linkHref;
  10549. }
  10550. }
  10551. // If this block is changed, it may need to be updated in GFM mode
  10552. if (ch === '`') {
  10553. var previousFormatting = state.formatting;
  10554. if (modeCfg.highlightFormatting) state.formatting = "code";
  10555. stream.eatWhile('`');
  10556. var count = stream.current().length
  10557. if (state.code == 0) {
  10558. state.code = count
  10559. return getType(state)
  10560. } else if (count == state.code) { // Must be exact
  10561. var t = getType(state)
  10562. state.code = 0
  10563. return t
  10564. } else {
  10565. state.formatting = previousFormatting
  10566. return getType(state)
  10567. }
  10568. } else if (state.code) {
  10569. return getType(state);
  10570. }
  10571. if (ch === '\\') {
  10572. stream.next();
  10573. if (modeCfg.highlightFormatting) {
  10574. var type = getType(state);
  10575. var formattingEscape = tokenTypes.formatting + "-escape";
  10576. return type ? type + " " + formattingEscape : formattingEscape;
  10577. }
  10578. }
  10579. if (ch === '!' && stream.match(/\[[^\]]*\] ?(?:\(|\[)/, false)) {
  10580. state.imageMarker = true;
  10581. state.image = true;
  10582. if (modeCfg.highlightFormatting) state.formatting = "image";
  10583. return getType(state);
  10584. }
  10585. if (ch === '[' && state.imageMarker) {
  10586. state.imageMarker = false;
  10587. state.imageAltText = true
  10588. if (modeCfg.highlightFormatting) state.formatting = "image";
  10589. return getType(state);
  10590. }
  10591. if (ch === ']' && state.imageAltText) {
  10592. if (modeCfg.highlightFormatting) state.formatting = "image";
  10593. var type = getType(state);
  10594. state.imageAltText = false;
  10595. state.image = false;
  10596. state.inline = state.f = linkHref;
  10597. return type;
  10598. }
  10599. if (ch === '[' && stream.match(/[^\]]*\](\(.*\)| ?\[.*?\])/, false) && !state.image) {
  10600. state.linkText = true;
  10601. if (modeCfg.highlightFormatting) state.formatting = "link";
  10602. return getType(state);
  10603. }
  10604. if (ch === ']' && state.linkText && stream.match(/\(.*?\)| ?\[.*?\]/, false)) {
  10605. if (modeCfg.highlightFormatting) state.formatting = "link";
  10606. var type = getType(state);
  10607. state.linkText = false;
  10608. state.inline = state.f = linkHref;
  10609. return type;
  10610. }
  10611. if (ch === '<' && stream.match(/^(https?|ftps?):\/\/(?:[^\\>]|\\.)+>/, false)) {
  10612. state.f = state.inline = linkInline;
  10613. if (modeCfg.highlightFormatting) state.formatting = "link";
  10614. var type = getType(state);
  10615. if (type){
  10616. type += " ";
  10617. } else {
  10618. type = "";
  10619. }
  10620. return type + tokenTypes.linkInline;
  10621. }
  10622. if (ch === '<' && stream.match(/^[^> \\]+@(?:[^\\>]|\\.)+>/, false)) {
  10623. state.f = state.inline = linkInline;
  10624. if (modeCfg.highlightFormatting) state.formatting = "link";
  10625. var type = getType(state);
  10626. if (type){
  10627. type += " ";
  10628. } else {
  10629. type = "";
  10630. }
  10631. return type + tokenTypes.linkEmail;
  10632. }
  10633. if (ch === '<' && stream.match(/^(!--|\w)/, false)) {
  10634. var end = stream.string.indexOf(">", stream.pos);
  10635. if (end != -1) {
  10636. var atts = stream.string.substring(stream.start, end);
  10637. if (/markdown\s*=\s*('|"){0,1}1('|"){0,1}/.test(atts)) state.md_inside = true;
  10638. }
  10639. stream.backUp(1);
  10640. state.htmlState = CodeMirror.startState(htmlMode);
  10641. return switchBlock(stream, state, htmlBlock);
  10642. }
  10643. if (ch === '<' && stream.match(/^\/\w*?>/)) {
  10644. state.md_inside = false;
  10645. return "tag";
  10646. }
  10647. var ignoreUnderscore = false;
  10648. if (!modeCfg.underscoresBreakWords) {
  10649. if (ch === '_' && stream.peek() !== '_' && stream.match(/(\w)/, false)) {
  10650. var prevPos = stream.pos - 2;
  10651. if (prevPos >= 0) {
  10652. var prevCh = stream.string.charAt(prevPos);
  10653. if (prevCh !== '_' && prevCh.match(/(\w)/, false)) {
  10654. ignoreUnderscore = true;
  10655. }
  10656. }
  10657. }
  10658. }
  10659. if (ch === '*' || (ch === '_' && !ignoreUnderscore)) {
  10660. if (sol && stream.peek() === ' ') {
  10661. // Do nothing, surrounded by newline and space
  10662. } else if (state.strong === ch && stream.eat(ch)) { // Remove STRONG
  10663. if (modeCfg.highlightFormatting) state.formatting = "strong";
  10664. var t = getType(state);
  10665. state.strong = false;
  10666. return t;
  10667. } else if (!state.strong && stream.eat(ch)) { // Add STRONG
  10668. state.strong = ch;
  10669. if (modeCfg.highlightFormatting) state.formatting = "strong";
  10670. return getType(state);
  10671. } else if (state.em === ch) { // Remove EM
  10672. if (modeCfg.highlightFormatting) state.formatting = "em";
  10673. var t = getType(state);
  10674. state.em = false;
  10675. return t;
  10676. } else if (!state.em) { // Add EM
  10677. state.em = ch;
  10678. if (modeCfg.highlightFormatting) state.formatting = "em";
  10679. return getType(state);
  10680. }
  10681. } else if (ch === ' ') {
  10682. if (stream.eat('*') || stream.eat('_')) { // Probably surrounded by spaces
  10683. if (stream.peek() === ' ') { // Surrounded by spaces, ignore
  10684. return getType(state);
  10685. } else { // Not surrounded by spaces, back up pointer
  10686. stream.backUp(1);
  10687. }
  10688. }
  10689. }
  10690. if (modeCfg.strikethrough) {
  10691. if (ch === '~' && stream.eatWhile(ch)) {
  10692. if (state.strikethrough) {// Remove strikethrough
  10693. if (modeCfg.highlightFormatting) state.formatting = "strikethrough";
  10694. var t = getType(state);
  10695. state.strikethrough = false;
  10696. return t;
  10697. } else if (stream.match(/^[^\s]/, false)) {// Add strikethrough
  10698. state.strikethrough = true;
  10699. if (modeCfg.highlightFormatting) state.formatting = "strikethrough";
  10700. return getType(state);
  10701. }
  10702. } else if (ch === ' ') {
  10703. if (stream.match(/^~~/, true)) { // Probably surrounded by space
  10704. if (stream.peek() === ' ') { // Surrounded by spaces, ignore
  10705. return getType(state);
  10706. } else { // Not surrounded by spaces, back up pointer
  10707. stream.backUp(2);
  10708. }
  10709. }
  10710. }
  10711. }
  10712. if (ch === ' ') {
  10713. if (stream.match(/ +$/, false)) {
  10714. state.trailingSpace++;
  10715. } else if (state.trailingSpace) {
  10716. state.trailingSpaceNewLine = true;
  10717. }
  10718. }
  10719. return getType(state);
  10720. }
  10721. function linkInline(stream, state) {
  10722. var ch = stream.next();
  10723. if (ch === ">") {
  10724. state.f = state.inline = inlineNormal;
  10725. if (modeCfg.highlightFormatting) state.formatting = "link";
  10726. var type = getType(state);
  10727. if (type){
  10728. type += " ";
  10729. } else {
  10730. type = "";
  10731. }
  10732. return type + tokenTypes.linkInline;
  10733. }
  10734. stream.match(/^[^>]+/, true);
  10735. return tokenTypes.linkInline;
  10736. }
  10737. function linkHref(stream, state) {
  10738. // Check if space, and return NULL if so (to avoid marking the space)
  10739. if(stream.eatSpace()){
  10740. return null;
  10741. }
  10742. var ch = stream.next();
  10743. if (ch === '(' || ch === '[') {
  10744. state.f = state.inline = getLinkHrefInside(ch === "(" ? ")" : "]", 0);
  10745. if (modeCfg.highlightFormatting) state.formatting = "link-string";
  10746. state.linkHref = true;
  10747. return getType(state);
  10748. }
  10749. return 'error';
  10750. }
  10751. var linkRE = {
  10752. ")": /^(?:[^\\\(\)]|\\.|\((?:[^\\\(\)]|\\.)*\))*?(?=\))/,
  10753. "]": /^(?:[^\\\[\]]|\\.|\[(?:[^\\\[\\]]|\\.)*\])*?(?=\])/
  10754. }
  10755. function getLinkHrefInside(endChar) {
  10756. return function(stream, state) {
  10757. var ch = stream.next();
  10758. if (ch === endChar) {
  10759. state.f = state.inline = inlineNormal;
  10760. if (modeCfg.highlightFormatting) state.formatting = "link-string";
  10761. var returnState = getType(state);
  10762. state.linkHref = false;
  10763. return returnState;
  10764. }
  10765. stream.match(linkRE[endChar])
  10766. state.linkHref = true;
  10767. return getType(state);
  10768. };
  10769. }
  10770. function footnoteLink(stream, state) {
  10771. if (stream.match(/^([^\]\\]|\\.)*\]:/, false)) {
  10772. state.f = footnoteLinkInside;
  10773. stream.next(); // Consume [
  10774. if (modeCfg.highlightFormatting) state.formatting = "link";
  10775. state.linkText = true;
  10776. return getType(state);
  10777. }
  10778. return switchInline(stream, state, inlineNormal);
  10779. }
  10780. function footnoteLinkInside(stream, state) {
  10781. if (stream.match(/^\]:/, true)) {
  10782. state.f = state.inline = footnoteUrl;
  10783. if (modeCfg.highlightFormatting) state.formatting = "link";
  10784. var returnType = getType(state);
  10785. state.linkText = false;
  10786. return returnType;
  10787. }
  10788. stream.match(/^([^\]\\]|\\.)+/, true);
  10789. return tokenTypes.linkText;
  10790. }
  10791. function footnoteUrl(stream, state) {
  10792. // Check if space, and return NULL if so (to avoid marking the space)
  10793. if(stream.eatSpace()){
  10794. return null;
  10795. }
  10796. // Match URL
  10797. stream.match(/^[^\s]+/, true);
  10798. // Check for link title
  10799. if (stream.peek() === undefined) { // End of line, set flag to check next line
  10800. state.linkTitle = true;
  10801. } else { // More content on line, check if link title
  10802. stream.match(/^(?:\s+(?:"(?:[^"\\]|\\\\|\\.)+"|'(?:[^'\\]|\\\\|\\.)+'|\((?:[^)\\]|\\\\|\\.)+\)))?/, true);
  10803. }
  10804. state.f = state.inline = inlineNormal;
  10805. return tokenTypes.linkHref + " url";
  10806. }
  10807. var mode = {
  10808. startState: function() {
  10809. return {
  10810. f: blockNormal,
  10811. prevLine: null,
  10812. thisLine: null,
  10813. block: blockNormal,
  10814. htmlState: null,
  10815. indentation: 0,
  10816. inline: inlineNormal,
  10817. text: handleText,
  10818. formatting: false,
  10819. linkText: false,
  10820. linkHref: false,
  10821. linkTitle: false,
  10822. code: 0,
  10823. em: false,
  10824. strong: false,
  10825. header: 0,
  10826. hr: false,
  10827. taskList: false,
  10828. list: false,
  10829. listStack: [],
  10830. quote: 0,
  10831. trailingSpace: 0,
  10832. trailingSpaceNewLine: false,
  10833. strikethrough: false,
  10834. fencedChars: null
  10835. };
  10836. },
  10837. copyState: function(s) {
  10838. return {
  10839. f: s.f,
  10840. prevLine: s.prevLine,
  10841. thisLine: s.thisLine,
  10842. block: s.block,
  10843. htmlState: s.htmlState && CodeMirror.copyState(htmlMode, s.htmlState),
  10844. indentation: s.indentation,
  10845. localMode: s.localMode,
  10846. localState: s.localMode ? CodeMirror.copyState(s.localMode, s.localState) : null,
  10847. inline: s.inline,
  10848. text: s.text,
  10849. formatting: false,
  10850. linkTitle: s.linkTitle,
  10851. code: s.code,
  10852. em: s.em,
  10853. strong: s.strong,
  10854. strikethrough: s.strikethrough,
  10855. header: s.header,
  10856. hr: s.hr,
  10857. taskList: s.taskList,
  10858. list: s.list,
  10859. listStack: s.listStack.slice(0),
  10860. quote: s.quote,
  10861. indentedCode: s.indentedCode,
  10862. trailingSpace: s.trailingSpace,
  10863. trailingSpaceNewLine: s.trailingSpaceNewLine,
  10864. md_inside: s.md_inside,
  10865. fencedChars: s.fencedChars
  10866. };
  10867. },
  10868. token: function(stream, state) {
  10869. // Reset state.formatting
  10870. state.formatting = false;
  10871. if (stream != state.thisLine) {
  10872. var forceBlankLine = state.header || state.hr;
  10873. // Reset state.header and state.hr
  10874. state.header = 0;
  10875. state.hr = false;
  10876. if (stream.match(/^\s*$/, true) || forceBlankLine) {
  10877. blankLine(state);
  10878. if (!forceBlankLine) return null
  10879. state.prevLine = null
  10880. }
  10881. state.prevLine = state.thisLine
  10882. state.thisLine = stream
  10883. // Reset state.taskList
  10884. state.taskList = false;
  10885. // Reset state.trailingSpace
  10886. state.trailingSpace = 0;
  10887. state.trailingSpaceNewLine = false;
  10888. state.f = state.block;
  10889. var indentation = stream.match(/^\s*/, true)[0].replace(/\t/g, ' ').length;
  10890. state.indentationDiff = Math.min(indentation - state.indentation, 4);
  10891. state.indentation = state.indentation + state.indentationDiff;
  10892. if (indentation > 0) return null;
  10893. }
  10894. return state.f(stream, state);
  10895. },
  10896. innerMode: function(state) {
  10897. if (state.block == htmlBlock) return {state: state.htmlState, mode: htmlMode};
  10898. if (state.localState) return {state: state.localState, mode: state.localMode};
  10899. return {state: state, mode: mode};
  10900. },
  10901. blankLine: blankLine,
  10902. getType: getType,
  10903. fold: "markdown"
  10904. };
  10905. return mode;
  10906. }, "xml");
  10907. CodeMirror.defineMIME("text/x-markdown", "markdown");
  10908. });
  10909. },{"../../lib/codemirror":10,"../meta":13,"../xml/xml":14}],13:[function(require,module,exports){
  10910. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  10911. // Distributed under an MIT license: http://codemirror.net/LICENSE
  10912. (function(mod) {
  10913. if (typeof exports == "object" && typeof module == "object") // CommonJS
  10914. mod(require("../lib/codemirror"));
  10915. else if (typeof define == "function" && define.amd) // AMD
  10916. define(["../lib/codemirror"], mod);
  10917. else // Plain browser env
  10918. mod(CodeMirror);
  10919. })(function(CodeMirror) {
  10920. "use strict";
  10921. CodeMirror.modeInfo = [
  10922. {name: "APL", mime: "text/apl", mode: "apl", ext: ["dyalog", "apl"]},
  10923. {name: "PGP", mimes: ["application/pgp", "application/pgp-keys", "application/pgp-signature"], mode: "asciiarmor", ext: ["pgp"]},
  10924. {name: "ASN.1", mime: "text/x-ttcn-asn", mode: "asn.1", ext: ["asn", "asn1"]},
  10925. {name: "Asterisk", mime: "text/x-asterisk", mode: "asterisk", file: /^extensions\.conf$/i},
  10926. {name: "Brainfuck", mime: "text/x-brainfuck", mode: "brainfuck", ext: ["b", "bf"]},
  10927. {name: "C", mime: "text/x-csrc", mode: "clike", ext: ["c", "h"]},
  10928. {name: "C++", mime: "text/x-c++src", mode: "clike", ext: ["cpp", "c++", "cc", "cxx", "hpp", "h++", "hh", "hxx"], alias: ["cpp"]},
  10929. {name: "Cobol", mime: "text/x-cobol", mode: "cobol", ext: ["cob", "cpy"]},
  10930. {name: "C#", mime: "text/x-csharp", mode: "clike", ext: ["cs"], alias: ["csharp"]},
  10931. {name: "Clojure", mime: "text/x-clojure", mode: "clojure", ext: ["clj", "cljc", "cljx"]},
  10932. {name: "ClojureScript", mime: "text/x-clojurescript", mode: "clojure", ext: ["cljs"]},
  10933. {name: "Closure Stylesheets (GSS)", mime: "text/x-gss", mode: "css", ext: ["gss"]},
  10934. {name: "CMake", mime: "text/x-cmake", mode: "cmake", ext: ["cmake", "cmake.in"], file: /^CMakeLists.txt$/},
  10935. {name: "CoffeeScript", mime: "text/x-coffeescript", mode: "coffeescript", ext: ["coffee"], alias: ["coffee", "coffee-script"]},
  10936. {name: "Common Lisp", mime: "text/x-common-lisp", mode: "commonlisp", ext: ["cl", "lisp", "el"], alias: ["lisp"]},
  10937. {name: "Cypher", mime: "application/x-cypher-query", mode: "cypher", ext: ["cyp", "cypher"]},
  10938. {name: "Cython", mime: "text/x-cython", mode: "python", ext: ["pyx", "pxd", "pxi"]},
  10939. {name: "Crystal", mime: "text/x-crystal", mode: "crystal", ext: ["cr"]},
  10940. {name: "CSS", mime: "text/css", mode: "css", ext: ["css"]},
  10941. {name: "CQL", mime: "text/x-cassandra", mode: "sql", ext: ["cql"]},
  10942. {name: "D", mime: "text/x-d", mode: "d", ext: ["d"]},
  10943. {name: "Dart", mimes: ["application/dart", "text/x-dart"], mode: "dart", ext: ["dart"]},
  10944. {name: "diff", mime: "text/x-diff", mode: "diff", ext: ["diff", "patch"]},
  10945. {name: "Django", mime: "text/x-django", mode: "django"},
  10946. {name: "Dockerfile", mime: "text/x-dockerfile", mode: "dockerfile", file: /^Dockerfile$/},
  10947. {name: "DTD", mime: "application/xml-dtd", mode: "dtd", ext: ["dtd"]},
  10948. {name: "Dylan", mime: "text/x-dylan", mode: "dylan", ext: ["dylan", "dyl", "intr"]},
  10949. {name: "EBNF", mime: "text/x-ebnf", mode: "ebnf"},
  10950. {name: "ECL", mime: "text/x-ecl", mode: "ecl", ext: ["ecl"]},
  10951. {name: "edn", mime: "application/edn", mode: "clojure", ext: ["edn"]},
  10952. {name: "Eiffel", mime: "text/x-eiffel", mode: "eiffel", ext: ["e"]},
  10953. {name: "Elm", mime: "text/x-elm", mode: "elm", ext: ["elm"]},
  10954. {name: "Embedded Javascript", mime: "application/x-ejs", mode: "htmlembedded", ext: ["ejs"]},
  10955. {name: "Embedded Ruby", mime: "application/x-erb", mode: "htmlembedded", ext: ["erb"]},
  10956. {name: "Erlang", mime: "text/x-erlang", mode: "erlang", ext: ["erl"]},
  10957. {name: "Factor", mime: "text/x-factor", mode: "factor", ext: ["factor"]},
  10958. {name: "FCL", mime: "text/x-fcl", mode: "fcl"},
  10959. {name: "Forth", mime: "text/x-forth", mode: "forth", ext: ["forth", "fth", "4th"]},
  10960. {name: "Fortran", mime: "text/x-fortran", mode: "fortran", ext: ["f", "for", "f77", "f90"]},
  10961. {name: "F#", mime: "text/x-fsharp", mode: "mllike", ext: ["fs"], alias: ["fsharp"]},
  10962. {name: "Gas", mime: "text/x-gas", mode: "gas", ext: ["s"]},
  10963. {name: "Gherkin", mime: "text/x-feature", mode: "gherkin", ext: ["feature"]},
  10964. {name: "GitHub Flavored Markdown", mime: "text/x-gfm", mode: "gfm", file: /^(readme|contributing|history).md$/i},
  10965. {name: "Go", mime: "text/x-go", mode: "go", ext: ["go"]},
  10966. {name: "Groovy", mime: "text/x-groovy", mode: "groovy", ext: ["groovy", "gradle"]},
  10967. {name: "HAML", mime: "text/x-haml", mode: "haml", ext: ["haml"]},
  10968. {name: "Haskell", mime: "text/x-haskell", mode: "haskell", ext: ["hs"]},
  10969. {name: "Haskell (Literate)", mime: "text/x-literate-haskell", mode: "haskell-literate", ext: ["lhs"]},
  10970. {name: "Haxe", mime: "text/x-haxe", mode: "haxe", ext: ["hx"]},
  10971. {name: "HXML", mime: "text/x-hxml", mode: "haxe", ext: ["hxml"]},
  10972. {name: "ASP.NET", mime: "application/x-aspx", mode: "htmlembedded", ext: ["aspx"], alias: ["asp", "aspx"]},
  10973. {name: "HTML", mime: "text/html", mode: "htmlmixed", ext: ["html", "htm"], alias: ["xhtml"]},
  10974. {name: "HTTP", mime: "message/http", mode: "http"},
  10975. {name: "IDL", mime: "text/x-idl", mode: "idl", ext: ["pro"]},
  10976. {name: "Jade", mime: "text/x-jade", mode: "jade", ext: ["jade"]},
  10977. {name: "Java", mime: "text/x-java", mode: "clike", ext: ["java"]},
  10978. {name: "Java Server Pages", mime: "application/x-jsp", mode: "htmlembedded", ext: ["jsp"], alias: ["jsp"]},
  10979. {name: "JavaScript", mimes: ["text/javascript", "text/ecmascript", "application/javascript", "application/x-javascript", "application/ecmascript"],
  10980. mode: "javascript", ext: ["js"], alias: ["ecmascript", "js", "node"]},
  10981. {name: "JSON", mimes: ["application/json", "application/x-json"], mode: "javascript", ext: ["json", "map"], alias: ["json5"]},
  10982. {name: "JSON-LD", mime: "application/ld+json", mode: "javascript", ext: ["jsonld"], alias: ["jsonld"]},
  10983. {name: "JSX", mime: "text/jsx", mode: "jsx", ext: ["jsx"]},
  10984. {name: "Jinja2", mime: "null", mode: "jinja2"},
  10985. {name: "Julia", mime: "text/x-julia", mode: "julia", ext: ["jl"]},
  10986. {name: "Kotlin", mime: "text/x-kotlin", mode: "clike", ext: ["kt"]},
  10987. {name: "LESS", mime: "text/x-less", mode: "css", ext: ["less"]},
  10988. {name: "LiveScript", mime: "text/x-livescript", mode: "livescript", ext: ["ls"], alias: ["ls"]},
  10989. {name: "Lua", mime: "text/x-lua", mode: "lua", ext: ["lua"]},
  10990. {name: "Markdown", mime: "text/x-markdown", mode: "markdown", ext: ["markdown", "md", "mkd"]},
  10991. {name: "mIRC", mime: "text/mirc", mode: "mirc"},
  10992. {name: "MariaDB SQL", mime: "text/x-mariadb", mode: "sql"},
  10993. {name: "Mathematica", mime: "text/x-mathematica", mode: "mathematica", ext: ["m", "nb"]},
  10994. {name: "Modelica", mime: "text/x-modelica", mode: "modelica", ext: ["mo"]},
  10995. {name: "MUMPS", mime: "text/x-mumps", mode: "mumps", ext: ["mps"]},
  10996. {name: "MS SQL", mime: "text/x-mssql", mode: "sql"},
  10997. {name: "mbox", mime: "application/mbox", mode: "mbox", ext: ["mbox"]},
  10998. {name: "MySQL", mime: "text/x-mysql", mode: "sql"},
  10999. {name: "Nginx", mime: "text/x-nginx-conf", mode: "nginx", file: /nginx.*\.conf$/i},
  11000. {name: "NSIS", mime: "text/x-nsis", mode: "nsis", ext: ["nsh", "nsi"]},
  11001. {name: "NTriples", mime: "text/n-triples", mode: "ntriples", ext: ["nt"]},
  11002. {name: "Objective C", mime: "text/x-objectivec", mode: "clike", ext: ["m", "mm"], alias: ["objective-c", "objc"]},
  11003. {name: "OCaml", mime: "text/x-ocaml", mode: "mllike", ext: ["ml", "mli", "mll", "mly"]},
  11004. {name: "Octave", mime: "text/x-octave", mode: "octave", ext: ["m"]},
  11005. {name: "Oz", mime: "text/x-oz", mode: "oz", ext: ["oz"]},
  11006. {name: "Pascal", mime: "text/x-pascal", mode: "pascal", ext: ["p", "pas"]},
  11007. {name: "PEG.js", mime: "null", mode: "pegjs", ext: ["jsonld"]},
  11008. {name: "Perl", mime: "text/x-perl", mode: "perl", ext: ["pl", "pm"]},
  11009. {name: "PHP", mime: "application/x-httpd-php", mode: "php", ext: ["php", "php3", "php4", "php5", "phtml"]},
  11010. {name: "Pig", mime: "text/x-pig", mode: "pig", ext: ["pig"]},
  11011. {name: "Plain Text", mime: "text/plain", mode: "null", ext: ["txt", "text", "conf", "def", "list", "log"]},
  11012. {name: "PLSQL", mime: "text/x-plsql", mode: "sql", ext: ["pls"]},
  11013. {name: "PowerShell", mime: "application/x-powershell", mode: "powershell", ext: ["ps1", "psd1", "psm1"]},
  11014. {name: "Properties files", mime: "text/x-properties", mode: "properties", ext: ["properties", "ini", "in"], alias: ["ini", "properties"]},
  11015. {name: "ProtoBuf", mime: "text/x-protobuf", mode: "protobuf", ext: ["proto"]},
  11016. {name: "Python", mime: "text/x-python", mode: "python", ext: ["BUILD", "bzl", "py", "pyw"], file: /^(BUCK|BUILD)$/},
  11017. {name: "Puppet", mime: "text/x-puppet", mode: "puppet", ext: ["pp"]},
  11018. {name: "Q", mime: "text/x-q", mode: "q", ext: ["q"]},
  11019. {name: "R", mime: "text/x-rsrc", mode: "r", ext: ["r"], alias: ["rscript"]},
  11020. {name: "reStructuredText", mime: "text/x-rst", mode: "rst", ext: ["rst"], alias: ["rst"]},
  11021. {name: "RPM Changes", mime: "text/x-rpm-changes", mode: "rpm"},
  11022. {name: "RPM Spec", mime: "text/x-rpm-spec", mode: "rpm", ext: ["spec"]},
  11023. {name: "Ruby", mime: "text/x-ruby", mode: "ruby", ext: ["rb"], alias: ["jruby", "macruby", "rake", "rb", "rbx"]},
  11024. {name: "Rust", mime: "text/x-rustsrc", mode: "rust", ext: ["rs"]},
  11025. {name: "SAS", mime: "text/x-sas", mode: "sas", ext: ["sas"]},
  11026. {name: "Sass", mime: "text/x-sass", mode: "sass", ext: ["sass"]},
  11027. {name: "Scala", mime: "text/x-scala", mode: "clike", ext: ["scala"]},
  11028. {name: "Scheme", mime: "text/x-scheme", mode: "scheme", ext: ["scm", "ss"]},
  11029. {name: "SCSS", mime: "text/x-scss", mode: "css", ext: ["scss"]},
  11030. {name: "Shell", mime: "text/x-sh", mode: "shell", ext: ["sh", "ksh", "bash"], alias: ["bash", "sh", "zsh"], file: /^PKGBUILD$/},
  11031. {name: "Sieve", mime: "application/sieve", mode: "sieve", ext: ["siv", "sieve"]},
  11032. {name: "Slim", mimes: ["text/x-slim", "application/x-slim"], mode: "slim", ext: ["slim"]},
  11033. {name: "Smalltalk", mime: "text/x-stsrc", mode: "smalltalk", ext: ["st"]},
  11034. {name: "Smarty", mime: "text/x-smarty", mode: "smarty", ext: ["tpl"]},
  11035. {name: "Solr", mime: "text/x-solr", mode: "solr"},
  11036. {name: "Soy", mime: "text/x-soy", mode: "soy", ext: ["soy"], alias: ["closure template"]},
  11037. {name: "SPARQL", mime: "application/sparql-query", mode: "sparql", ext: ["rq", "sparql"], alias: ["sparul"]},
  11038. {name: "Spreadsheet", mime: "text/x-spreadsheet", mode: "spreadsheet", alias: ["excel", "formula"]},
  11039. {name: "SQL", mime: "text/x-sql", mode: "sql", ext: ["sql"]},
  11040. {name: "Squirrel", mime: "text/x-squirrel", mode: "clike", ext: ["nut"]},
  11041. {name: "Swift", mime: "text/x-swift", mode: "swift", ext: ["swift"]},
  11042. {name: "sTeX", mime: "text/x-stex", mode: "stex"},
  11043. {name: "LaTeX", mime: "text/x-latex", mode: "stex", ext: ["text", "ltx"], alias: ["tex"]},
  11044. {name: "SystemVerilog", mime: "text/x-systemverilog", mode: "verilog", ext: ["v"]},
  11045. {name: "Tcl", mime: "text/x-tcl", mode: "tcl", ext: ["tcl"]},
  11046. {name: "Textile", mime: "text/x-textile", mode: "textile", ext: ["textile"]},
  11047. {name: "TiddlyWiki ", mime: "text/x-tiddlywiki", mode: "tiddlywiki"},
  11048. {name: "Tiki wiki", mime: "text/tiki", mode: "tiki"},
  11049. {name: "TOML", mime: "text/x-toml", mode: "toml", ext: ["toml"]},
  11050. {name: "Tornado", mime: "text/x-tornado", mode: "tornado"},
  11051. {name: "troff", mime: "text/troff", mode: "troff", ext: ["1", "2", "3", "4", "5", "6", "7", "8", "9"]},
  11052. {name: "TTCN", mime: "text/x-ttcn", mode: "ttcn", ext: ["ttcn", "ttcn3", "ttcnpp"]},
  11053. {name: "TTCN_CFG", mime: "text/x-ttcn-cfg", mode: "ttcn-cfg", ext: ["cfg"]},
  11054. {name: "Turtle", mime: "text/turtle", mode: "turtle", ext: ["ttl"]},
  11055. {name: "TypeScript", mime: "application/typescript", mode: "javascript", ext: ["ts"], alias: ["ts"]},
  11056. {name: "Twig", mime: "text/x-twig", mode: "twig"},
  11057. {name: "Web IDL", mime: "text/x-webidl", mode: "webidl", ext: ["webidl"]},
  11058. {name: "VB.NET", mime: "text/x-vb", mode: "vb", ext: ["vb"]},
  11059. {name: "VBScript", mime: "text/vbscript", mode: "vbscript", ext: ["vbs"]},
  11060. {name: "Velocity", mime: "text/velocity", mode: "velocity", ext: ["vtl"]},
  11061. {name: "Verilog", mime: "text/x-verilog", mode: "verilog", ext: ["v"]},
  11062. {name: "VHDL", mime: "text/x-vhdl", mode: "vhdl", ext: ["vhd", "vhdl"]},
  11063. {name: "XML", mimes: ["application/xml", "text/xml"], mode: "xml", ext: ["xml", "xsl", "xsd"], alias: ["rss", "wsdl", "xsd"]},
  11064. {name: "XQuery", mime: "application/xquery", mode: "xquery", ext: ["xy", "xquery"]},
  11065. {name: "Yacas", mime: "text/x-yacas", mode: "yacas", ext: ["ys"]},
  11066. {name: "YAML", mime: "text/x-yaml", mode: "yaml", ext: ["yaml", "yml"], alias: ["yml"]},
  11067. {name: "Z80", mime: "text/x-z80", mode: "z80", ext: ["z80"]},
  11068. {name: "mscgen", mime: "text/x-mscgen", mode: "mscgen", ext: ["mscgen", "mscin", "msc"]},
  11069. {name: "xu", mime: "text/x-xu", mode: "mscgen", ext: ["xu"]},
  11070. {name: "msgenny", mime: "text/x-msgenny", mode: "mscgen", ext: ["msgenny"]}
  11071. ];
  11072. // Ensure all modes have a mime property for backwards compatibility
  11073. for (var i = 0; i < CodeMirror.modeInfo.length; i++) {
  11074. var info = CodeMirror.modeInfo[i];
  11075. if (info.mimes) info.mime = info.mimes[0];
  11076. }
  11077. CodeMirror.findModeByMIME = function(mime) {
  11078. mime = mime.toLowerCase();
  11079. for (var i = 0; i < CodeMirror.modeInfo.length; i++) {
  11080. var info = CodeMirror.modeInfo[i];
  11081. if (info.mime == mime) return info;
  11082. if (info.mimes) for (var j = 0; j < info.mimes.length; j++)
  11083. if (info.mimes[j] == mime) return info;
  11084. }
  11085. };
  11086. CodeMirror.findModeByExtension = function(ext) {
  11087. for (var i = 0; i < CodeMirror.modeInfo.length; i++) {
  11088. var info = CodeMirror.modeInfo[i];
  11089. if (info.ext) for (var j = 0; j < info.ext.length; j++)
  11090. if (info.ext[j] == ext) return info;
  11091. }
  11092. };
  11093. CodeMirror.findModeByFileName = function(filename) {
  11094. for (var i = 0; i < CodeMirror.modeInfo.length; i++) {
  11095. var info = CodeMirror.modeInfo[i];
  11096. if (info.file && info.file.test(filename)) return info;
  11097. }
  11098. var dot = filename.lastIndexOf(".");
  11099. var ext = dot > -1 && filename.substring(dot + 1, filename.length);
  11100. if (ext) return CodeMirror.findModeByExtension(ext);
  11101. };
  11102. CodeMirror.findModeByName = function(name) {
  11103. name = name.toLowerCase();
  11104. for (var i = 0; i < CodeMirror.modeInfo.length; i++) {
  11105. var info = CodeMirror.modeInfo[i];
  11106. if (info.name.toLowerCase() == name) return info;
  11107. if (info.alias) for (var j = 0; j < info.alias.length; j++)
  11108. if (info.alias[j].toLowerCase() == name) return info;
  11109. }
  11110. };
  11111. });
  11112. },{"../lib/codemirror":10}],14:[function(require,module,exports){
  11113. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  11114. // Distributed under an MIT license: http://codemirror.net/LICENSE
  11115. (function(mod) {
  11116. if (typeof exports == "object" && typeof module == "object") // CommonJS
  11117. mod(require("../../lib/codemirror"));
  11118. else if (typeof define == "function" && define.amd) // AMD
  11119. define(["../../lib/codemirror"], mod);
  11120. else // Plain browser env
  11121. mod(CodeMirror);
  11122. })(function(CodeMirror) {
  11123. "use strict";
  11124. var htmlConfig = {
  11125. autoSelfClosers: {'area': true, 'base': true, 'br': true, 'col': true, 'command': true,
  11126. 'embed': true, 'frame': true, 'hr': true, 'img': true, 'input': true,
  11127. 'keygen': true, 'link': true, 'meta': true, 'param': true, 'source': true,
  11128. 'track': true, 'wbr': true, 'menuitem': true},
  11129. implicitlyClosed: {'dd': true, 'li': true, 'optgroup': true, 'option': true, 'p': true,
  11130. 'rp': true, 'rt': true, 'tbody': true, 'td': true, 'tfoot': true,
  11131. 'th': true, 'tr': true},
  11132. contextGrabbers: {
  11133. 'dd': {'dd': true, 'dt': true},
  11134. 'dt': {'dd': true, 'dt': true},
  11135. 'li': {'li': true},
  11136. 'option': {'option': true, 'optgroup': true},
  11137. 'optgroup': {'optgroup': true},
  11138. 'p': {'address': true, 'article': true, 'aside': true, 'blockquote': true, 'dir': true,
  11139. 'div': true, 'dl': true, 'fieldset': true, 'footer': true, 'form': true,
  11140. 'h1': true, 'h2': true, 'h3': true, 'h4': true, 'h5': true, 'h6': true,
  11141. 'header': true, 'hgroup': true, 'hr': true, 'menu': true, 'nav': true, 'ol': true,
  11142. 'p': true, 'pre': true, 'section': true, 'table': true, 'ul': true},
  11143. 'rp': {'rp': true, 'rt': true},
  11144. 'rt': {'rp': true, 'rt': true},
  11145. 'tbody': {'tbody': true, 'tfoot': true},
  11146. 'td': {'td': true, 'th': true},
  11147. 'tfoot': {'tbody': true},
  11148. 'th': {'td': true, 'th': true},
  11149. 'thead': {'tbody': true, 'tfoot': true},
  11150. 'tr': {'tr': true}
  11151. },
  11152. doNotIndent: {"pre": true},
  11153. allowUnquoted: true,
  11154. allowMissing: true,
  11155. caseFold: true
  11156. }
  11157. var xmlConfig = {
  11158. autoSelfClosers: {},
  11159. implicitlyClosed: {},
  11160. contextGrabbers: {},
  11161. doNotIndent: {},
  11162. allowUnquoted: false,
  11163. allowMissing: false,
  11164. caseFold: false
  11165. }
  11166. CodeMirror.defineMode("xml", function(editorConf, config_) {
  11167. var indentUnit = editorConf.indentUnit
  11168. var config = {}
  11169. var defaults = config_.htmlMode ? htmlConfig : xmlConfig
  11170. for (var prop in defaults) config[prop] = defaults[prop]
  11171. for (var prop in config_) config[prop] = config_[prop]
  11172. // Return variables for tokenizers
  11173. var type, setStyle;
  11174. function inText(stream, state) {
  11175. function chain(parser) {
  11176. state.tokenize = parser;
  11177. return parser(stream, state);
  11178. }
  11179. var ch = stream.next();
  11180. if (ch == "<") {
  11181. if (stream.eat("!")) {
  11182. if (stream.eat("[")) {
  11183. if (stream.match("CDATA[")) return chain(inBlock("atom", "]]>"));
  11184. else return null;
  11185. } else if (stream.match("--")) {
  11186. return chain(inBlock("comment", "-->"));
  11187. } else if (stream.match("DOCTYPE", true, true)) {
  11188. stream.eatWhile(/[\w\._\-]/);
  11189. return chain(doctype(1));
  11190. } else {
  11191. return null;
  11192. }
  11193. } else if (stream.eat("?")) {
  11194. stream.eatWhile(/[\w\._\-]/);
  11195. state.tokenize = inBlock("meta", "?>");
  11196. return "meta";
  11197. } else {
  11198. type = stream.eat("/") ? "closeTag" : "openTag";
  11199. state.tokenize = inTag;
  11200. return "tag bracket";
  11201. }
  11202. } else if (ch == "&") {
  11203. var ok;
  11204. if (stream.eat("#")) {
  11205. if (stream.eat("x")) {
  11206. ok = stream.eatWhile(/[a-fA-F\d]/) && stream.eat(";");
  11207. } else {
  11208. ok = stream.eatWhile(/[\d]/) && stream.eat(";");
  11209. }
  11210. } else {
  11211. ok = stream.eatWhile(/[\w\.\-:]/) && stream.eat(";");
  11212. }
  11213. return ok ? "atom" : "error";
  11214. } else {
  11215. stream.eatWhile(/[^&<]/);
  11216. return null;
  11217. }
  11218. }
  11219. inText.isInText = true;
  11220. function inTag(stream, state) {
  11221. var ch = stream.next();
  11222. if (ch == ">" || (ch == "/" && stream.eat(">"))) {
  11223. state.tokenize = inText;
  11224. type = ch == ">" ? "endTag" : "selfcloseTag";
  11225. return "tag bracket";
  11226. } else if (ch == "=") {
  11227. type = "equals";
  11228. return null;
  11229. } else if (ch == "<") {
  11230. state.tokenize = inText;
  11231. state.state = baseState;
  11232. state.tagName = state.tagStart = null;
  11233. var next = state.tokenize(stream, state);
  11234. return next ? next + " tag error" : "tag error";
  11235. } else if (/[\'\"]/.test(ch)) {
  11236. state.tokenize = inAttribute(ch);
  11237. state.stringStartCol = stream.column();
  11238. return state.tokenize(stream, state);
  11239. } else {
  11240. stream.match(/^[^\s\u00a0=<>\"\']*[^\s\u00a0=<>\"\'\/]/);
  11241. return "word";
  11242. }
  11243. }
  11244. function inAttribute(quote) {
  11245. var closure = function(stream, state) {
  11246. while (!stream.eol()) {
  11247. if (stream.next() == quote) {
  11248. state.tokenize = inTag;
  11249. break;
  11250. }
  11251. }
  11252. return "string";
  11253. };
  11254. closure.isInAttribute = true;
  11255. return closure;
  11256. }
  11257. function inBlock(style, terminator) {
  11258. return function(stream, state) {
  11259. while (!stream.eol()) {
  11260. if (stream.match(terminator)) {
  11261. state.tokenize = inText;
  11262. break;
  11263. }
  11264. stream.next();
  11265. }
  11266. return style;
  11267. };
  11268. }
  11269. function doctype(depth) {
  11270. return function(stream, state) {
  11271. var ch;
  11272. while ((ch = stream.next()) != null) {
  11273. if (ch == "<") {
  11274. state.tokenize = doctype(depth + 1);
  11275. return state.tokenize(stream, state);
  11276. } else if (ch == ">") {
  11277. if (depth == 1) {
  11278. state.tokenize = inText;
  11279. break;
  11280. } else {
  11281. state.tokenize = doctype(depth - 1);
  11282. return state.tokenize(stream, state);
  11283. }
  11284. }
  11285. }
  11286. return "meta";
  11287. };
  11288. }
  11289. function Context(state, tagName, startOfLine) {
  11290. this.prev = state.context;
  11291. this.tagName = tagName;
  11292. this.indent = state.indented;
  11293. this.startOfLine = startOfLine;
  11294. if (config.doNotIndent.hasOwnProperty(tagName) || (state.context && state.context.noIndent))
  11295. this.noIndent = true;
  11296. }
  11297. function popContext(state) {
  11298. if (state.context) state.context = state.context.prev;
  11299. }
  11300. function maybePopContext(state, nextTagName) {
  11301. var parentTagName;
  11302. while (true) {
  11303. if (!state.context) {
  11304. return;
  11305. }
  11306. parentTagName = state.context.tagName;
  11307. if (!config.contextGrabbers.hasOwnProperty(parentTagName) ||
  11308. !config.contextGrabbers[parentTagName].hasOwnProperty(nextTagName)) {
  11309. return;
  11310. }
  11311. popContext(state);
  11312. }
  11313. }
  11314. function baseState(type, stream, state) {
  11315. if (type == "openTag") {
  11316. state.tagStart = stream.column();
  11317. return tagNameState;
  11318. } else if (type == "closeTag") {
  11319. return closeTagNameState;
  11320. } else {
  11321. return baseState;
  11322. }
  11323. }
  11324. function tagNameState(type, stream, state) {
  11325. if (type == "word") {
  11326. state.tagName = stream.current();
  11327. setStyle = "tag";
  11328. return attrState;
  11329. } else {
  11330. setStyle = "error";
  11331. return tagNameState;
  11332. }
  11333. }
  11334. function closeTagNameState(type, stream, state) {
  11335. if (type == "word") {
  11336. var tagName = stream.current();
  11337. if (state.context && state.context.tagName != tagName &&
  11338. config.implicitlyClosed.hasOwnProperty(state.context.tagName))
  11339. popContext(state);
  11340. if ((state.context && state.context.tagName == tagName) || config.matchClosing === false) {
  11341. setStyle = "tag";
  11342. return closeState;
  11343. } else {
  11344. setStyle = "tag error";
  11345. return closeStateErr;
  11346. }
  11347. } else {
  11348. setStyle = "error";
  11349. return closeStateErr;
  11350. }
  11351. }
  11352. function closeState(type, _stream, state) {
  11353. if (type != "endTag") {
  11354. setStyle = "error";
  11355. return closeState;
  11356. }
  11357. popContext(state);
  11358. return baseState;
  11359. }
  11360. function closeStateErr(type, stream, state) {
  11361. setStyle = "error";
  11362. return closeState(type, stream, state);
  11363. }
  11364. function attrState(type, _stream, state) {
  11365. if (type == "word") {
  11366. setStyle = "attribute";
  11367. return attrEqState;
  11368. } else if (type == "endTag" || type == "selfcloseTag") {
  11369. var tagName = state.tagName, tagStart = state.tagStart;
  11370. state.tagName = state.tagStart = null;
  11371. if (type == "selfcloseTag" ||
  11372. config.autoSelfClosers.hasOwnProperty(tagName)) {
  11373. maybePopContext(state, tagName);
  11374. } else {
  11375. maybePopContext(state, tagName);
  11376. state.context = new Context(state, tagName, tagStart == state.indented);
  11377. }
  11378. return baseState;
  11379. }
  11380. setStyle = "error";
  11381. return attrState;
  11382. }
  11383. function attrEqState(type, stream, state) {
  11384. if (type == "equals") return attrValueState;
  11385. if (!config.allowMissing) setStyle = "error";
  11386. return attrState(type, stream, state);
  11387. }
  11388. function attrValueState(type, stream, state) {
  11389. if (type == "string") return attrContinuedState;
  11390. if (type == "word" && config.allowUnquoted) {setStyle = "string"; return attrState;}
  11391. setStyle = "error";
  11392. return attrState(type, stream, state);
  11393. }
  11394. function attrContinuedState(type, stream, state) {
  11395. if (type == "string") return attrContinuedState;
  11396. return attrState(type, stream, state);
  11397. }
  11398. return {
  11399. startState: function(baseIndent) {
  11400. var state = {tokenize: inText,
  11401. state: baseState,
  11402. indented: baseIndent || 0,
  11403. tagName: null, tagStart: null,
  11404. context: null}
  11405. if (baseIndent != null) state.baseIndent = baseIndent
  11406. return state
  11407. },
  11408. token: function(stream, state) {
  11409. if (!state.tagName && stream.sol())
  11410. state.indented = stream.indentation();
  11411. if (stream.eatSpace()) return null;
  11412. type = null;
  11413. var style = state.tokenize(stream, state);
  11414. if ((style || type) && style != "comment") {
  11415. setStyle = null;
  11416. state.state = state.state(type || style, stream, state);
  11417. if (setStyle)
  11418. style = setStyle == "error" ? style + " error" : setStyle;
  11419. }
  11420. return style;
  11421. },
  11422. indent: function(state, textAfter, fullLine) {
  11423. var context = state.context;
  11424. // Indent multi-line strings (e.g. css).
  11425. if (state.tokenize.isInAttribute) {
  11426. if (state.tagStart == state.indented)
  11427. return state.stringStartCol + 1;
  11428. else
  11429. return state.indented + indentUnit;
  11430. }
  11431. if (context && context.noIndent) return CodeMirror.Pass;
  11432. if (state.tokenize != inTag && state.tokenize != inText)
  11433. return fullLine ? fullLine.match(/^(\s*)/)[0].length : 0;
  11434. // Indent the starts of attribute names.
  11435. if (state.tagName) {
  11436. if (config.multilineTagIndentPastTag !== false)
  11437. return state.tagStart + state.tagName.length + 2;
  11438. else
  11439. return state.tagStart + indentUnit * (config.multilineTagIndentFactor || 1);
  11440. }
  11441. if (config.alignCDATA && /<!\[CDATA\[/.test(textAfter)) return 0;
  11442. var tagAfter = textAfter && /^<(\/)?([\w_:\.-]*)/.exec(textAfter);
  11443. if (tagAfter && tagAfter[1]) { // Closing tag spotted
  11444. while (context) {
  11445. if (context.tagName == tagAfter[2]) {
  11446. context = context.prev;
  11447. break;
  11448. } else if (config.implicitlyClosed.hasOwnProperty(context.tagName)) {
  11449. context = context.prev;
  11450. } else {
  11451. break;
  11452. }
  11453. }
  11454. } else if (tagAfter) { // Opening tag spotted
  11455. while (context) {
  11456. var grabbers = config.contextGrabbers[context.tagName];
  11457. if (grabbers && grabbers.hasOwnProperty(tagAfter[2]))
  11458. context = context.prev;
  11459. else
  11460. break;
  11461. }
  11462. }
  11463. while (context && context.prev && !context.startOfLine)
  11464. context = context.prev;
  11465. if (context) return context.indent + indentUnit;
  11466. else return state.baseIndent || 0;
  11467. },
  11468. electricInput: /<\/[\s\w:]+>$/,
  11469. blockCommentStart: "<!--",
  11470. blockCommentEnd: "-->",
  11471. configuration: config.htmlMode ? "html" : "xml",
  11472. helperType: config.htmlMode ? "html" : "xml",
  11473. skipAttribute: function(state) {
  11474. if (state.state == attrValueState)
  11475. state.state = attrState
  11476. }
  11477. };
  11478. });
  11479. CodeMirror.defineMIME("text/xml", "xml");
  11480. CodeMirror.defineMIME("application/xml", "xml");
  11481. if (!CodeMirror.mimeModes.hasOwnProperty("text/html"))
  11482. CodeMirror.defineMIME("text/html", {name: "xml", htmlMode: true});
  11483. });
  11484. },{"../../lib/codemirror":10}],15:[function(require,module,exports){
  11485. exports.read = function (buffer, offset, isLE, mLen, nBytes) {
  11486. var e, m
  11487. var eLen = nBytes * 8 - mLen - 1
  11488. var eMax = (1 << eLen) - 1
  11489. var eBias = eMax >> 1
  11490. var nBits = -7
  11491. var i = isLE ? (nBytes - 1) : 0
  11492. var d = isLE ? -1 : 1
  11493. var s = buffer[offset + i]
  11494. i += d
  11495. e = s & ((1 << (-nBits)) - 1)
  11496. s >>= (-nBits)
  11497. nBits += eLen
  11498. for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
  11499. m = e & ((1 << (-nBits)) - 1)
  11500. e >>= (-nBits)
  11501. nBits += mLen
  11502. for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
  11503. if (e === 0) {
  11504. e = 1 - eBias
  11505. } else if (e === eMax) {
  11506. return m ? NaN : ((s ? -1 : 1) * Infinity)
  11507. } else {
  11508. m = m + Math.pow(2, mLen)
  11509. e = e - eBias
  11510. }
  11511. return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
  11512. }
  11513. exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
  11514. var e, m, c
  11515. var eLen = nBytes * 8 - mLen - 1
  11516. var eMax = (1 << eLen) - 1
  11517. var eBias = eMax >> 1
  11518. var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
  11519. var i = isLE ? 0 : (nBytes - 1)
  11520. var d = isLE ? 1 : -1
  11521. var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
  11522. value = Math.abs(value)
  11523. if (isNaN(value) || value === Infinity) {
  11524. m = isNaN(value) ? 1 : 0
  11525. e = eMax
  11526. } else {
  11527. e = Math.floor(Math.log(value) / Math.LN2)
  11528. if (value * (c = Math.pow(2, -e)) < 1) {
  11529. e--
  11530. c *= 2
  11531. }
  11532. if (e + eBias >= 1) {
  11533. value += rt / c
  11534. } else {
  11535. value += rt * Math.pow(2, 1 - eBias)
  11536. }
  11537. if (value * c >= 2) {
  11538. e++
  11539. c /= 2
  11540. }
  11541. if (e + eBias >= eMax) {
  11542. m = 0
  11543. e = eMax
  11544. } else if (e + eBias >= 1) {
  11545. m = (value * c - 1) * Math.pow(2, mLen)
  11546. e = e + eBias
  11547. } else {
  11548. m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
  11549. e = 0
  11550. }
  11551. }
  11552. for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
  11553. e = (e << mLen) | m
  11554. eLen += mLen
  11555. for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
  11556. buffer[offset + i - d] |= s * 128
  11557. }
  11558. },{}],16:[function(require,module,exports){
  11559. var toString = {}.toString;
  11560. module.exports = Array.isArray || function (arr) {
  11561. return toString.call(arr) == '[object Array]';
  11562. };
  11563. },{}],17:[function(require,module,exports){
  11564. (function (global){
  11565. /**
  11566. * marked - a markdown parser
  11567. * Copyright (c) 2011-2014, Christopher Jeffrey. (MIT Licensed)
  11568. * https://github.com/chjj/marked
  11569. */
  11570. ;(function() {
  11571. /**
  11572. * Block-Level Grammar
  11573. */
  11574. var block = {
  11575. newline: /^\n+/,
  11576. code: /^( {4}[^\n]+\n*)+/,
  11577. fences: noop,
  11578. hr: /^( *[-*_]){3,} *(?:\n+|$)/,
  11579. heading: /^ *(#{1,6}) *([^\n]+?) *#* *(?:\n+|$)/,
  11580. nptable: noop,
  11581. lheading: /^([^\n]+)\n *(=|-){2,} *(?:\n+|$)/,
  11582. blockquote: /^( *>[^\n]+(\n(?!def)[^\n]+)*\n*)+/,
  11583. list: /^( *)(bull) [\s\S]+?(?:hr|def|\n{2,}(?! )(?!\1bull )\n*|\s*$)/,
  11584. html: /^ *(?:comment *(?:\n|\s*$)|closed *(?:\n{2,}|\s*$)|closing *(?:\n{2,}|\s*$))/,
  11585. def: /^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +["(]([^\n]+)[")])? *(?:\n+|$)/,
  11586. table: noop,
  11587. paragraph: /^((?:[^\n]+\n?(?!hr|heading|lheading|blockquote|tag|def))+)\n*/,
  11588. text: /^[^\n]+/
  11589. };
  11590. block.bullet = /(?:[*+-]|\d+\.)/;
  11591. block.item = /^( *)(bull) [^\n]*(?:\n(?!\1bull )[^\n]*)*/;
  11592. block.item = replace(block.item, 'gm')
  11593. (/bull/g, block.bullet)
  11594. ();
  11595. block.list = replace(block.list)
  11596. (/bull/g, block.bullet)
  11597. ('hr', '\\n+(?=\\1?(?:[-*_] *){3,}(?:\\n+|$))')
  11598. ('def', '\\n+(?=' + block.def.source + ')')
  11599. ();
  11600. block.blockquote = replace(block.blockquote)
  11601. ('def', block.def)
  11602. ();
  11603. block._tag = '(?!(?:'
  11604. + 'a|em|strong|small|s|cite|q|dfn|abbr|data|time|code'
  11605. + '|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo'
  11606. + '|span|br|wbr|ins|del|img)\\b)\\w+(?!:/|[^\\w\\s@]*@)\\b';
  11607. block.html = replace(block.html)
  11608. ('comment', /<!--[\s\S]*?-->/)
  11609. ('closed', /<(tag)[\s\S]+?<\/\1>/)
  11610. ('closing', /<tag(?:"[^"]*"|'[^']*'|[^'">])*?>/)
  11611. (/tag/g, block._tag)
  11612. ();
  11613. block.paragraph = replace(block.paragraph)
  11614. ('hr', block.hr)
  11615. ('heading', block.heading)
  11616. ('lheading', block.lheading)
  11617. ('blockquote', block.blockquote)
  11618. ('tag', '<' + block._tag)
  11619. ('def', block.def)
  11620. ();
  11621. /**
  11622. * Normal Block Grammar
  11623. */
  11624. block.normal = merge({}, block);
  11625. /**
  11626. * GFM Block Grammar
  11627. */
  11628. block.gfm = merge({}, block.normal, {
  11629. fences: /^ *(`{3,}|~{3,})[ \.]*(\S+)? *\n([\s\S]*?)\s*\1 *(?:\n+|$)/,
  11630. paragraph: /^/,
  11631. heading: /^ *(#{1,6}) +([^\n]+?) *#* *(?:\n+|$)/
  11632. });
  11633. block.gfm.paragraph = replace(block.paragraph)
  11634. ('(?!', '(?!'
  11635. + block.gfm.fences.source.replace('\\1', '\\2') + '|'
  11636. + block.list.source.replace('\\1', '\\3') + '|')
  11637. ();
  11638. /**
  11639. * GFM + Tables Block Grammar
  11640. */
  11641. block.tables = merge({}, block.gfm, {
  11642. nptable: /^ *(\S.*\|.*)\n *([-:]+ *\|[-| :]*)\n((?:.*\|.*(?:\n|$))*)\n*/,
  11643. table: /^ *\|(.+)\n *\|( *[-:]+[-| :]*)\n((?: *\|.*(?:\n|$))*)\n*/
  11644. });
  11645. /**
  11646. * Block Lexer
  11647. */
  11648. function Lexer(options) {
  11649. this.tokens = [];
  11650. this.tokens.links = {};
  11651. this.options = options || marked.defaults;
  11652. this.rules = block.normal;
  11653. if (this.options.gfm) {
  11654. if (this.options.tables) {
  11655. this.rules = block.tables;
  11656. } else {
  11657. this.rules = block.gfm;
  11658. }
  11659. }
  11660. }
  11661. /**
  11662. * Expose Block Rules
  11663. */
  11664. Lexer.rules = block;
  11665. /**
  11666. * Static Lex Method
  11667. */
  11668. Lexer.lex = function(src, options) {
  11669. var lexer = new Lexer(options);
  11670. return lexer.lex(src);
  11671. };
  11672. /**
  11673. * Preprocessing
  11674. */
  11675. Lexer.prototype.lex = function(src) {
  11676. src = src
  11677. .replace(/\r\n|\r/g, '\n')
  11678. .replace(/\t/g, ' ')
  11679. .replace(/\u00a0/g, ' ')
  11680. .replace(/\u2424/g, '\n');
  11681. return this.token(src, true);
  11682. };
  11683. /**
  11684. * Lexing
  11685. */
  11686. Lexer.prototype.token = function(src, top, bq) {
  11687. var src = src.replace(/^ +$/gm, '')
  11688. , next
  11689. , loose
  11690. , cap
  11691. , bull
  11692. , b
  11693. , item
  11694. , space
  11695. , i
  11696. , l;
  11697. while (src) {
  11698. // newline
  11699. if (cap = this.rules.newline.exec(src)) {
  11700. src = src.substring(cap[0].length);
  11701. if (cap[0].length > 1) {
  11702. this.tokens.push({
  11703. type: 'space'
  11704. });
  11705. }
  11706. }
  11707. // code
  11708. if (cap = this.rules.code.exec(src)) {
  11709. src = src.substring(cap[0].length);
  11710. cap = cap[0].replace(/^ {4}/gm, '');
  11711. this.tokens.push({
  11712. type: 'code',
  11713. text: !this.options.pedantic
  11714. ? cap.replace(/\n+$/, '')
  11715. : cap
  11716. });
  11717. continue;
  11718. }
  11719. // fences (gfm)
  11720. if (cap = this.rules.fences.exec(src)) {
  11721. src = src.substring(cap[0].length);
  11722. this.tokens.push({
  11723. type: 'code',
  11724. lang: cap[2],
  11725. text: cap[3] || ''
  11726. });
  11727. continue;
  11728. }
  11729. // heading
  11730. if (cap = this.rules.heading.exec(src)) {
  11731. src = src.substring(cap[0].length);
  11732. this.tokens.push({
  11733. type: 'heading',
  11734. depth: cap[1].length,
  11735. text: cap[2]
  11736. });
  11737. continue;
  11738. }
  11739. // table no leading pipe (gfm)
  11740. if (top && (cap = this.rules.nptable.exec(src))) {
  11741. src = src.substring(cap[0].length);
  11742. item = {
  11743. type: 'table',
  11744. header: cap[1].replace(/^ *| *\| *$/g, '').split(/ *\| */),
  11745. align: cap[2].replace(/^ *|\| *$/g, '').split(/ *\| */),
  11746. cells: cap[3].replace(/\n$/, '').split('\n')
  11747. };
  11748. for (i = 0; i < item.align.length; i++) {
  11749. if (/^ *-+: *$/.test(item.align[i])) {
  11750. item.align[i] = 'right';
  11751. } else if (/^ *:-+: *$/.test(item.align[i])) {
  11752. item.align[i] = 'center';
  11753. } else if (/^ *:-+ *$/.test(item.align[i])) {
  11754. item.align[i] = 'left';
  11755. } else {
  11756. item.align[i] = null;
  11757. }
  11758. }
  11759. for (i = 0; i < item.cells.length; i++) {
  11760. item.cells[i] = item.cells[i].split(/ *\| */);
  11761. }
  11762. this.tokens.push(item);
  11763. continue;
  11764. }
  11765. // lheading
  11766. if (cap = this.rules.lheading.exec(src)) {
  11767. src = src.substring(cap[0].length);
  11768. this.tokens.push({
  11769. type: 'heading',
  11770. depth: cap[2] === '=' ? 1 : 2,
  11771. text: cap[1]
  11772. });
  11773. continue;
  11774. }
  11775. // hr
  11776. if (cap = this.rules.hr.exec(src)) {
  11777. src = src.substring(cap[0].length);
  11778. this.tokens.push({
  11779. type: 'hr'
  11780. });
  11781. continue;
  11782. }
  11783. // blockquote
  11784. if (cap = this.rules.blockquote.exec(src)) {
  11785. src = src.substring(cap[0].length);
  11786. this.tokens.push({
  11787. type: 'blockquote_start'
  11788. });
  11789. cap = cap[0].replace(/^ *> ?/gm, '');
  11790. // Pass `top` to keep the current
  11791. // "toplevel" state. This is exactly
  11792. // how markdown.pl works.
  11793. this.token(cap, top, true);
  11794. this.tokens.push({
  11795. type: 'blockquote_end'
  11796. });
  11797. continue;
  11798. }
  11799. // list
  11800. if (cap = this.rules.list.exec(src)) {
  11801. src = src.substring(cap[0].length);
  11802. bull = cap[2];
  11803. this.tokens.push({
  11804. type: 'list_start',
  11805. ordered: bull.length > 1
  11806. });
  11807. // Get each top-level item.
  11808. cap = cap[0].match(this.rules.item);
  11809. next = false;
  11810. l = cap.length;
  11811. i = 0;
  11812. for (; i < l; i++) {
  11813. item = cap[i];
  11814. // Remove the list item's bullet
  11815. // so it is seen as the next token.
  11816. space = item.length;
  11817. item = item.replace(/^ *([*+-]|\d+\.) +/, '');
  11818. // Outdent whatever the
  11819. // list item contains. Hacky.
  11820. if (~item.indexOf('\n ')) {
  11821. space -= item.length;
  11822. item = !this.options.pedantic
  11823. ? item.replace(new RegExp('^ {1,' + space + '}', 'gm'), '')
  11824. : item.replace(/^ {1,4}/gm, '');
  11825. }
  11826. // Determine whether the next list item belongs here.
  11827. // Backpedal if it does not belong in this list.
  11828. if (this.options.smartLists && i !== l - 1) {
  11829. b = block.bullet.exec(cap[i + 1])[0];
  11830. if (bull !== b && !(bull.length > 1 && b.length > 1)) {
  11831. src = cap.slice(i + 1).join('\n') + src;
  11832. i = l - 1;
  11833. }
  11834. }
  11835. // Determine whether item is loose or not.
  11836. // Use: /(^|\n)(?! )[^\n]+\n\n(?!\s*$)/
  11837. // for discount behavior.
  11838. loose = next || /\n\n(?!\s*$)/.test(item);
  11839. if (i !== l - 1) {
  11840. next = item.charAt(item.length - 1) === '\n';
  11841. if (!loose) loose = next;
  11842. }
  11843. this.tokens.push({
  11844. type: loose
  11845. ? 'loose_item_start'
  11846. : 'list_item_start'
  11847. });
  11848. // Recurse.
  11849. this.token(item, false, bq);
  11850. this.tokens.push({
  11851. type: 'list_item_end'
  11852. });
  11853. }
  11854. this.tokens.push({
  11855. type: 'list_end'
  11856. });
  11857. continue;
  11858. }
  11859. // html
  11860. if (cap = this.rules.html.exec(src)) {
  11861. src = src.substring(cap[0].length);
  11862. this.tokens.push({
  11863. type: this.options.sanitize
  11864. ? 'paragraph'
  11865. : 'html',
  11866. pre: !this.options.sanitizer
  11867. && (cap[1] === 'pre' || cap[1] === 'script' || cap[1] === 'style'),
  11868. text: cap[0]
  11869. });
  11870. continue;
  11871. }
  11872. // def
  11873. if ((!bq && top) && (cap = this.rules.def.exec(src))) {
  11874. src = src.substring(cap[0].length);
  11875. this.tokens.links[cap[1].toLowerCase()] = {
  11876. href: cap[2],
  11877. title: cap[3]
  11878. };
  11879. continue;
  11880. }
  11881. // table (gfm)
  11882. if (top && (cap = this.rules.table.exec(src))) {
  11883. src = src.substring(cap[0].length);
  11884. item = {
  11885. type: 'table',
  11886. header: cap[1].replace(/^ *| *\| *$/g, '').split(/ *\| */),
  11887. align: cap[2].replace(/^ *|\| *$/g, '').split(/ *\| */),
  11888. cells: cap[3].replace(/(?: *\| *)?\n$/, '').split('\n')
  11889. };
  11890. for (i = 0; i < item.align.length; i++) {
  11891. if (/^ *-+: *$/.test(item.align[i])) {
  11892. item.align[i] = 'right';
  11893. } else if (/^ *:-+: *$/.test(item.align[i])) {
  11894. item.align[i] = 'center';
  11895. } else if (/^ *:-+ *$/.test(item.align[i])) {
  11896. item.align[i] = 'left';
  11897. } else {
  11898. item.align[i] = null;
  11899. }
  11900. }
  11901. for (i = 0; i < item.cells.length; i++) {
  11902. item.cells[i] = item.cells[i]
  11903. .replace(/^ *\| *| *\| *$/g, '')
  11904. .split(/ *\| */);
  11905. }
  11906. this.tokens.push(item);
  11907. continue;
  11908. }
  11909. // top-level paragraph
  11910. if (top && (cap = this.rules.paragraph.exec(src))) {
  11911. src = src.substring(cap[0].length);
  11912. this.tokens.push({
  11913. type: 'paragraph',
  11914. text: cap[1].charAt(cap[1].length - 1) === '\n'
  11915. ? cap[1].slice(0, -1)
  11916. : cap[1]
  11917. });
  11918. continue;
  11919. }
  11920. // text
  11921. if (cap = this.rules.text.exec(src)) {
  11922. // Top-level should never reach here.
  11923. src = src.substring(cap[0].length);
  11924. this.tokens.push({
  11925. type: 'text',
  11926. text: cap[0]
  11927. });
  11928. continue;
  11929. }
  11930. if (src) {
  11931. throw new
  11932. Error('Infinite loop on byte: ' + src.charCodeAt(0));
  11933. }
  11934. }
  11935. return this.tokens;
  11936. };
  11937. /**
  11938. * Inline-Level Grammar
  11939. */
  11940. var inline = {
  11941. escape: /^\\([\\`*{}\[\]()#+\-.!_>])/,
  11942. autolink: /^<([^ >]+(@|:\/)[^ >]+)>/,
  11943. url: noop,
  11944. tag: /^<!--[\s\S]*?-->|^<\/?\w+(?:"[^"]*"|'[^']*'|[^'">])*?>/,
  11945. link: /^!?\[(inside)\]\(href\)/,
  11946. reflink: /^!?\[(inside)\]\s*\[([^\]]*)\]/,
  11947. nolink: /^!?\[((?:\[[^\]]*\]|[^\[\]])*)\]/,
  11948. strong: /^__([\s\S]+?)__(?!_)|^\*\*([\s\S]+?)\*\*(?!\*)/,
  11949. em: /^\b_((?:[^_]|__)+?)_\b|^\*((?:\*\*|[\s\S])+?)\*(?!\*)/,
  11950. code: /^(`+)\s*([\s\S]*?[^`])\s*\1(?!`)/,
  11951. br: /^ {2,}\n(?!\s*$)/,
  11952. del: noop,
  11953. text: /^[\s\S]+?(?=[\\<!\[_*`]| {2,}\n|$)/
  11954. };
  11955. inline._inside = /(?:\[[^\]]*\]|[^\[\]]|\](?=[^\[]*\]))*/;
  11956. inline._href = /\s*<?([\s\S]*?)>?(?:\s+['"]([\s\S]*?)['"])?\s*/;
  11957. inline.link = replace(inline.link)
  11958. ('inside', inline._inside)
  11959. ('href', inline._href)
  11960. ();
  11961. inline.reflink = replace(inline.reflink)
  11962. ('inside', inline._inside)
  11963. ();
  11964. /**
  11965. * Normal Inline Grammar
  11966. */
  11967. inline.normal = merge({}, inline);
  11968. /**
  11969. * Pedantic Inline Grammar
  11970. */
  11971. inline.pedantic = merge({}, inline.normal, {
  11972. strong: /^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/,
  11973. em: /^_(?=\S)([\s\S]*?\S)_(?!_)|^\*(?=\S)([\s\S]*?\S)\*(?!\*)/
  11974. });
  11975. /**
  11976. * GFM Inline Grammar
  11977. */
  11978. inline.gfm = merge({}, inline.normal, {
  11979. escape: replace(inline.escape)('])', '~|])')(),
  11980. url: /^(https?:\/\/[^\s<]+[^<.,:;"')\]\s])/,
  11981. del: /^~~(?=\S)([\s\S]*?\S)~~/,
  11982. text: replace(inline.text)
  11983. (']|', '~]|')
  11984. ('|', '|https?://|')
  11985. ()
  11986. });
  11987. /**
  11988. * GFM + Line Breaks Inline Grammar
  11989. */
  11990. inline.breaks = merge({}, inline.gfm, {
  11991. br: replace(inline.br)('{2,}', '*')(),
  11992. text: replace(inline.gfm.text)('{2,}', '*')()
  11993. });
  11994. /**
  11995. * Inline Lexer & Compiler
  11996. */
  11997. function InlineLexer(links, options) {
  11998. this.options = options || marked.defaults;
  11999. this.links = links;
  12000. this.rules = inline.normal;
  12001. this.renderer = this.options.renderer || new Renderer;
  12002. this.renderer.options = this.options;
  12003. if (!this.links) {
  12004. throw new
  12005. Error('Tokens array requires a `links` property.');
  12006. }
  12007. if (this.options.gfm) {
  12008. if (this.options.breaks) {
  12009. this.rules = inline.breaks;
  12010. } else {
  12011. this.rules = inline.gfm;
  12012. }
  12013. } else if (this.options.pedantic) {
  12014. this.rules = inline.pedantic;
  12015. }
  12016. }
  12017. /**
  12018. * Expose Inline Rules
  12019. */
  12020. InlineLexer.rules = inline;
  12021. /**
  12022. * Static Lexing/Compiling Method
  12023. */
  12024. InlineLexer.output = function(src, links, options) {
  12025. var inline = new InlineLexer(links, options);
  12026. return inline.output(src);
  12027. };
  12028. /**
  12029. * Lexing/Compiling
  12030. */
  12031. InlineLexer.prototype.output = function(src) {
  12032. var out = ''
  12033. , link
  12034. , text
  12035. , href
  12036. , cap;
  12037. while (src) {
  12038. // escape
  12039. if (cap = this.rules.escape.exec(src)) {
  12040. src = src.substring(cap[0].length);
  12041. out += cap[1];
  12042. continue;
  12043. }
  12044. // autolink
  12045. if (cap = this.rules.autolink.exec(src)) {
  12046. src = src.substring(cap[0].length);
  12047. if (cap[2] === '@') {
  12048. text = cap[1].charAt(6) === ':'
  12049. ? this.mangle(cap[1].substring(7))
  12050. : this.mangle(cap[1]);
  12051. href = this.mangle('mailto:') + text;
  12052. } else {
  12053. text = escape(cap[1]);
  12054. href = text;
  12055. }
  12056. out += this.renderer.link(href, null, text);
  12057. continue;
  12058. }
  12059. // url (gfm)
  12060. if (!this.inLink && (cap = this.rules.url.exec(src))) {
  12061. src = src.substring(cap[0].length);
  12062. text = escape(cap[1]);
  12063. href = text;
  12064. out += this.renderer.link(href, null, text);
  12065. continue;
  12066. }
  12067. // tag
  12068. if (cap = this.rules.tag.exec(src)) {
  12069. if (!this.inLink && /^<a /i.test(cap[0])) {
  12070. this.inLink = true;
  12071. } else if (this.inLink && /^<\/a>/i.test(cap[0])) {
  12072. this.inLink = false;
  12073. }
  12074. src = src.substring(cap[0].length);
  12075. out += this.options.sanitize
  12076. ? this.options.sanitizer
  12077. ? this.options.sanitizer(cap[0])
  12078. : escape(cap[0])
  12079. : cap[0]
  12080. continue;
  12081. }
  12082. // link
  12083. if (cap = this.rules.link.exec(src)) {
  12084. src = src.substring(cap[0].length);
  12085. this.inLink = true;
  12086. out += this.outputLink(cap, {
  12087. href: cap[2],
  12088. title: cap[3]
  12089. });
  12090. this.inLink = false;
  12091. continue;
  12092. }
  12093. // reflink, nolink
  12094. if ((cap = this.rules.reflink.exec(src))
  12095. || (cap = this.rules.nolink.exec(src))) {
  12096. src = src.substring(cap[0].length);
  12097. link = (cap[2] || cap[1]).replace(/\s+/g, ' ');
  12098. link = this.links[link.toLowerCase()];
  12099. if (!link || !link.href) {
  12100. out += cap[0].charAt(0);
  12101. src = cap[0].substring(1) + src;
  12102. continue;
  12103. }
  12104. this.inLink = true;
  12105. out += this.outputLink(cap, link);
  12106. this.inLink = false;
  12107. continue;
  12108. }
  12109. // strong
  12110. if (cap = this.rules.strong.exec(src)) {
  12111. src = src.substring(cap[0].length);
  12112. out += this.renderer.strong(this.output(cap[2] || cap[1]));
  12113. continue;
  12114. }
  12115. // em
  12116. if (cap = this.rules.em.exec(src)) {
  12117. src = src.substring(cap[0].length);
  12118. out += this.renderer.em(this.output(cap[2] || cap[1]));
  12119. continue;
  12120. }
  12121. // code
  12122. if (cap = this.rules.code.exec(src)) {
  12123. src = src.substring(cap[0].length);
  12124. out += this.renderer.codespan(escape(cap[2], true));
  12125. continue;
  12126. }
  12127. // br
  12128. if (cap = this.rules.br.exec(src)) {
  12129. src = src.substring(cap[0].length);
  12130. out += this.renderer.br();
  12131. continue;
  12132. }
  12133. // del (gfm)
  12134. if (cap = this.rules.del.exec(src)) {
  12135. src = src.substring(cap[0].length);
  12136. out += this.renderer.del(this.output(cap[1]));
  12137. continue;
  12138. }
  12139. // text
  12140. if (cap = this.rules.text.exec(src)) {
  12141. src = src.substring(cap[0].length);
  12142. out += this.renderer.text(escape(this.smartypants(cap[0])));
  12143. continue;
  12144. }
  12145. if (src) {
  12146. throw new
  12147. Error('Infinite loop on byte: ' + src.charCodeAt(0));
  12148. }
  12149. }
  12150. return out;
  12151. };
  12152. /**
  12153. * Compile Link
  12154. */
  12155. InlineLexer.prototype.outputLink = function(cap, link) {
  12156. var href = escape(link.href)
  12157. , title = link.title ? escape(link.title) : null;
  12158. return cap[0].charAt(0) !== '!'
  12159. ? this.renderer.link(href, title, this.output(cap[1]))
  12160. : this.renderer.image(href, title, escape(cap[1]));
  12161. };
  12162. /**
  12163. * Smartypants Transformations
  12164. */
  12165. InlineLexer.prototype.smartypants = function(text) {
  12166. if (!this.options.smartypants) return text;
  12167. return text
  12168. // em-dashes
  12169. .replace(/---/g, '\u2014')
  12170. // en-dashes
  12171. .replace(/--/g, '\u2013')
  12172. // opening singles
  12173. .replace(/(^|[-\u2014/(\[{"\s])'/g, '$1\u2018')
  12174. // closing singles & apostrophes
  12175. .replace(/'/g, '\u2019')
  12176. // opening doubles
  12177. .replace(/(^|[-\u2014/(\[{\u2018\s])"/g, '$1\u201c')
  12178. // closing doubles
  12179. .replace(/"/g, '\u201d')
  12180. // ellipses
  12181. .replace(/\.{3}/g, '\u2026');
  12182. };
  12183. /**
  12184. * Mangle Links
  12185. */
  12186. InlineLexer.prototype.mangle = function(text) {
  12187. if (!this.options.mangle) return text;
  12188. var out = ''
  12189. , l = text.length
  12190. , i = 0
  12191. , ch;
  12192. for (; i < l; i++) {
  12193. ch = text.charCodeAt(i);
  12194. if (Math.random() > 0.5) {
  12195. ch = 'x' + ch.toString(16);
  12196. }
  12197. out += '&#' + ch + ';';
  12198. }
  12199. return out;
  12200. };
  12201. /**
  12202. * Renderer
  12203. */
  12204. function Renderer(options) {
  12205. this.options = options || {};
  12206. }
  12207. Renderer.prototype.code = function(code, lang, escaped) {
  12208. if (this.options.highlight) {
  12209. var out = this.options.highlight(code, lang);
  12210. if (out != null && out !== code) {
  12211. escaped = true;
  12212. code = out;
  12213. }
  12214. }
  12215. if (!lang) {
  12216. return '<pre><code>'
  12217. + (escaped ? code : escape(code, true))
  12218. + '\n</code></pre>';
  12219. }
  12220. return '<pre><code class="'
  12221. + this.options.langPrefix
  12222. + escape(lang, true)
  12223. + '">'
  12224. + (escaped ? code : escape(code, true))
  12225. + '\n</code></pre>\n';
  12226. };
  12227. Renderer.prototype.blockquote = function(quote) {
  12228. return '<blockquote>\n' + quote + '</blockquote>\n';
  12229. };
  12230. Renderer.prototype.html = function(html) {
  12231. return html;
  12232. };
  12233. Renderer.prototype.heading = function(text, level, raw) {
  12234. return '<h'
  12235. + level
  12236. + ' id="'
  12237. + this.options.headerPrefix
  12238. + raw.toLowerCase().replace(/[^\w]+/g, '-')
  12239. + '">'
  12240. + text
  12241. + '</h'
  12242. + level
  12243. + '>\n';
  12244. };
  12245. Renderer.prototype.hr = function() {
  12246. return this.options.xhtml ? '<hr/>\n' : '<hr>\n';
  12247. };
  12248. Renderer.prototype.list = function(body, ordered) {
  12249. var type = ordered ? 'ol' : 'ul';
  12250. return '<' + type + '>\n' + body + '</' + type + '>\n';
  12251. };
  12252. Renderer.prototype.listitem = function(text) {
  12253. return '<li>' + text + '</li>\n';
  12254. };
  12255. Renderer.prototype.paragraph = function(text) {
  12256. return '<p>' + text + '</p>\n';
  12257. };
  12258. Renderer.prototype.table = function(header, body) {
  12259. return '<table>\n'
  12260. + '<thead>\n'
  12261. + header
  12262. + '</thead>\n'
  12263. + '<tbody>\n'
  12264. + body
  12265. + '</tbody>\n'
  12266. + '</table>\n';
  12267. };
  12268. Renderer.prototype.tablerow = function(content) {
  12269. return '<tr>\n' + content + '</tr>\n';
  12270. };
  12271. Renderer.prototype.tablecell = function(content, flags) {
  12272. var type = flags.header ? 'th' : 'td';
  12273. var tag = flags.align
  12274. ? '<' + type + ' style="text-align:' + flags.align + '">'
  12275. : '<' + type + '>';
  12276. return tag + content + '</' + type + '>\n';
  12277. };
  12278. // span level renderer
  12279. Renderer.prototype.strong = function(text) {
  12280. return '<strong>' + text + '</strong>';
  12281. };
  12282. Renderer.prototype.em = function(text) {
  12283. return '<em>' + text + '</em>';
  12284. };
  12285. Renderer.prototype.codespan = function(text) {
  12286. return '<code>' + text + '</code>';
  12287. };
  12288. Renderer.prototype.br = function() {
  12289. return this.options.xhtml ? '<br/>' : '<br>';
  12290. };
  12291. Renderer.prototype.del = function(text) {
  12292. return '<del>' + text + '</del>';
  12293. };
  12294. Renderer.prototype.link = function(href, title, text) {
  12295. if (this.options.sanitize) {
  12296. try {
  12297. var prot = decodeURIComponent(unescape(href))
  12298. .replace(/[^\w:]/g, '')
  12299. .toLowerCase();
  12300. } catch (e) {
  12301. return '';
  12302. }
  12303. if (prot.indexOf('javascript:') === 0 || prot.indexOf('vbscript:') === 0) {
  12304. return '';
  12305. }
  12306. }
  12307. var out = '<a href="' + href + '"';
  12308. if (title) {
  12309. out += ' title="' + title + '"';
  12310. }
  12311. out += '>' + text + '</a>';
  12312. return out;
  12313. };
  12314. Renderer.prototype.image = function(href, title, text) {
  12315. var out = '<img src="' + href + '" alt="' + text + '"';
  12316. if (title) {
  12317. out += ' title="' + title + '"';
  12318. }
  12319. out += this.options.xhtml ? '/>' : '>';
  12320. return out;
  12321. };
  12322. Renderer.prototype.text = function(text) {
  12323. return text;
  12324. };
  12325. /**
  12326. * Parsing & Compiling
  12327. */
  12328. function Parser(options) {
  12329. this.tokens = [];
  12330. this.token = null;
  12331. this.options = options || marked.defaults;
  12332. this.options.renderer = this.options.renderer || new Renderer;
  12333. this.renderer = this.options.renderer;
  12334. this.renderer.options = this.options;
  12335. }
  12336. /**
  12337. * Static Parse Method
  12338. */
  12339. Parser.parse = function(src, options, renderer) {
  12340. var parser = new Parser(options, renderer);
  12341. return parser.parse(src);
  12342. };
  12343. /**
  12344. * Parse Loop
  12345. */
  12346. Parser.prototype.parse = function(src) {
  12347. this.inline = new InlineLexer(src.links, this.options, this.renderer);
  12348. this.tokens = src.reverse();
  12349. var out = '';
  12350. while (this.next()) {
  12351. out += this.tok();
  12352. }
  12353. return out;
  12354. };
  12355. /**
  12356. * Next Token
  12357. */
  12358. Parser.prototype.next = function() {
  12359. return this.token = this.tokens.pop();
  12360. };
  12361. /**
  12362. * Preview Next Token
  12363. */
  12364. Parser.prototype.peek = function() {
  12365. return this.tokens[this.tokens.length - 1] || 0;
  12366. };
  12367. /**
  12368. * Parse Text Tokens
  12369. */
  12370. Parser.prototype.parseText = function() {
  12371. var body = this.token.text;
  12372. while (this.peek().type === 'text') {
  12373. body += '\n' + this.next().text;
  12374. }
  12375. return this.inline.output(body);
  12376. };
  12377. /**
  12378. * Parse Current Token
  12379. */
  12380. Parser.prototype.tok = function() {
  12381. switch (this.token.type) {
  12382. case 'space': {
  12383. return '';
  12384. }
  12385. case 'hr': {
  12386. return this.renderer.hr();
  12387. }
  12388. case 'heading': {
  12389. return this.renderer.heading(
  12390. this.inline.output(this.token.text),
  12391. this.token.depth,
  12392. this.token.text);
  12393. }
  12394. case 'code': {
  12395. return this.renderer.code(this.token.text,
  12396. this.token.lang,
  12397. this.token.escaped);
  12398. }
  12399. case 'table': {
  12400. var header = ''
  12401. , body = ''
  12402. , i
  12403. , row
  12404. , cell
  12405. , flags
  12406. , j;
  12407. // header
  12408. cell = '';
  12409. for (i = 0; i < this.token.header.length; i++) {
  12410. flags = { header: true, align: this.token.align[i] };
  12411. cell += this.renderer.tablecell(
  12412. this.inline.output(this.token.header[i]),
  12413. { header: true, align: this.token.align[i] }
  12414. );
  12415. }
  12416. header += this.renderer.tablerow(cell);
  12417. for (i = 0; i < this.token.cells.length; i++) {
  12418. row = this.token.cells[i];
  12419. cell = '';
  12420. for (j = 0; j < row.length; j++) {
  12421. cell += this.renderer.tablecell(
  12422. this.inline.output(row[j]),
  12423. { header: false, align: this.token.align[j] }
  12424. );
  12425. }
  12426. body += this.renderer.tablerow(cell);
  12427. }
  12428. return this.renderer.table(header, body);
  12429. }
  12430. case 'blockquote_start': {
  12431. var body = '';
  12432. while (this.next().type !== 'blockquote_end') {
  12433. body += this.tok();
  12434. }
  12435. return this.renderer.blockquote(body);
  12436. }
  12437. case 'list_start': {
  12438. var body = ''
  12439. , ordered = this.token.ordered;
  12440. while (this.next().type !== 'list_end') {
  12441. body += this.tok();
  12442. }
  12443. return this.renderer.list(body, ordered);
  12444. }
  12445. case 'list_item_start': {
  12446. var body = '';
  12447. while (this.next().type !== 'list_item_end') {
  12448. body += this.token.type === 'text'
  12449. ? this.parseText()
  12450. : this.tok();
  12451. }
  12452. return this.renderer.listitem(body);
  12453. }
  12454. case 'loose_item_start': {
  12455. var body = '';
  12456. while (this.next().type !== 'list_item_end') {
  12457. body += this.tok();
  12458. }
  12459. return this.renderer.listitem(body);
  12460. }
  12461. case 'html': {
  12462. var html = !this.token.pre && !this.options.pedantic
  12463. ? this.inline.output(this.token.text)
  12464. : this.token.text;
  12465. return this.renderer.html(html);
  12466. }
  12467. case 'paragraph': {
  12468. return this.renderer.paragraph(this.inline.output(this.token.text));
  12469. }
  12470. case 'text': {
  12471. return this.renderer.paragraph(this.parseText());
  12472. }
  12473. }
  12474. };
  12475. /**
  12476. * Helpers
  12477. */
  12478. function escape(html, encode) {
  12479. return html
  12480. .replace(!encode ? /&(?!#?\w+;)/g : /&/g, '&amp;')
  12481. .replace(/</g, '&lt;')
  12482. .replace(/>/g, '&gt;')
  12483. .replace(/"/g, '&quot;')
  12484. .replace(/'/g, '&#39;');
  12485. }
  12486. function unescape(html) {
  12487. return html.replace(/&([#\w]+);/g, function(_, n) {
  12488. n = n.toLowerCase();
  12489. if (n === 'colon') return ':';
  12490. if (n.charAt(0) === '#') {
  12491. return n.charAt(1) === 'x'
  12492. ? String.fromCharCode(parseInt(n.substring(2), 16))
  12493. : String.fromCharCode(+n.substring(1));
  12494. }
  12495. return '';
  12496. });
  12497. }
  12498. function replace(regex, opt) {
  12499. regex = regex.source;
  12500. opt = opt || '';
  12501. return function self(name, val) {
  12502. if (!name) return new RegExp(regex, opt);
  12503. val = val.source || val;
  12504. val = val.replace(/(^|[^\[])\^/g, '$1');
  12505. regex = regex.replace(name, val);
  12506. return self;
  12507. };
  12508. }
  12509. function noop() {}
  12510. noop.exec = noop;
  12511. function merge(obj) {
  12512. var i = 1
  12513. , target
  12514. , key;
  12515. for (; i < arguments.length; i++) {
  12516. target = arguments[i];
  12517. for (key in target) {
  12518. if (Object.prototype.hasOwnProperty.call(target, key)) {
  12519. obj[key] = target[key];
  12520. }
  12521. }
  12522. }
  12523. return obj;
  12524. }
  12525. /**
  12526. * Marked
  12527. */
  12528. function marked(src, opt, callback) {
  12529. if (callback || typeof opt === 'function') {
  12530. if (!callback) {
  12531. callback = opt;
  12532. opt = null;
  12533. }
  12534. opt = merge({}, marked.defaults, opt || {});
  12535. var highlight = opt.highlight
  12536. , tokens
  12537. , pending
  12538. , i = 0;
  12539. try {
  12540. tokens = Lexer.lex(src, opt)
  12541. } catch (e) {
  12542. return callback(e);
  12543. }
  12544. pending = tokens.length;
  12545. var done = function(err) {
  12546. if (err) {
  12547. opt.highlight = highlight;
  12548. return callback(err);
  12549. }
  12550. var out;
  12551. try {
  12552. out = Parser.parse(tokens, opt);
  12553. } catch (e) {
  12554. err = e;
  12555. }
  12556. opt.highlight = highlight;
  12557. return err
  12558. ? callback(err)
  12559. : callback(null, out);
  12560. };
  12561. if (!highlight || highlight.length < 3) {
  12562. return done();
  12563. }
  12564. delete opt.highlight;
  12565. if (!pending) return done();
  12566. for (; i < tokens.length; i++) {
  12567. (function(token) {
  12568. if (token.type !== 'code') {
  12569. return --pending || done();
  12570. }
  12571. return highlight(token.text, token.lang, function(err, code) {
  12572. if (err) return done(err);
  12573. if (code == null || code === token.text) {
  12574. return --pending || done();
  12575. }
  12576. token.text = code;
  12577. token.escaped = true;
  12578. --pending || done();
  12579. });
  12580. })(tokens[i]);
  12581. }
  12582. return;
  12583. }
  12584. try {
  12585. if (opt) opt = merge({}, marked.defaults, opt);
  12586. return Parser.parse(Lexer.lex(src, opt), opt);
  12587. } catch (e) {
  12588. e.message += '\nPlease report this to https://github.com/chjj/marked.';
  12589. if ((opt || marked.defaults).silent) {
  12590. return '<p>An error occured:</p><pre>'
  12591. + escape(e.message + '', true)
  12592. + '</pre>';
  12593. }
  12594. throw e;
  12595. }
  12596. }
  12597. /**
  12598. * Options
  12599. */
  12600. marked.options =
  12601. marked.setOptions = function(opt) {
  12602. merge(marked.defaults, opt);
  12603. return marked;
  12604. };
  12605. marked.defaults = {
  12606. gfm: true,
  12607. tables: true,
  12608. breaks: false,
  12609. pedantic: false,
  12610. sanitize: false,
  12611. sanitizer: null,
  12612. mangle: true,
  12613. smartLists: false,
  12614. silent: false,
  12615. highlight: null,
  12616. langPrefix: 'lang-',
  12617. smartypants: false,
  12618. headerPrefix: '',
  12619. renderer: new Renderer,
  12620. xhtml: false
  12621. };
  12622. /**
  12623. * Expose
  12624. */
  12625. marked.Parser = Parser;
  12626. marked.parser = Parser.parse;
  12627. marked.Renderer = Renderer;
  12628. marked.Lexer = Lexer;
  12629. marked.lexer = Lexer.lex;
  12630. marked.InlineLexer = InlineLexer;
  12631. marked.inlineLexer = InlineLexer.output;
  12632. marked.parse = marked;
  12633. if (typeof module !== 'undefined' && typeof exports === 'object') {
  12634. module.exports = marked;
  12635. } else if (typeof define === 'function' && define.amd) {
  12636. define(function() { return marked; });
  12637. } else {
  12638. this.marked = marked;
  12639. }
  12640. }).call(function() {
  12641. return this || (typeof window !== 'undefined' ? window : global);
  12642. }());
  12643. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  12644. },{}],18:[function(require,module,exports){
  12645. (function (Buffer,__dirname){
  12646. 'use strict';
  12647. /**
  12648. * Typo is a JavaScript implementation of a spellchecker using hunspell-style
  12649. * dictionaries.
  12650. */
  12651. /**
  12652. * Typo constructor.
  12653. *
  12654. * @param {String} [dictionary] The locale code of the dictionary being used. e.g.,
  12655. * "en_US". This is only used to auto-load dictionaries.
  12656. * @param {String} [affData] The data from the dictionary's .aff file. If omitted
  12657. * and Typo.js is being used in a Chrome extension, the .aff
  12658. * file will be loaded automatically from
  12659. * lib/typo/dictionaries/[dictionary]/[dictionary].aff
  12660. * In other environments, it will be loaded from
  12661. * [settings.dictionaryPath]/dictionaries/[dictionary]/[dictionary].aff
  12662. * @param {String} [wordsData] The data from the dictionary's .dic file. If omitted
  12663. * and Typo.js is being used in a Chrome extension, the .dic
  12664. * file will be loaded automatically from
  12665. * lib/typo/dictionaries/[dictionary]/[dictionary].dic
  12666. * In other environments, it will be loaded from
  12667. * [settings.dictionaryPath]/dictionaries/[dictionary]/[dictionary].dic
  12668. * @param {Object} [settings] Constructor settings. Available properties are:
  12669. * {String} [dictionaryPath]: path to load dictionary from in non-chrome
  12670. * environment.
  12671. * {Object} [flags]: flag information.
  12672. *
  12673. *
  12674. * @returns {Typo} A Typo object.
  12675. */
  12676. var Typo = function (dictionary, affData, wordsData, settings) {
  12677. settings = settings || {};
  12678. this.dictionary = null;
  12679. this.rules = {};
  12680. this.dictionaryTable = {};
  12681. this.compoundRules = [];
  12682. this.compoundRuleCodes = {};
  12683. this.replacementTable = [];
  12684. this.flags = settings.flags || {};
  12685. if (dictionary) {
  12686. this.dictionary = dictionary;
  12687. if (typeof window !== 'undefined' && 'chrome' in window && 'extension' in window.chrome && 'getURL' in window.chrome.extension) {
  12688. if (!affData) affData = this._readFile(chrome.extension.getURL("lib/typo/dictionaries/" + dictionary + "/" + dictionary + ".aff"));
  12689. if (!wordsData) wordsData = this._readFile(chrome.extension.getURL("lib/typo/dictionaries/" + dictionary + "/" + dictionary + ".dic"));
  12690. } else {
  12691. if (settings.dictionaryPath) {
  12692. var path = settings.dictionaryPath;
  12693. }
  12694. else if (typeof __dirname !== 'undefined') {
  12695. var path = __dirname + '/dictionaries';
  12696. }
  12697. else {
  12698. var path = './dictionaries';
  12699. }
  12700. if (!affData) affData = this._readFile(path + "/" + dictionary + "/" + dictionary + ".aff");
  12701. if (!wordsData) wordsData = this._readFile(path + "/" + dictionary + "/" + dictionary + ".dic");
  12702. }
  12703. this.rules = this._parseAFF(affData);
  12704. // Save the rule codes that are used in compound rules.
  12705. this.compoundRuleCodes = {};
  12706. for (var i = 0, _len = this.compoundRules.length; i < _len; i++) {
  12707. var rule = this.compoundRules[i];
  12708. for (var j = 0, _jlen = rule.length; j < _jlen; j++) {
  12709. this.compoundRuleCodes[rule[j]] = [];
  12710. }
  12711. }
  12712. // If we add this ONLYINCOMPOUND flag to this.compoundRuleCodes, then _parseDIC
  12713. // will do the work of saving the list of words that are compound-only.
  12714. if ("ONLYINCOMPOUND" in this.flags) {
  12715. this.compoundRuleCodes[this.flags.ONLYINCOMPOUND] = [];
  12716. }
  12717. this.dictionaryTable = this._parseDIC(wordsData);
  12718. // Get rid of any codes from the compound rule codes that are never used
  12719. // (or that were special regex characters). Not especially necessary...
  12720. for (var i in this.compoundRuleCodes) {
  12721. if (this.compoundRuleCodes[i].length == 0) {
  12722. delete this.compoundRuleCodes[i];
  12723. }
  12724. }
  12725. // Build the full regular expressions for each compound rule.
  12726. // I have a feeling (but no confirmation yet) that this method of
  12727. // testing for compound words is probably slow.
  12728. for (var i = 0, _len = this.compoundRules.length; i < _len; i++) {
  12729. var ruleText = this.compoundRules[i];
  12730. var expressionText = "";
  12731. for (var j = 0, _jlen = ruleText.length; j < _jlen; j++) {
  12732. var character = ruleText[j];
  12733. if (character in this.compoundRuleCodes) {
  12734. expressionText += "(" + this.compoundRuleCodes[character].join("|") + ")";
  12735. }
  12736. else {
  12737. expressionText += character;
  12738. }
  12739. }
  12740. this.compoundRules[i] = new RegExp(expressionText, "i");
  12741. }
  12742. }
  12743. return this;
  12744. };
  12745. Typo.prototype = {
  12746. /**
  12747. * Loads a Typo instance from a hash of all of the Typo properties.
  12748. *
  12749. * @param object obj A hash of Typo properties, probably gotten from a JSON.parse(JSON.stringify(typo_instance)).
  12750. */
  12751. load : function (obj) {
  12752. for (var i in obj) {
  12753. this[i] = obj[i];
  12754. }
  12755. return this;
  12756. },
  12757. /**
  12758. * Read the contents of a file.
  12759. *
  12760. * @param {String} path The path (relative) to the file.
  12761. * @param {String} [charset="ISO8859-1"] The expected charset of the file
  12762. * @returns string The file data.
  12763. */
  12764. _readFile : function (path, charset) {
  12765. if (!charset) charset = "utf8";
  12766. if (typeof XMLHttpRequest !== 'undefined') {
  12767. var req = new XMLHttpRequest();
  12768. req.open("GET", path, false);
  12769. if (req.overrideMimeType)
  12770. req.overrideMimeType("text/plain; charset=" + charset);
  12771. req.send(null);
  12772. return req.responseText;
  12773. }
  12774. else if (typeof require !== 'undefined') {
  12775. // Node.js
  12776. var fs = require("fs");
  12777. try {
  12778. if (fs.existsSync(path)) {
  12779. var stats = fs.statSync(path);
  12780. var fileDescriptor = fs.openSync(path, 'r');
  12781. var buffer = new Buffer(stats.size);
  12782. fs.readSync(fileDescriptor, buffer, 0, buffer.length, null);
  12783. return buffer.toString(charset, 0, buffer.length);
  12784. }
  12785. else {
  12786. console.log("Path " + path + " does not exist.");
  12787. }
  12788. } catch (e) {
  12789. console.log(e);
  12790. return '';
  12791. }
  12792. }
  12793. },
  12794. /**
  12795. * Parse the rules out from a .aff file.
  12796. *
  12797. * @param {String} data The contents of the affix file.
  12798. * @returns object The rules from the file.
  12799. */
  12800. _parseAFF : function (data) {
  12801. var rules = {};
  12802. // Remove comment lines
  12803. data = this._removeAffixComments(data);
  12804. var lines = data.split("\n");
  12805. for (var i = 0, _len = lines.length; i < _len; i++) {
  12806. var line = lines[i];
  12807. var definitionParts = line.split(/\s+/);
  12808. var ruleType = definitionParts[0];
  12809. if (ruleType == "PFX" || ruleType == "SFX") {
  12810. var ruleCode = definitionParts[1];
  12811. var combineable = definitionParts[2];
  12812. var numEntries = parseInt(definitionParts[3], 10);
  12813. var entries = [];
  12814. for (var j = i + 1, _jlen = i + 1 + numEntries; j < _jlen; j++) {
  12815. var line = lines[j];
  12816. var lineParts = line.split(/\s+/);
  12817. var charactersToRemove = lineParts[2];
  12818. var additionParts = lineParts[3].split("/");
  12819. var charactersToAdd = additionParts[0];
  12820. if (charactersToAdd === "0") charactersToAdd = "";
  12821. var continuationClasses = this.parseRuleCodes(additionParts[1]);
  12822. var regexToMatch = lineParts[4];
  12823. var entry = {};
  12824. entry.add = charactersToAdd;
  12825. if (continuationClasses.length > 0) entry.continuationClasses = continuationClasses;
  12826. if (regexToMatch !== ".") {
  12827. if (ruleType === "SFX") {
  12828. entry.match = new RegExp(regexToMatch + "$");
  12829. }
  12830. else {
  12831. entry.match = new RegExp("^" + regexToMatch);
  12832. }
  12833. }
  12834. if (charactersToRemove != "0") {
  12835. if (ruleType === "SFX") {
  12836. entry.remove = new RegExp(charactersToRemove + "$");
  12837. }
  12838. else {
  12839. entry.remove = charactersToRemove;
  12840. }
  12841. }
  12842. entries.push(entry);
  12843. }
  12844. rules[ruleCode] = { "type" : ruleType, "combineable" : (combineable == "Y"), "entries" : entries };
  12845. i += numEntries;
  12846. }
  12847. else if (ruleType === "COMPOUNDRULE") {
  12848. var numEntries = parseInt(definitionParts[1], 10);
  12849. for (var j = i + 1, _jlen = i + 1 + numEntries; j < _jlen; j++) {
  12850. var line = lines[j];
  12851. var lineParts = line.split(/\s+/);
  12852. this.compoundRules.push(lineParts[1]);
  12853. }
  12854. i += numEntries;
  12855. }
  12856. else if (ruleType === "REP") {
  12857. var lineParts = line.split(/\s+/);
  12858. if (lineParts.length === 3) {
  12859. this.replacementTable.push([ lineParts[1], lineParts[2] ]);
  12860. }
  12861. }
  12862. else {
  12863. // ONLYINCOMPOUND
  12864. // COMPOUNDMIN
  12865. // FLAG
  12866. // KEEPCASE
  12867. // NEEDAFFIX
  12868. this.flags[ruleType] = definitionParts[1];
  12869. }
  12870. }
  12871. return rules;
  12872. },
  12873. /**
  12874. * Removes comment lines and then cleans up blank lines and trailing whitespace.
  12875. *
  12876. * @param {String} data The data from an affix file.
  12877. * @return {String} The cleaned-up data.
  12878. */
  12879. _removeAffixComments : function (data) {
  12880. // Remove comments
  12881. data = data.replace(/#.*$/mg, "");
  12882. // Trim each line
  12883. data = data.replace(/^\s\s*/m, '').replace(/\s\s*$/m, '');
  12884. // Remove blank lines.
  12885. data = data.replace(/\n{2,}/g, "\n");
  12886. // Trim the entire string
  12887. data = data.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
  12888. return data;
  12889. },
  12890. /**
  12891. * Parses the words out from the .dic file.
  12892. *
  12893. * @param {String} data The data from the dictionary file.
  12894. * @returns object The lookup table containing all of the words and
  12895. * word forms from the dictionary.
  12896. */
  12897. _parseDIC : function (data) {
  12898. data = this._removeDicComments(data);
  12899. var lines = data.split("\n");
  12900. var dictionaryTable = {};
  12901. function addWord(word, rules) {
  12902. // Some dictionaries will list the same word multiple times with different rule sets.
  12903. if (!(word in dictionaryTable) || typeof dictionaryTable[word] != 'object') {
  12904. dictionaryTable[word] = [];
  12905. }
  12906. dictionaryTable[word].push(rules);
  12907. }
  12908. // The first line is the number of words in the dictionary.
  12909. for (var i = 1, _len = lines.length; i < _len; i++) {
  12910. var line = lines[i];
  12911. var parts = line.split("/", 2);
  12912. var word = parts[0];
  12913. // Now for each affix rule, generate that form of the word.
  12914. if (parts.length > 1) {
  12915. var ruleCodesArray = this.parseRuleCodes(parts[1]);
  12916. // Save the ruleCodes for compound word situations.
  12917. if (!("NEEDAFFIX" in this.flags) || ruleCodesArray.indexOf(this.flags.NEEDAFFIX) == -1) {
  12918. addWord(word, ruleCodesArray);
  12919. }
  12920. for (var j = 0, _jlen = ruleCodesArray.length; j < _jlen; j++) {
  12921. var code = ruleCodesArray[j];
  12922. var rule = this.rules[code];
  12923. if (rule) {
  12924. var newWords = this._applyRule(word, rule);
  12925. for (var ii = 0, _iilen = newWords.length; ii < _iilen; ii++) {
  12926. var newWord = newWords[ii];
  12927. addWord(newWord, []);
  12928. if (rule.combineable) {
  12929. for (var k = j + 1; k < _jlen; k++) {
  12930. var combineCode = ruleCodesArray[k];
  12931. var combineRule = this.rules[combineCode];
  12932. if (combineRule) {
  12933. if (combineRule.combineable && (rule.type != combineRule.type)) {
  12934. var otherNewWords = this._applyRule(newWord, combineRule);
  12935. for (var iii = 0, _iiilen = otherNewWords.length; iii < _iiilen; iii++) {
  12936. var otherNewWord = otherNewWords[iii];
  12937. addWord(otherNewWord, []);
  12938. }
  12939. }
  12940. }
  12941. }
  12942. }
  12943. }
  12944. }
  12945. if (code in this.compoundRuleCodes) {
  12946. this.compoundRuleCodes[code].push(word);
  12947. }
  12948. }
  12949. }
  12950. else {
  12951. addWord(word.trim(), []);
  12952. }
  12953. }
  12954. return dictionaryTable;
  12955. },
  12956. /**
  12957. * Removes comment lines and then cleans up blank lines and trailing whitespace.
  12958. *
  12959. * @param {String} data The data from a .dic file.
  12960. * @return {String} The cleaned-up data.
  12961. */
  12962. _removeDicComments : function (data) {
  12963. // I can't find any official documentation on it, but at least the de_DE
  12964. // dictionary uses tab-indented lines as comments.
  12965. // Remove comments
  12966. data = data.replace(/^\t.*$/mg, "");
  12967. return data;
  12968. },
  12969. parseRuleCodes : function (textCodes) {
  12970. if (!textCodes) {
  12971. return [];
  12972. }
  12973. else if (!("FLAG" in this.flags)) {
  12974. return textCodes.split("");
  12975. }
  12976. else if (this.flags.FLAG === "long") {
  12977. var flags = [];
  12978. for (var i = 0, _len = textCodes.length; i < _len; i += 2) {
  12979. flags.push(textCodes.substr(i, 2));
  12980. }
  12981. return flags;
  12982. }
  12983. else if (this.flags.FLAG === "num") {
  12984. return textCode.split(",");
  12985. }
  12986. },
  12987. /**
  12988. * Applies an affix rule to a word.
  12989. *
  12990. * @param {String} word The base word.
  12991. * @param {Object} rule The affix rule.
  12992. * @returns {String[]} The new words generated by the rule.
  12993. */
  12994. _applyRule : function (word, rule) {
  12995. var entries = rule.entries;
  12996. var newWords = [];
  12997. for (var i = 0, _len = entries.length; i < _len; i++) {
  12998. var entry = entries[i];
  12999. if (!entry.match || word.match(entry.match)) {
  13000. var newWord = word;
  13001. if (entry.remove) {
  13002. newWord = newWord.replace(entry.remove, "");
  13003. }
  13004. if (rule.type === "SFX") {
  13005. newWord = newWord + entry.add;
  13006. }
  13007. else {
  13008. newWord = entry.add + newWord;
  13009. }
  13010. newWords.push(newWord);
  13011. if ("continuationClasses" in entry) {
  13012. for (var j = 0, _jlen = entry.continuationClasses.length; j < _jlen; j++) {
  13013. var continuationRule = this.rules[entry.continuationClasses[j]];
  13014. if (continuationRule) {
  13015. newWords = newWords.concat(this._applyRule(newWord, continuationRule));
  13016. }
  13017. /*
  13018. else {
  13019. // This shouldn't happen, but it does, at least in the de_DE dictionary.
  13020. // I think the author mistakenly supplied lower-case rule codes instead
  13021. // of upper-case.
  13022. }
  13023. */
  13024. }
  13025. }
  13026. }
  13027. }
  13028. return newWords;
  13029. },
  13030. /**
  13031. * Checks whether a word or a capitalization variant exists in the current dictionary.
  13032. * The word is trimmed and several variations of capitalizations are checked.
  13033. * If you want to check a word without any changes made to it, call checkExact()
  13034. *
  13035. * @see http://blog.stevenlevithan.com/archives/faster-trim-javascript re:trimming function
  13036. *
  13037. * @param {String} aWord The word to check.
  13038. * @returns {Boolean}
  13039. */
  13040. check : function (aWord) {
  13041. // Remove leading and trailing whitespace
  13042. var trimmedWord = aWord.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
  13043. if (this.checkExact(trimmedWord)) {
  13044. return true;
  13045. }
  13046. // The exact word is not in the dictionary.
  13047. if (trimmedWord.toUpperCase() === trimmedWord) {
  13048. // The word was supplied in all uppercase.
  13049. // Check for a capitalized form of the word.
  13050. var capitalizedWord = trimmedWord[0] + trimmedWord.substring(1).toLowerCase();
  13051. if (this.hasFlag(capitalizedWord, "KEEPCASE")) {
  13052. // Capitalization variants are not allowed for this word.
  13053. return false;
  13054. }
  13055. if (this.checkExact(capitalizedWord)) {
  13056. return true;
  13057. }
  13058. }
  13059. var lowercaseWord = trimmedWord.toLowerCase();
  13060. if (lowercaseWord !== trimmedWord) {
  13061. if (this.hasFlag(lowercaseWord, "KEEPCASE")) {
  13062. // Capitalization variants are not allowed for this word.
  13063. return false;
  13064. }
  13065. // Check for a lowercase form
  13066. if (this.checkExact(lowercaseWord)) {
  13067. return true;
  13068. }
  13069. }
  13070. return false;
  13071. },
  13072. /**
  13073. * Checks whether a word exists in the current dictionary.
  13074. *
  13075. * @param {String} word The word to check.
  13076. * @returns {Boolean}
  13077. */
  13078. checkExact : function (word) {
  13079. var ruleCodes = this.dictionaryTable[word];
  13080. if (typeof ruleCodes === 'undefined') {
  13081. // Check if this might be a compound word.
  13082. if ("COMPOUNDMIN" in this.flags && word.length >= this.flags.COMPOUNDMIN) {
  13083. for (var i = 0, _len = this.compoundRules.length; i < _len; i++) {
  13084. if (word.match(this.compoundRules[i])) {
  13085. return true;
  13086. }
  13087. }
  13088. }
  13089. return false;
  13090. }
  13091. else if (typeof ruleCodes === 'object') { // this.dictionary['hasOwnProperty'] will be a function.
  13092. for (var i = 0, _len = ruleCodes.length; i < _len; i++) {
  13093. if (!this.hasFlag(word, "ONLYINCOMPOUND", ruleCodes[i])) {
  13094. return true;
  13095. }
  13096. }
  13097. return false;
  13098. }
  13099. },
  13100. /**
  13101. * Looks up whether a given word is flagged with a given flag.
  13102. *
  13103. * @param {String} word The word in question.
  13104. * @param {String} flag The flag in question.
  13105. * @return {Boolean}
  13106. */
  13107. hasFlag : function (word, flag, wordFlags) {
  13108. if (flag in this.flags) {
  13109. if (typeof wordFlags === 'undefined') {
  13110. var wordFlags = Array.prototype.concat.apply([], this.dictionaryTable[word]);
  13111. }
  13112. if (wordFlags && wordFlags.indexOf(this.flags[flag]) !== -1) {
  13113. return true;
  13114. }
  13115. }
  13116. return false;
  13117. },
  13118. /**
  13119. * Returns a list of suggestions for a misspelled word.
  13120. *
  13121. * @see http://www.norvig.com/spell-correct.html for the basis of this suggestor.
  13122. * This suggestor is primitive, but it works.
  13123. *
  13124. * @param {String} word The misspelling.
  13125. * @param {Number} [limit=5] The maximum number of suggestions to return.
  13126. * @returns {String[]} The array of suggestions.
  13127. */
  13128. alphabet : "",
  13129. suggest : function (word, limit) {
  13130. if (!limit) limit = 5;
  13131. if (this.check(word)) return [];
  13132. // Check the replacement table.
  13133. for (var i = 0, _len = this.replacementTable.length; i < _len; i++) {
  13134. var replacementEntry = this.replacementTable[i];
  13135. if (word.indexOf(replacementEntry[0]) !== -1) {
  13136. var correctedWord = word.replace(replacementEntry[0], replacementEntry[1]);
  13137. if (this.check(correctedWord)) {
  13138. return [ correctedWord ];
  13139. }
  13140. }
  13141. }
  13142. var self = this;
  13143. self.alphabet = "abcdefghijklmnopqrstuvwxyz";
  13144. /*
  13145. if (!self.alphabet) {
  13146. // Use the alphabet as implicitly defined by the words in the dictionary.
  13147. var alphaHash = {};
  13148. for (var i in self.dictionaryTable) {
  13149. for (var j = 0, _len = i.length; j < _len; j++) {
  13150. alphaHash[i[j]] = true;
  13151. }
  13152. }
  13153. for (var i in alphaHash) {
  13154. self.alphabet += i;
  13155. }
  13156. var alphaArray = self.alphabet.split("");
  13157. alphaArray.sort();
  13158. self.alphabet = alphaArray.join("");
  13159. }
  13160. */
  13161. function edits1(words) {
  13162. var rv = [];
  13163. for (var ii = 0, _iilen = words.length; ii < _iilen; ii++) {
  13164. var word = words[ii];
  13165. var splits = [];
  13166. for (var i = 0, _len = word.length + 1; i < _len; i++) {
  13167. splits.push([ word.substring(0, i), word.substring(i, word.length) ]);
  13168. }
  13169. var deletes = [];
  13170. for (var i = 0, _len = splits.length; i < _len; i++) {
  13171. var s = splits[i];
  13172. if (s[1]) {
  13173. deletes.push(s[0] + s[1].substring(1));
  13174. }
  13175. }
  13176. var transposes = [];
  13177. for (var i = 0, _len = splits.length; i < _len; i++) {
  13178. var s = splits[i];
  13179. if (s[1].length > 1) {
  13180. transposes.push(s[0] + s[1][1] + s[1][0] + s[1].substring(2));
  13181. }
  13182. }
  13183. var replaces = [];
  13184. for (var i = 0, _len = splits.length; i < _len; i++) {
  13185. var s = splits[i];
  13186. if (s[1]) {
  13187. for (var j = 0, _jlen = self.alphabet.length; j < _jlen; j++) {
  13188. replaces.push(s[0] + self.alphabet[j] + s[1].substring(1));
  13189. }
  13190. }
  13191. }
  13192. var inserts = [];
  13193. for (var i = 0, _len = splits.length; i < _len; i++) {
  13194. var s = splits[i];
  13195. if (s[1]) {
  13196. for (var j = 0, _jlen = self.alphabet.length; j < _jlen; j++) {
  13197. replaces.push(s[0] + self.alphabet[j] + s[1]);
  13198. }
  13199. }
  13200. }
  13201. rv = rv.concat(deletes);
  13202. rv = rv.concat(transposes);
  13203. rv = rv.concat(replaces);
  13204. rv = rv.concat(inserts);
  13205. }
  13206. return rv;
  13207. }
  13208. function known(words) {
  13209. var rv = [];
  13210. for (var i = 0; i < words.length; i++) {
  13211. if (self.check(words[i])) {
  13212. rv.push(words[i]);
  13213. }
  13214. }
  13215. return rv;
  13216. }
  13217. function correct(word) {
  13218. // Get the edit-distance-1 and edit-distance-2 forms of this word.
  13219. var ed1 = edits1([word]);
  13220. var ed2 = edits1(ed1);
  13221. var corrections = known(ed1).concat(known(ed2));
  13222. // Sort the edits based on how many different ways they were created.
  13223. var weighted_corrections = {};
  13224. for (var i = 0, _len = corrections.length; i < _len; i++) {
  13225. if (!(corrections[i] in weighted_corrections)) {
  13226. weighted_corrections[corrections[i]] = 1;
  13227. }
  13228. else {
  13229. weighted_corrections[corrections[i]] += 1;
  13230. }
  13231. }
  13232. var sorted_corrections = [];
  13233. for (var i in weighted_corrections) {
  13234. sorted_corrections.push([ i, weighted_corrections[i] ]);
  13235. }
  13236. function sorter(a, b) {
  13237. if (a[1] < b[1]) {
  13238. return -1;
  13239. }
  13240. return 1;
  13241. }
  13242. sorted_corrections.sort(sorter).reverse();
  13243. var rv = [];
  13244. for (var i = 0, _len = Math.min(limit, sorted_corrections.length); i < _len; i++) {
  13245. if (!self.hasFlag(sorted_corrections[i][0], "NOSUGGEST")) {
  13246. rv.push(sorted_corrections[i][0]);
  13247. }
  13248. }
  13249. return rv;
  13250. }
  13251. return correct(word);
  13252. }
  13253. };
  13254. // Support for use as a node.js module.
  13255. if (typeof module !== 'undefined') {
  13256. module.exports = Typo;
  13257. }
  13258. }).call(this,require("buffer").Buffer,"/node_modules/typo-js")
  13259. },{"buffer":3,"fs":2}],19:[function(require,module,exports){
  13260. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  13261. // Distributed under an MIT license: http://codemirror.net/LICENSE
  13262. var CodeMirror = require("codemirror");
  13263. CodeMirror.commands.tabAndIndentMarkdownList = function (cm) {
  13264. var ranges = cm.listSelections();
  13265. var pos = ranges[0].head;
  13266. var eolState = cm.getStateAfter(pos.line);
  13267. var inList = eolState.list !== false;
  13268. if (inList) {
  13269. cm.execCommand("indentMore");
  13270. return;
  13271. }
  13272. if (cm.options.indentWithTabs) {
  13273. cm.execCommand("insertTab");
  13274. }
  13275. else {
  13276. var spaces = Array(cm.options.tabSize + 1).join(" ");
  13277. cm.replaceSelection(spaces);
  13278. }
  13279. };
  13280. CodeMirror.commands.shiftTabAndUnindentMarkdownList = function (cm) {
  13281. var ranges = cm.listSelections();
  13282. var pos = ranges[0].head;
  13283. var eolState = cm.getStateAfter(pos.line);
  13284. var inList = eolState.list !== false;
  13285. if (inList) {
  13286. cm.execCommand("indentLess");
  13287. return;
  13288. }
  13289. if (cm.options.indentWithTabs) {
  13290. cm.execCommand("insertTab");
  13291. }
  13292. else {
  13293. var spaces = Array(cm.options.tabSize + 1).join(" ");
  13294. cm.replaceSelection(spaces);
  13295. }
  13296. };
  13297. },{"codemirror":10}],20:[function(require,module,exports){
  13298. /*global require,module*/
  13299. "use strict";
  13300. var CodeMirror = require("codemirror");
  13301. require("codemirror/addon/edit/continuelist.js");
  13302. require("./codemirror/tablist");
  13303. require("codemirror/addon/display/fullscreen.js");
  13304. require("codemirror/mode/markdown/markdown.js");
  13305. require("codemirror/addon/mode/overlay.js");
  13306. require("codemirror/addon/display/placeholder.js");
  13307. require("codemirror/addon/selection/mark-selection.js");
  13308. require("codemirror/mode/gfm/gfm.js");
  13309. require("codemirror/mode/xml/xml.js");
  13310. var CodeMirrorSpellChecker = require("codemirror-spell-checker");
  13311. var marked = require("marked");
  13312. // Some variables
  13313. var isMac = /Mac/.test(navigator.platform);
  13314. // Mapping of actions that can be bound to keyboard shortcuts or toolbar buttons
  13315. var bindings = {
  13316. "toggleBold": toggleBold,
  13317. "toggleItalic": toggleItalic,
  13318. "drawLink": drawLink,
  13319. "toggleHeadingSmaller": toggleHeadingSmaller,
  13320. "toggleHeadingBigger": toggleHeadingBigger,
  13321. "drawImage": drawImage,
  13322. "toggleBlockquote": toggleBlockquote,
  13323. "toggleOrderedList": toggleOrderedList,
  13324. "toggleUnorderedList": toggleUnorderedList,
  13325. "toggleCodeBlock": toggleCodeBlock,
  13326. "togglePreview": togglePreview,
  13327. "toggleStrikethrough": toggleStrikethrough,
  13328. "toggleHeading1": toggleHeading1,
  13329. "toggleHeading2": toggleHeading2,
  13330. "toggleHeading3": toggleHeading3,
  13331. "cleanBlock": cleanBlock,
  13332. "drawTable": drawTable,
  13333. "drawHorizontalRule": drawHorizontalRule,
  13334. "undo": undo,
  13335. "redo": redo,
  13336. "toggleSideBySide": toggleSideBySide,
  13337. "toggleFullScreen": toggleFullScreen
  13338. };
  13339. var shortcuts = {
  13340. "toggleBold": "Cmd-B",
  13341. "toggleItalic": "Cmd-I",
  13342. "drawLink": "Cmd-K",
  13343. "toggleHeadingSmaller": "Cmd-H",
  13344. "toggleHeadingBigger": "Shift-Cmd-H",
  13345. "cleanBlock": "Cmd-E",
  13346. "drawImage": "Cmd-Alt-I",
  13347. "toggleBlockquote": "Cmd-'",
  13348. "toggleOrderedList": "Cmd-Alt-L",
  13349. "toggleUnorderedList": "Cmd-L",
  13350. "toggleCodeBlock": "Cmd-Alt-C",
  13351. "togglePreview": "Cmd-P",
  13352. "toggleSideBySide": "F9",
  13353. "toggleFullScreen": "F11"
  13354. };
  13355. var getBindingName = function(f) {
  13356. for(var key in bindings) {
  13357. if(bindings[key] === f) {
  13358. return key;
  13359. }
  13360. }
  13361. return null;
  13362. };
  13363. var isMobile = function() {
  13364. var check = false;
  13365. (function(a) {
  13366. 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;
  13367. })(navigator.userAgent || navigator.vendor || window.opera);
  13368. return check;
  13369. };
  13370. /**
  13371. * Fix shortcut. Mac use Command, others use Ctrl.
  13372. */
  13373. function fixShortcut(name) {
  13374. if(isMac) {
  13375. name = name.replace("Ctrl", "Cmd");
  13376. } else {
  13377. name = name.replace("Cmd", "Ctrl");
  13378. }
  13379. return name;
  13380. }
  13381. /**
  13382. * Create icon element for toolbar.
  13383. */
  13384. function createIcon(options, enableTooltips, shortcuts) {
  13385. options = options || {};
  13386. var el = document.createElement("a");
  13387. enableTooltips = (enableTooltips == undefined) ? true : enableTooltips;
  13388. if(options.title && enableTooltips) {
  13389. el.title = createTootlip(options.title, options.action, shortcuts);
  13390. if(isMac) {
  13391. el.title = el.title.replace("Ctrl", "⌘");
  13392. el.title = el.title.replace("Alt", "⌥");
  13393. }
  13394. }
  13395. el.tabIndex = -1;
  13396. el.className = options.className;
  13397. return el;
  13398. }
  13399. function createSep() {
  13400. var el = document.createElement("i");
  13401. el.className = "separator";
  13402. el.innerHTML = "|";
  13403. return el;
  13404. }
  13405. function createTootlip(title, action, shortcuts) {
  13406. var actionName;
  13407. var tooltip = title;
  13408. if(action) {
  13409. actionName = getBindingName(action);
  13410. if(shortcuts[actionName]) {
  13411. tooltip += " (" + fixShortcut(shortcuts[actionName]) + ")";
  13412. }
  13413. }
  13414. return tooltip;
  13415. }
  13416. /**
  13417. * The state of CodeMirror at the given position.
  13418. */
  13419. function getState(cm, pos) {
  13420. pos = pos || cm.getCursor("start");
  13421. var stat = cm.getTokenAt(pos);
  13422. if(!stat.type) return {};
  13423. var types = stat.type.split(" ");
  13424. var ret = {},
  13425. data, text;
  13426. for(var i = 0; i < types.length; i++) {
  13427. data = types[i];
  13428. if(data === "strong") {
  13429. ret.bold = true;
  13430. } else if(data === "variable-2") {
  13431. text = cm.getLine(pos.line);
  13432. if(/^\s*\d+\.\s/.test(text)) {
  13433. ret["ordered-list"] = true;
  13434. } else {
  13435. ret["unordered-list"] = true;
  13436. }
  13437. } else if(data === "atom") {
  13438. ret.quote = true;
  13439. } else if(data === "em") {
  13440. ret.italic = true;
  13441. } else if(data === "quote") {
  13442. ret.quote = true;
  13443. } else if(data === "strikethrough") {
  13444. ret.strikethrough = true;
  13445. } else if(data === "comment") {
  13446. ret.code = true;
  13447. } else if(data === "link") {
  13448. ret.link = true;
  13449. } else if(data === "tag") {
  13450. ret.image = true;
  13451. } else if(data.match(/^header(\-[1-6])?$/)) {
  13452. ret[data.replace("header", "heading")] = true;
  13453. }
  13454. }
  13455. return ret;
  13456. }
  13457. // Saved overflow setting
  13458. var saved_overflow = "";
  13459. /**
  13460. * Toggle full screen of the editor.
  13461. */
  13462. function toggleFullScreen(editor) {
  13463. // Set fullscreen
  13464. var cm = editor.codemirror;
  13465. cm.setOption("fullScreen", !cm.getOption("fullScreen"));
  13466. // Prevent scrolling on body during fullscreen active
  13467. if(cm.getOption("fullScreen")) {
  13468. saved_overflow = document.body.style.overflow;
  13469. document.body.style.overflow = "hidden";
  13470. } else {
  13471. document.body.style.overflow = saved_overflow;
  13472. }
  13473. // Update toolbar class
  13474. var wrap = cm.getWrapperElement();
  13475. if(!/fullscreen/.test(wrap.previousSibling.className)) {
  13476. wrap.previousSibling.className += " fullscreen";
  13477. } else {
  13478. wrap.previousSibling.className = wrap.previousSibling.className.replace(/\s*fullscreen\b/, "");
  13479. }
  13480. // Update toolbar button
  13481. var toolbarButton = editor.toolbarElements.fullscreen;
  13482. if(!/active/.test(toolbarButton.className)) {
  13483. toolbarButton.className += " active";
  13484. } else {
  13485. toolbarButton.className = toolbarButton.className.replace(/\s*active\s*/g, "");
  13486. }
  13487. // Hide side by side if needed
  13488. var sidebyside = cm.getWrapperElement().nextSibling;
  13489. if(/editor-preview-active-side/.test(sidebyside.className))
  13490. toggleSideBySide(editor);
  13491. }
  13492. /**
  13493. * Action for toggling bold.
  13494. */
  13495. function toggleBold(editor) {
  13496. _toggleBlock(editor, "bold", editor.options.blockStyles.bold);
  13497. }
  13498. /**
  13499. * Action for toggling italic.
  13500. */
  13501. function toggleItalic(editor) {
  13502. _toggleBlock(editor, "italic", editor.options.blockStyles.italic);
  13503. }
  13504. /**
  13505. * Action for toggling strikethrough.
  13506. */
  13507. function toggleStrikethrough(editor) {
  13508. _toggleBlock(editor, "strikethrough", "~~");
  13509. }
  13510. /**
  13511. * Action for toggling code block.
  13512. */
  13513. function toggleCodeBlock(editor) {
  13514. var fenceCharsToInsert = editor.options.blockStyles.code;
  13515. function fencing_line(line) {
  13516. /* return true, if this is a ``` or ~~~ line */
  13517. if(typeof line !== "object") {
  13518. throw "fencing_line() takes a 'line' object (not a line number, or line text). Got: " + typeof line + ": " + line;
  13519. }
  13520. return line.styles && line.styles[2] && line.styles[2].indexOf("formatting-code-block") !== -1;
  13521. }
  13522. function token_state(token) {
  13523. // base goes an extra level deep when mode backdrops are used, e.g. spellchecker on
  13524. return token.state.base.base || token.state.base;
  13525. }
  13526. function code_type(cm, line_num, line, firstTok, lastTok) {
  13527. /*
  13528. * Return "single", "indented", "fenced" or false
  13529. *
  13530. * cm and line_num are required. Others are optional for efficiency
  13531. * To check in the middle of a line, pass in firstTok yourself.
  13532. */
  13533. line = line || cm.getLineHandle(line_num);
  13534. firstTok = firstTok || cm.getTokenAt({
  13535. line: line_num,
  13536. ch: 1
  13537. });
  13538. lastTok = lastTok || (!!line.text && cm.getTokenAt({
  13539. line: line_num,
  13540. ch: line.text.length - 1
  13541. }));
  13542. var types = firstTok.type ? firstTok.type.split(" ") : [];
  13543. if(lastTok && token_state(lastTok).indentedCode) {
  13544. // have to check last char, since first chars of first line aren"t marked as indented
  13545. return "indented";
  13546. } else if(types.indexOf("comment") === -1) {
  13547. // has to be after "indented" check, since first chars of first indented line aren"t marked as such
  13548. return false;
  13549. } else if(token_state(firstTok).fencedChars || token_state(lastTok).fencedChars || fencing_line(line)) {
  13550. return "fenced";
  13551. } else {
  13552. return "single";
  13553. }
  13554. }
  13555. function insertFencingAtSelection(cm, cur_start, cur_end, fenceCharsToInsert) {
  13556. var start_line_sel = cur_start.line + 1,
  13557. end_line_sel = cur_end.line + 1,
  13558. sel_multi = cur_start.line !== cur_end.line,
  13559. repl_start = fenceCharsToInsert + "\n",
  13560. repl_end = "\n" + fenceCharsToInsert;
  13561. if(sel_multi) {
  13562. end_line_sel++;
  13563. }
  13564. // handle last char including \n or not
  13565. if(sel_multi && cur_end.ch === 0) {
  13566. repl_end = fenceCharsToInsert + "\n";
  13567. end_line_sel--;
  13568. }
  13569. _replaceSelection(cm, false, [repl_start, repl_end]);
  13570. cm.setSelection({
  13571. line: start_line_sel,
  13572. ch: 0
  13573. }, {
  13574. line: end_line_sel,
  13575. ch: 0
  13576. });
  13577. }
  13578. var cm = editor.codemirror,
  13579. cur_start = cm.getCursor("start"),
  13580. cur_end = cm.getCursor("end"),
  13581. tok = cm.getTokenAt({
  13582. line: cur_start.line,
  13583. ch: cur_start.ch || 1
  13584. }), // avoid ch 0 which is a cursor pos but not token
  13585. line = cm.getLineHandle(cur_start.line),
  13586. is_code = code_type(cm, cur_start.line, line, tok);
  13587. var block_start, block_end, lineCount;
  13588. if(is_code === "single") {
  13589. // similar to some SimpleMDE _toggleBlock logic
  13590. var start = line.text.slice(0, cur_start.ch).replace("`", ""),
  13591. end = line.text.slice(cur_start.ch).replace("`", "");
  13592. cm.replaceRange(start + end, {
  13593. line: cur_start.line,
  13594. ch: 0
  13595. }, {
  13596. line: cur_start.line,
  13597. ch: 99999999999999
  13598. });
  13599. cur_start.ch--;
  13600. if(cur_start !== cur_end) {
  13601. cur_end.ch--;
  13602. }
  13603. cm.setSelection(cur_start, cur_end);
  13604. cm.focus();
  13605. } else if(is_code === "fenced") {
  13606. if(cur_start.line !== cur_end.line || cur_start.ch !== cur_end.ch) {
  13607. // use selection
  13608. // find the fenced line so we know what type it is (tilde, backticks, number of them)
  13609. for(block_start = cur_start.line; block_start >= 0; block_start--) {
  13610. line = cm.getLineHandle(block_start);
  13611. if(fencing_line(line)) {
  13612. break;
  13613. }
  13614. }
  13615. var fencedTok = cm.getTokenAt({
  13616. line: block_start,
  13617. ch: 1
  13618. });
  13619. var fence_chars = token_state(fencedTok).fencedChars;
  13620. var start_text, start_line;
  13621. var end_text, end_line;
  13622. // check for selection going up against fenced lines, in which case we don't want to add more fencing
  13623. if(fencing_line(cm.getLineHandle(cur_start.line))) {
  13624. start_text = "";
  13625. start_line = cur_start.line;
  13626. } else if(fencing_line(cm.getLineHandle(cur_start.line - 1))) {
  13627. start_text = "";
  13628. start_line = cur_start.line - 1;
  13629. } else {
  13630. start_text = fence_chars + "\n";
  13631. start_line = cur_start.line;
  13632. }
  13633. if(fencing_line(cm.getLineHandle(cur_end.line))) {
  13634. end_text = "";
  13635. end_line = cur_end.line;
  13636. if(cur_end.ch === 0) {
  13637. end_line += 1;
  13638. }
  13639. } else if(cur_end.ch !== 0 && fencing_line(cm.getLineHandle(cur_end.line + 1))) {
  13640. end_text = "";
  13641. end_line = cur_end.line + 1;
  13642. } else {
  13643. end_text = fence_chars + "\n";
  13644. end_line = cur_end.line + 1;
  13645. }
  13646. if(cur_end.ch === 0) {
  13647. // full last line selected, putting cursor at beginning of next
  13648. end_line -= 1;
  13649. }
  13650. cm.operation(function() {
  13651. // end line first, so that line numbers don't change
  13652. cm.replaceRange(end_text, {
  13653. line: end_line,
  13654. ch: 0
  13655. }, {
  13656. line: end_line + (end_text ? 0 : 1),
  13657. ch: 0
  13658. });
  13659. cm.replaceRange(start_text, {
  13660. line: start_line,
  13661. ch: 0
  13662. }, {
  13663. line: start_line + (start_text ? 0 : 1),
  13664. ch: 0
  13665. });
  13666. });
  13667. cm.setSelection({
  13668. line: start_line + (start_text ? 1 : 0),
  13669. ch: 0
  13670. }, {
  13671. line: end_line + (start_text ? 1 : -1),
  13672. ch: 0
  13673. });
  13674. cm.focus();
  13675. } else {
  13676. // no selection, search for ends of this fenced block
  13677. var search_from = cur_start.line;
  13678. if(fencing_line(cm.getLineHandle(cur_start.line))) { // gets a little tricky if cursor is right on a fenced line
  13679. if(code_type(cm, cur_start.line + 1) === "fenced") {
  13680. block_start = cur_start.line;
  13681. search_from = cur_start.line + 1; // for searching for "end"
  13682. } else {
  13683. block_end = cur_start.line;
  13684. search_from = cur_start.line - 1; // for searching for "start"
  13685. }
  13686. }
  13687. if(block_start === undefined) {
  13688. for(block_start = search_from; block_start >= 0; block_start--) {
  13689. line = cm.getLineHandle(block_start);
  13690. if(fencing_line(line)) {
  13691. break;
  13692. }
  13693. }
  13694. }
  13695. if(block_end === undefined) {
  13696. lineCount = cm.lineCount();
  13697. for(block_end = search_from; block_end < lineCount; block_end++) {
  13698. line = cm.getLineHandle(block_end);
  13699. if(fencing_line(line)) {
  13700. break;
  13701. }
  13702. }
  13703. }
  13704. cm.operation(function() {
  13705. cm.replaceRange("", {
  13706. line: block_start,
  13707. ch: 0
  13708. }, {
  13709. line: block_start + 1,
  13710. ch: 0
  13711. });
  13712. cm.replaceRange("", {
  13713. line: block_end - 1,
  13714. ch: 0
  13715. }, {
  13716. line: block_end,
  13717. ch: 0
  13718. });
  13719. });
  13720. cm.focus();
  13721. }
  13722. } else if(is_code === "indented") {
  13723. if(cur_start.line !== cur_end.line || cur_start.ch !== cur_end.ch) {
  13724. // use selection
  13725. block_start = cur_start.line;
  13726. block_end = cur_end.line;
  13727. if(cur_end.ch === 0) {
  13728. block_end--;
  13729. }
  13730. } else {
  13731. // no selection, search for ends of this indented block
  13732. for(block_start = cur_start.line; block_start >= 0; block_start--) {
  13733. line = cm.getLineHandle(block_start);
  13734. if(line.text.match(/^\s*$/)) {
  13735. // empty or all whitespace - keep going
  13736. continue;
  13737. } else {
  13738. if(code_type(cm, block_start, line) !== "indented") {
  13739. block_start += 1;
  13740. break;
  13741. }
  13742. }
  13743. }
  13744. lineCount = cm.lineCount();
  13745. for(block_end = cur_start.line; block_end < lineCount; block_end++) {
  13746. line = cm.getLineHandle(block_end);
  13747. if(line.text.match(/^\s*$/)) {
  13748. // empty or all whitespace - keep going
  13749. continue;
  13750. } else {
  13751. if(code_type(cm, block_end, line) !== "indented") {
  13752. block_end -= 1;
  13753. break;
  13754. }
  13755. }
  13756. }
  13757. }
  13758. // if we are going to un-indent based on a selected set of lines, and the next line is indented too, we need to
  13759. // insert a blank line so that the next line(s) continue to be indented code
  13760. var next_line = cm.getLineHandle(block_end + 1),
  13761. next_line_last_tok = next_line && cm.getTokenAt({
  13762. line: block_end + 1,
  13763. ch: next_line.text.length - 1
  13764. }),
  13765. next_line_indented = next_line_last_tok && token_state(next_line_last_tok).indentedCode;
  13766. if(next_line_indented) {
  13767. cm.replaceRange("\n", {
  13768. line: block_end + 1,
  13769. ch: 0
  13770. });
  13771. }
  13772. for(var i = block_start; i <= block_end; i++) {
  13773. cm.indentLine(i, "subtract"); // TODO: this doesn't get tracked in the history, so can't be undone :(
  13774. }
  13775. cm.focus();
  13776. } else {
  13777. // insert code formatting
  13778. var no_sel_and_starting_of_line = (cur_start.line === cur_end.line && cur_start.ch === cur_end.ch && cur_start.ch === 0);
  13779. var sel_multi = cur_start.line !== cur_end.line;
  13780. if(no_sel_and_starting_of_line || sel_multi) {
  13781. insertFencingAtSelection(cm, cur_start, cur_end, fenceCharsToInsert);
  13782. } else {
  13783. _replaceSelection(cm, false, ["`", "`"]);
  13784. }
  13785. }
  13786. }
  13787. /**
  13788. * Action for toggling blockquote.
  13789. */
  13790. function toggleBlockquote(editor) {
  13791. var cm = editor.codemirror;
  13792. _toggleLine(cm, "quote");
  13793. }
  13794. /**
  13795. * Action for toggling heading size: normal -> h1 -> h2 -> h3 -> h4 -> h5 -> h6 -> normal
  13796. */
  13797. function toggleHeadingSmaller(editor) {
  13798. var cm = editor.codemirror;
  13799. _toggleHeading(cm, "smaller");
  13800. }
  13801. /**
  13802. * Action for toggling heading size: normal -> h6 -> h5 -> h4 -> h3 -> h2 -> h1 -> normal
  13803. */
  13804. function toggleHeadingBigger(editor) {
  13805. var cm = editor.codemirror;
  13806. _toggleHeading(cm, "bigger");
  13807. }
  13808. /**
  13809. * Action for toggling heading size 1
  13810. */
  13811. function toggleHeading1(editor) {
  13812. var cm = editor.codemirror;
  13813. _toggleHeading(cm, undefined, 1);
  13814. }
  13815. /**
  13816. * Action for toggling heading size 2
  13817. */
  13818. function toggleHeading2(editor) {
  13819. var cm = editor.codemirror;
  13820. _toggleHeading(cm, undefined, 2);
  13821. }
  13822. /**
  13823. * Action for toggling heading size 3
  13824. */
  13825. function toggleHeading3(editor) {
  13826. var cm = editor.codemirror;
  13827. _toggleHeading(cm, undefined, 3);
  13828. }
  13829. /**
  13830. * Action for toggling ul.
  13831. */
  13832. function toggleUnorderedList(editor) {
  13833. var cm = editor.codemirror;
  13834. _toggleLine(cm, "unordered-list");
  13835. }
  13836. /**
  13837. * Action for toggling ol.
  13838. */
  13839. function toggleOrderedList(editor) {
  13840. var cm = editor.codemirror;
  13841. _toggleLine(cm, "ordered-list");
  13842. }
  13843. /**
  13844. * Action for clean block (remove headline, list, blockquote code, markers)
  13845. */
  13846. function cleanBlock(editor) {
  13847. var cm = editor.codemirror;
  13848. _cleanBlock(cm);
  13849. }
  13850. /**
  13851. * Action for drawing a link.
  13852. */
  13853. function drawLink(editor) {
  13854. var cm = editor.codemirror;
  13855. var stat = getState(cm);
  13856. var options = editor.options;
  13857. var url = "http://";
  13858. if(options.promptURLs) {
  13859. url = prompt(options.promptTexts.link);
  13860. if(!url) {
  13861. return false;
  13862. }
  13863. }
  13864. _replaceSelection(cm, stat.link, options.insertTexts.link, url);
  13865. }
  13866. /**
  13867. * Action for drawing an img.
  13868. */
  13869. function drawImage(editor) {
  13870. var cm = editor.codemirror;
  13871. var stat = getState(cm);
  13872. var options = editor.options;
  13873. var url = "http://";
  13874. if(options.promptURLs) {
  13875. url = prompt(options.promptTexts.image);
  13876. if(!url) {
  13877. return false;
  13878. }
  13879. }
  13880. _replaceSelection(cm, stat.image, options.insertTexts.image, url);
  13881. }
  13882. /**
  13883. * Action for drawing a table.
  13884. */
  13885. function drawTable(editor) {
  13886. var cm = editor.codemirror;
  13887. var stat = getState(cm);
  13888. var options = editor.options;
  13889. _replaceSelection(cm, stat.table, options.insertTexts.table);
  13890. }
  13891. /**
  13892. * Action for drawing a horizontal rule.
  13893. */
  13894. function drawHorizontalRule(editor) {
  13895. var cm = editor.codemirror;
  13896. var stat = getState(cm);
  13897. var options = editor.options;
  13898. _replaceSelection(cm, stat.image, options.insertTexts.horizontalRule);
  13899. }
  13900. /**
  13901. * Undo action.
  13902. */
  13903. function undo(editor) {
  13904. var cm = editor.codemirror;
  13905. cm.undo();
  13906. cm.focus();
  13907. }
  13908. /**
  13909. * Redo action.
  13910. */
  13911. function redo(editor) {
  13912. var cm = editor.codemirror;
  13913. cm.redo();
  13914. cm.focus();
  13915. }
  13916. /**
  13917. * Toggle side by side preview
  13918. */
  13919. function toggleSideBySide(editor) {
  13920. var cm = editor.codemirror;
  13921. var wrapper = cm.getWrapperElement();
  13922. var preview = wrapper.nextSibling;
  13923. var toolbarButton = editor.toolbarElements["side-by-side"];
  13924. var useSideBySideListener = false;
  13925. if(/editor-preview-active-side/.test(preview.className)) {
  13926. preview.className = preview.className.replace(
  13927. /\s*editor-preview-active-side\s*/g, ""
  13928. );
  13929. toolbarButton.className = toolbarButton.className.replace(/\s*active\s*/g, "");
  13930. wrapper.className = wrapper.className.replace(/\s*CodeMirror-sided\s*/g, " ");
  13931. } else {
  13932. // When the preview button is clicked for the first time,
  13933. // give some time for the transition from editor.css to fire and the view to slide from right to left,
  13934. // instead of just appearing.
  13935. setTimeout(function() {
  13936. if(!cm.getOption("fullScreen"))
  13937. toggleFullScreen(editor);
  13938. preview.className += " editor-preview-active-side";
  13939. }, 1);
  13940. toolbarButton.className += " active";
  13941. wrapper.className += " CodeMirror-sided";
  13942. useSideBySideListener = true;
  13943. }
  13944. // Hide normal preview if active
  13945. var previewNormal = wrapper.lastChild;
  13946. if(/editor-preview-active/.test(previewNormal.className)) {
  13947. previewNormal.className = previewNormal.className.replace(
  13948. /\s*editor-preview-active\s*/g, ""
  13949. );
  13950. var toolbar = editor.toolbarElements.preview;
  13951. var toolbar_div = wrapper.previousSibling;
  13952. toolbar.className = toolbar.className.replace(/\s*active\s*/g, "");
  13953. toolbar_div.className = toolbar_div.className.replace(/\s*disabled-for-preview*/g, "");
  13954. }
  13955. var sideBySideRenderingFunction = function() {
  13956. preview.innerHTML = editor.options.previewRender(editor.value(), preview);
  13957. };
  13958. if(!cm.sideBySideRenderingFunction) {
  13959. cm.sideBySideRenderingFunction = sideBySideRenderingFunction;
  13960. }
  13961. if(useSideBySideListener) {
  13962. preview.innerHTML = editor.options.previewRender(editor.value(), preview);
  13963. cm.on("update", cm.sideBySideRenderingFunction);
  13964. } else {
  13965. cm.off("update", cm.sideBySideRenderingFunction);
  13966. }
  13967. // Refresh to fix selection being off (#309)
  13968. cm.refresh();
  13969. }
  13970. /**
  13971. * Preview action.
  13972. */
  13973. function togglePreview(editor) {
  13974. var cm = editor.codemirror;
  13975. var wrapper = cm.getWrapperElement();
  13976. var toolbar_div = wrapper.previousSibling;
  13977. var toolbar = editor.options.toolbar ? editor.toolbarElements.preview : false;
  13978. var preview = wrapper.lastChild;
  13979. if(!preview || !/editor-preview/.test(preview.className)) {
  13980. preview = document.createElement("div");
  13981. preview.className = "editor-preview";
  13982. wrapper.appendChild(preview);
  13983. }
  13984. if(/editor-preview-active/.test(preview.className)) {
  13985. preview.className = preview.className.replace(
  13986. /\s*editor-preview-active\s*/g, ""
  13987. );
  13988. if(toolbar) {
  13989. toolbar.className = toolbar.className.replace(/\s*active\s*/g, "");
  13990. toolbar_div.className = toolbar_div.className.replace(/\s*disabled-for-preview*/g, "");
  13991. }
  13992. } else {
  13993. // When the preview button is clicked for the first time,
  13994. // give some time for the transition from editor.css to fire and the view to slide from right to left,
  13995. // instead of just appearing.
  13996. setTimeout(function() {
  13997. preview.className += " editor-preview-active";
  13998. }, 1);
  13999. if(toolbar) {
  14000. toolbar.className += " active";
  14001. toolbar_div.className += " disabled-for-preview";
  14002. }
  14003. }
  14004. preview.innerHTML = editor.options.previewRender(editor.value(), preview);
  14005. // Turn off side by side if needed
  14006. var sidebyside = cm.getWrapperElement().nextSibling;
  14007. if(/editor-preview-active-side/.test(sidebyside.className))
  14008. toggleSideBySide(editor);
  14009. }
  14010. function _replaceSelection(cm, active, startEnd, url) {
  14011. if(/editor-preview-active/.test(cm.getWrapperElement().lastChild.className))
  14012. return;
  14013. var text;
  14014. var start = startEnd[0];
  14015. var end = startEnd[1];
  14016. var startPoint = {},
  14017. endPoint = {};
  14018. Object.assign(startPoint, cm.getCursor("start"));
  14019. Object.assign(endPoint, cm.getCursor("end"));
  14020. if(url) {
  14021. end = end.replace("#url#", url);
  14022. }
  14023. if(active) {
  14024. text = cm.getLine(startPoint.line);
  14025. start = text.slice(0, startPoint.ch);
  14026. end = text.slice(startPoint.ch);
  14027. cm.replaceRange(start + end, {
  14028. line: startPoint.line,
  14029. ch: 0
  14030. });
  14031. } else {
  14032. text = cm.getSelection();
  14033. cm.replaceSelection(start + text + end);
  14034. startPoint.ch += start.length;
  14035. if(startPoint !== endPoint) {
  14036. endPoint.ch += start.length;
  14037. }
  14038. }
  14039. cm.setSelection(startPoint, endPoint);
  14040. cm.focus();
  14041. }
  14042. function _toggleHeading(cm, direction, size) {
  14043. if(/editor-preview-active/.test(cm.getWrapperElement().lastChild.className))
  14044. return;
  14045. var startPoint = cm.getCursor("start");
  14046. var endPoint = cm.getCursor("end");
  14047. for(var i = startPoint.line; i <= endPoint.line; i++) {
  14048. (function(i) {
  14049. var text = cm.getLine(i);
  14050. var currHeadingLevel = text.search(/[^#]/);
  14051. if(direction !== undefined) {
  14052. if(currHeadingLevel <= 0) {
  14053. if(direction == "bigger") {
  14054. text = "###### " + text;
  14055. } else {
  14056. text = "# " + text;
  14057. }
  14058. } else if(currHeadingLevel == 6 && direction == "smaller") {
  14059. text = text.substr(7);
  14060. } else if(currHeadingLevel == 1 && direction == "bigger") {
  14061. text = text.substr(2);
  14062. } else {
  14063. if(direction == "bigger") {
  14064. text = text.substr(1);
  14065. } else {
  14066. text = "#" + text;
  14067. }
  14068. }
  14069. } else {
  14070. if(size == 1) {
  14071. if(currHeadingLevel <= 0) {
  14072. text = "# " + text;
  14073. } else if(currHeadingLevel == size) {
  14074. text = text.substr(currHeadingLevel + 1);
  14075. } else {
  14076. text = "# " + text.substr(currHeadingLevel + 1);
  14077. }
  14078. } else if(size == 2) {
  14079. if(currHeadingLevel <= 0) {
  14080. text = "## " + text;
  14081. } else if(currHeadingLevel == size) {
  14082. text = text.substr(currHeadingLevel + 1);
  14083. } else {
  14084. text = "## " + text.substr(currHeadingLevel + 1);
  14085. }
  14086. } else {
  14087. if(currHeadingLevel <= 0) {
  14088. text = "### " + text;
  14089. } else if(currHeadingLevel == size) {
  14090. text = text.substr(currHeadingLevel + 1);
  14091. } else {
  14092. text = "### " + text.substr(currHeadingLevel + 1);
  14093. }
  14094. }
  14095. }
  14096. cm.replaceRange(text, {
  14097. line: i,
  14098. ch: 0
  14099. }, {
  14100. line: i,
  14101. ch: 99999999999999
  14102. });
  14103. })(i);
  14104. }
  14105. cm.focus();
  14106. }
  14107. function _toggleLine(cm, name) {
  14108. if(/editor-preview-active/.test(cm.getWrapperElement().lastChild.className))
  14109. return;
  14110. var listRegexp = /^(\s*)(\*|\-|\+|\d*\.)(\s+)/;
  14111. var whitespacesRegexp = /^\s*/;
  14112. var stat = getState(cm);
  14113. var startPoint = cm.getCursor("start");
  14114. var endPoint = cm.getCursor("end");
  14115. var repl = {
  14116. "quote": /^(\s*)\>\s+/,
  14117. "unordered-list": listRegexp,
  14118. "ordered-list": listRegexp
  14119. };
  14120. var map = {
  14121. "quote": ">",
  14122. "unordered-list": "*",
  14123. "ordered-list": "1."
  14124. };
  14125. for(var i = startPoint.line; i <= endPoint.line; i++) {
  14126. (function(i) {
  14127. var text = cm.getLine(i);
  14128. if(stat[name]) {
  14129. text = text.replace(repl[name], "$1");
  14130. } else {
  14131. var arr = listRegexp.exec(text);
  14132. if(arr !== null) {
  14133. var char = map[name];
  14134. if(arr[2] && arr[2] == map[name]) {
  14135. char = "";
  14136. }
  14137. text = arr[1] + char + arr[3] + text.replace(whitespacesRegexp, "").replace(repl[name], "$1");
  14138. } else {
  14139. text = map[name] + " " + text;
  14140. }
  14141. }
  14142. cm.replaceRange(text, {
  14143. line: i,
  14144. ch: 0
  14145. }, {
  14146. line: i,
  14147. ch: 99999999999999
  14148. });
  14149. })(i);
  14150. }
  14151. cm.focus();
  14152. }
  14153. function _toggleBlock(editor, type, start_chars, end_chars) {
  14154. if(/editor-preview-active/.test(editor.codemirror.getWrapperElement().lastChild.className))
  14155. return;
  14156. end_chars = (typeof end_chars === "undefined") ? start_chars : end_chars;
  14157. var cm = editor.codemirror;
  14158. var stat = getState(cm);
  14159. var text;
  14160. var start = start_chars;
  14161. var end = end_chars;
  14162. var startPoint = cm.getCursor("start");
  14163. var endPoint = cm.getCursor("end");
  14164. if(stat[type]) {
  14165. text = cm.getLine(startPoint.line);
  14166. start = text.slice(0, startPoint.ch);
  14167. end = text.slice(startPoint.ch);
  14168. if(type == "bold") {
  14169. start = start.replace(/(\*\*|__)(?![\s\S]*(\*\*|__))/, "");
  14170. end = end.replace(/(\*\*|__)/, "");
  14171. } else if(type == "italic") {
  14172. start = start.replace(/(\*|_)(?![\s\S]*(\*|_))/, "");
  14173. end = end.replace(/(\*|_)/, "");
  14174. } else if(type == "strikethrough") {
  14175. start = start.replace(/(\*\*|~~)(?![\s\S]*(\*\*|~~))/, "");
  14176. end = end.replace(/(\*\*|~~)/, "");
  14177. }
  14178. cm.replaceRange(start + end, {
  14179. line: startPoint.line,
  14180. ch: 0
  14181. }, {
  14182. line: startPoint.line,
  14183. ch: 99999999999999
  14184. });
  14185. if(type == "bold" || type == "strikethrough") {
  14186. startPoint.ch -= 2;
  14187. if(startPoint !== endPoint) {
  14188. endPoint.ch -= 2;
  14189. }
  14190. } else if(type == "italic") {
  14191. startPoint.ch -= 1;
  14192. if(startPoint !== endPoint) {
  14193. endPoint.ch -= 1;
  14194. }
  14195. }
  14196. } else {
  14197. text = cm.getSelection();
  14198. if(type == "bold") {
  14199. text = text.split("**").join("");
  14200. text = text.split("__").join("");
  14201. } else if(type == "italic") {
  14202. text = text.split("*").join("");
  14203. text = text.split("_").join("");
  14204. } else if(type == "strikethrough") {
  14205. text = text.split("~~").join("");
  14206. }
  14207. cm.replaceSelection(start + text + end);
  14208. startPoint.ch += start_chars.length;
  14209. endPoint.ch = startPoint.ch + text.length;
  14210. }
  14211. cm.setSelection(startPoint, endPoint);
  14212. cm.focus();
  14213. }
  14214. function _cleanBlock(cm) {
  14215. if(/editor-preview-active/.test(cm.getWrapperElement().lastChild.className))
  14216. return;
  14217. var startPoint = cm.getCursor("start");
  14218. var endPoint = cm.getCursor("end");
  14219. var text;
  14220. for(var line = startPoint.line; line <= endPoint.line; line++) {
  14221. text = cm.getLine(line);
  14222. text = text.replace(/^[ ]*([# ]+|\*|\-|[> ]+|[0-9]+(.|\)))[ ]*/, "");
  14223. cm.replaceRange(text, {
  14224. line: line,
  14225. ch: 0
  14226. }, {
  14227. line: line,
  14228. ch: 99999999999999
  14229. });
  14230. }
  14231. }
  14232. // Merge the properties of one object into another.
  14233. function _mergeProperties(target, source) {
  14234. for(var property in source) {
  14235. if(source.hasOwnProperty(property)) {
  14236. if(source[property] instanceof Array) {
  14237. target[property] = source[property].concat(target[property] instanceof Array ? target[property] : []);
  14238. } else if(
  14239. source[property] !== null &&
  14240. typeof source[property] === "object" &&
  14241. source[property].constructor === Object
  14242. ) {
  14243. target[property] = _mergeProperties(target[property] || {}, source[property]);
  14244. } else {
  14245. target[property] = source[property];
  14246. }
  14247. }
  14248. }
  14249. return target;
  14250. }
  14251. // Merge an arbitrary number of objects into one.
  14252. function extend(target) {
  14253. for(var i = 1; i < arguments.length; i++) {
  14254. target = _mergeProperties(target, arguments[i]);
  14255. }
  14256. return target;
  14257. }
  14258. /* The right word count in respect for CJK. */
  14259. function wordCount(data) {
  14260. var pattern = /[a-zA-Z0-9_\u0392-\u03c9\u0410-\u04F9]+|[\u4E00-\u9FFF\u3400-\u4dbf\uf900-\ufaff\u3040-\u309f\uac00-\ud7af]+/g;
  14261. var m = data.match(pattern);
  14262. var count = 0;
  14263. if(m === null) return count;
  14264. for(var i = 0; i < m.length; i++) {
  14265. if(m[i].charCodeAt(0) >= 0x4E00) {
  14266. count += m[i].length;
  14267. } else {
  14268. count += 1;
  14269. }
  14270. }
  14271. return count;
  14272. }
  14273. var toolbarBuiltInButtons = {
  14274. "bold": {
  14275. name: "bold",
  14276. action: toggleBold,
  14277. className: "fa fa-bold",
  14278. title: "Bold",
  14279. default: true
  14280. },
  14281. "italic": {
  14282. name: "italic",
  14283. action: toggleItalic,
  14284. className: "fa fa-italic",
  14285. title: "Italic",
  14286. default: true
  14287. },
  14288. "strikethrough": {
  14289. name: "strikethrough",
  14290. action: toggleStrikethrough,
  14291. className: "fa fa-strikethrough",
  14292. title: "Strikethrough"
  14293. },
  14294. "heading": {
  14295. name: "heading",
  14296. action: toggleHeadingSmaller,
  14297. className: "fa fa-header",
  14298. title: "Heading",
  14299. default: true
  14300. },
  14301. "heading-smaller": {
  14302. name: "heading-smaller",
  14303. action: toggleHeadingSmaller,
  14304. className: "fa fa-header fa-header-x fa-header-smaller",
  14305. title: "Smaller Heading"
  14306. },
  14307. "heading-bigger": {
  14308. name: "heading-bigger",
  14309. action: toggleHeadingBigger,
  14310. className: "fa fa-header fa-header-x fa-header-bigger",
  14311. title: "Bigger Heading"
  14312. },
  14313. "heading-1": {
  14314. name: "heading-1",
  14315. action: toggleHeading1,
  14316. className: "fa fa-header fa-header-x fa-header-1",
  14317. title: "Big Heading"
  14318. },
  14319. "heading-2": {
  14320. name: "heading-2",
  14321. action: toggleHeading2,
  14322. className: "fa fa-header fa-header-x fa-header-2",
  14323. title: "Medium Heading"
  14324. },
  14325. "heading-3": {
  14326. name: "heading-3",
  14327. action: toggleHeading3,
  14328. className: "fa fa-header fa-header-x fa-header-3",
  14329. title: "Small Heading"
  14330. },
  14331. "separator-1": {
  14332. name: "separator-1"
  14333. },
  14334. "code": {
  14335. name: "code",
  14336. action: toggleCodeBlock,
  14337. className: "fa fa-code",
  14338. title: "Code"
  14339. },
  14340. "quote": {
  14341. name: "quote",
  14342. action: toggleBlockquote,
  14343. className: "fa fa-quote-left",
  14344. title: "Quote",
  14345. default: true
  14346. },
  14347. "unordered-list": {
  14348. name: "unordered-list",
  14349. action: toggleUnorderedList,
  14350. className: "fa fa-list-ul",
  14351. title: "Generic List",
  14352. default: true
  14353. },
  14354. "ordered-list": {
  14355. name: "ordered-list",
  14356. action: toggleOrderedList,
  14357. className: "fa fa-list-ol",
  14358. title: "Numbered List",
  14359. default: true
  14360. },
  14361. "clean-block": {
  14362. name: "clean-block",
  14363. action: cleanBlock,
  14364. className: "fa fa-eraser fa-clean-block",
  14365. title: "Clean block"
  14366. },
  14367. "separator-2": {
  14368. name: "separator-2"
  14369. },
  14370. "link": {
  14371. name: "link",
  14372. action: drawLink,
  14373. className: "fa fa-link",
  14374. title: "Create Link",
  14375. default: true
  14376. },
  14377. "image": {
  14378. name: "image",
  14379. action: drawImage,
  14380. className: "fa fa-picture-o",
  14381. title: "Insert Image",
  14382. default: true
  14383. },
  14384. "table": {
  14385. name: "table",
  14386. action: drawTable,
  14387. className: "fa fa-table",
  14388. title: "Insert Table"
  14389. },
  14390. "horizontal-rule": {
  14391. name: "horizontal-rule",
  14392. action: drawHorizontalRule,
  14393. className: "fa fa-minus",
  14394. title: "Insert Horizontal Line"
  14395. },
  14396. "separator-3": {
  14397. name: "separator-3"
  14398. },
  14399. "preview": {
  14400. name: "preview",
  14401. action: togglePreview,
  14402. className: "fa fa-eye no-disable",
  14403. title: "Toggle Preview",
  14404. default: true
  14405. },
  14406. "side-by-side": {
  14407. name: "side-by-side",
  14408. action: toggleSideBySide,
  14409. className: "fa fa-columns no-disable no-mobile",
  14410. title: "Toggle Side by Side",
  14411. default: true
  14412. },
  14413. "fullscreen": {
  14414. name: "fullscreen",
  14415. action: toggleFullScreen,
  14416. className: "fa fa-arrows-alt no-disable no-mobile",
  14417. title: "Toggle Fullscreen",
  14418. default: true
  14419. },
  14420. "separator-4": {
  14421. name: "separator-4"
  14422. },
  14423. "guide": {
  14424. name: "guide",
  14425. action: "https://simplemde.com/markdown-guide",
  14426. className: "fa fa-question-circle",
  14427. title: "Markdown Guide",
  14428. default: true
  14429. },
  14430. "separator-5": {
  14431. name: "separator-5"
  14432. },
  14433. "undo": {
  14434. name: "undo",
  14435. action: undo,
  14436. className: "fa fa-undo no-disable",
  14437. title: "Undo"
  14438. },
  14439. "redo": {
  14440. name: "redo",
  14441. action: redo,
  14442. className: "fa fa-repeat no-disable",
  14443. title: "Redo"
  14444. }
  14445. };
  14446. var insertTexts = {
  14447. link: ["[", "](#url#)"],
  14448. image: ["![](", "#url#)"],
  14449. table: ["", "\n\n| Column 1 | Column 2 | Column 3 |\n| -------- | -------- | -------- |\n| Text | Text | Text |\n\n"],
  14450. horizontalRule: ["", "\n\n-----\n\n"]
  14451. };
  14452. var promptTexts = {
  14453. link: "URL for the link:",
  14454. image: "URL of the image:"
  14455. };
  14456. var blockStyles = {
  14457. "bold": "**",
  14458. "code": "```",
  14459. "italic": "*"
  14460. };
  14461. /**
  14462. * Interface of SimpleMDE.
  14463. */
  14464. function SimpleMDE(options) {
  14465. // Handle options parameter
  14466. options = options || {};
  14467. // Used later to refer to it"s parent
  14468. options.parent = this;
  14469. // Check if Font Awesome needs to be auto downloaded
  14470. var autoDownloadFA = true;
  14471. if(options.autoDownloadFontAwesome === false) {
  14472. autoDownloadFA = false;
  14473. }
  14474. if(options.autoDownloadFontAwesome !== true) {
  14475. var styleSheets = document.styleSheets;
  14476. for(var i = 0; i < styleSheets.length; i++) {
  14477. if(!styleSheets[i].href)
  14478. continue;
  14479. if(styleSheets[i].href.indexOf("//maxcdn.bootstrapcdn.com/font-awesome/") > -1) {
  14480. autoDownloadFA = false;
  14481. }
  14482. }
  14483. }
  14484. if(autoDownloadFA) {
  14485. var link = document.createElement("link");
  14486. link.rel = "stylesheet";
  14487. link.href = "https://maxcdn.bootstrapcdn.com/font-awesome/latest/css/font-awesome.min.css";
  14488. document.getElementsByTagName("head")[0].appendChild(link);
  14489. }
  14490. // Find the textarea to use
  14491. if(options.element) {
  14492. this.element = options.element;
  14493. } else if(options.element === null) {
  14494. // This means that the element option was specified, but no element was found
  14495. console.log("SimpleMDE: Error. No element was found.");
  14496. return;
  14497. }
  14498. // Handle toolbar
  14499. if(options.toolbar === undefined) {
  14500. // Initialize
  14501. options.toolbar = [];
  14502. // Loop over the built in buttons, to get the preferred order
  14503. for(var key in toolbarBuiltInButtons) {
  14504. if(toolbarBuiltInButtons.hasOwnProperty(key)) {
  14505. if(key.indexOf("separator-") != -1) {
  14506. options.toolbar.push("|");
  14507. }
  14508. if(toolbarBuiltInButtons[key].default === true || (options.showIcons && options.showIcons.constructor === Array && options.showIcons.indexOf(key) != -1)) {
  14509. options.toolbar.push(key);
  14510. }
  14511. }
  14512. }
  14513. }
  14514. // Handle status bar
  14515. if(!options.hasOwnProperty("status")) {
  14516. options.status = ["autosave", "lines", "words", "cursor"];
  14517. }
  14518. // Add default preview rendering function
  14519. if(!options.previewRender) {
  14520. options.previewRender = function(plainText) {
  14521. // Note: "this" refers to the options object
  14522. return this.parent.markdown(plainText);
  14523. };
  14524. }
  14525. // Set default options for parsing config
  14526. options.parsingConfig = extend({
  14527. highlightFormatting: true // needed for toggleCodeBlock to detect types of code
  14528. }, options.parsingConfig || {});
  14529. // Merging the insertTexts, with the given options
  14530. options.insertTexts = extend({}, insertTexts, options.insertTexts || {});
  14531. // Merging the promptTexts, with the given options
  14532. options.promptTexts = promptTexts;
  14533. // Merging the blockStyles, with the given options
  14534. options.blockStyles = extend({}, blockStyles, options.blockStyles || {});
  14535. // Merging the shortcuts, with the given options
  14536. options.shortcuts = extend({}, shortcuts, options.shortcuts || {});
  14537. options.minHeight = options.minHeight || "300px";
  14538. // Change unique_id to uniqueId for backwards compatibility
  14539. if(options.autosave != undefined && options.autosave.unique_id != undefined && options.autosave.unique_id != "")
  14540. options.autosave.uniqueId = options.autosave.unique_id;
  14541. // Update this options
  14542. this.options = options;
  14543. // Auto render
  14544. this.render();
  14545. // The codemirror component is only available after rendering
  14546. // so, the setter for the initialValue can only run after
  14547. // the element has been rendered
  14548. if(options.initialValue && (!this.options.autosave || this.options.autosave.foundSavedValue !== true)) {
  14549. this.value(options.initialValue);
  14550. }
  14551. }
  14552. /**
  14553. * Default markdown render.
  14554. */
  14555. SimpleMDE.prototype.markdown = function(text) {
  14556. if(marked) {
  14557. // Initialize
  14558. var markedOptions;
  14559. if(this.options && this.options.renderingConfig && this.options.renderingConfig.markedOptions) {
  14560. markedOptions = this.options.renderingConfig.markedOptions;
  14561. } else {
  14562. markedOptions = {};
  14563. }
  14564. // Update options
  14565. if(this.options && this.options.renderingConfig && this.options.renderingConfig.singleLineBreaks === false) {
  14566. markedOptions.breaks = false;
  14567. } else {
  14568. markedOptions.breaks = true;
  14569. }
  14570. if(this.options && this.options.renderingConfig && this.options.renderingConfig.codeSyntaxHighlighting === true) {
  14571. /* Get HLJS from config or window */
  14572. var hljs = this.options.renderingConfig.hljs || window.hljs;
  14573. /* Check if HLJS loaded */
  14574. if(hljs) {
  14575. markedOptions.highlight = function(code) {
  14576. return hljs.highlightAuto(code).value;
  14577. };
  14578. }
  14579. }
  14580. // Set options
  14581. marked.setOptions(markedOptions);
  14582. // Return
  14583. return marked(text);
  14584. }
  14585. };
  14586. /**
  14587. * Render editor to the given element.
  14588. */
  14589. SimpleMDE.prototype.render = function(el) {
  14590. if(!el) {
  14591. el = this.element || document.getElementsByTagName("textarea")[0];
  14592. }
  14593. if(this._rendered && this._rendered === el) {
  14594. // Already rendered.
  14595. return;
  14596. }
  14597. this.element = el;
  14598. var options = this.options;
  14599. var self = this;
  14600. var keyMaps = {};
  14601. for(var key in options.shortcuts) {
  14602. // null stands for "do not bind this command"
  14603. if(options.shortcuts[key] !== null && bindings[key] !== null) {
  14604. (function(key) {
  14605. keyMaps[fixShortcut(options.shortcuts[key])] = function() {
  14606. bindings[key](self);
  14607. };
  14608. })(key);
  14609. }
  14610. }
  14611. keyMaps["Enter"] = "newlineAndIndentContinueMarkdownList";
  14612. keyMaps["Tab"] = "tabAndIndentMarkdownList";
  14613. keyMaps["Shift-Tab"] = "shiftTabAndUnindentMarkdownList";
  14614. keyMaps["Esc"] = function(cm) {
  14615. if(cm.getOption("fullScreen")) toggleFullScreen(self);
  14616. };
  14617. document.addEventListener("keydown", function(e) {
  14618. e = e || window.event;
  14619. if(e.keyCode == 27) {
  14620. if(self.codemirror.getOption("fullScreen")) toggleFullScreen(self);
  14621. }
  14622. }, false);
  14623. var mode, backdrop;
  14624. if(options.spellChecker !== false) {
  14625. mode = "spell-checker";
  14626. backdrop = options.parsingConfig;
  14627. backdrop.name = "gfm";
  14628. backdrop.gitHubSpice = false;
  14629. CodeMirrorSpellChecker({
  14630. codeMirrorInstance: CodeMirror
  14631. });
  14632. } else {
  14633. mode = options.parsingConfig;
  14634. mode.name = "gfm";
  14635. mode.gitHubSpice = false;
  14636. }
  14637. this.codemirror = CodeMirror.fromTextArea(el, {
  14638. mode: mode,
  14639. backdrop: backdrop,
  14640. theme: "paper",
  14641. tabSize: (options.tabSize != undefined) ? options.tabSize : 2,
  14642. indentUnit: (options.tabSize != undefined) ? options.tabSize : 2,
  14643. indentWithTabs: (options.indentWithTabs === false) ? false : true,
  14644. lineNumbers: false,
  14645. autofocus: (options.autofocus === true) ? true : false,
  14646. extraKeys: keyMaps,
  14647. lineWrapping: (options.lineWrapping === false) ? false : true,
  14648. allowDropFileTypes: ["text/plain"],
  14649. placeholder: options.placeholder || el.getAttribute("placeholder") || "",
  14650. styleSelectedText: (options.styleSelectedText != undefined) ? options.styleSelectedText : true
  14651. });
  14652. this.codemirror.getScrollerElement().style.minHeight = options.minHeight;
  14653. if(options.forceSync === true) {
  14654. var cm = this.codemirror;
  14655. cm.on("change", function() {
  14656. cm.save();
  14657. });
  14658. }
  14659. this.gui = {};
  14660. if(options.toolbar !== false) {
  14661. this.gui.toolbar = this.createToolbar();
  14662. }
  14663. if(options.status !== false) {
  14664. this.gui.statusbar = this.createStatusbar();
  14665. }
  14666. if(options.autosave != undefined && options.autosave.enabled === true) {
  14667. this.autosave();
  14668. }
  14669. this.gui.sideBySide = this.createSideBySide();
  14670. this._rendered = this.element;
  14671. // Fixes CodeMirror bug (#344)
  14672. var temp_cm = this.codemirror;
  14673. setTimeout(function() {
  14674. temp_cm.refresh();
  14675. }.bind(temp_cm), 0);
  14676. };
  14677. // 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.
  14678. function isLocalStorageAvailable() {
  14679. if(typeof localStorage === "object") {
  14680. try {
  14681. localStorage.setItem("smde_localStorage", 1);
  14682. localStorage.removeItem("smde_localStorage");
  14683. } catch(e) {
  14684. return false;
  14685. }
  14686. } else {
  14687. return false;
  14688. }
  14689. return true;
  14690. }
  14691. SimpleMDE.prototype.autosave = function() {
  14692. if(isLocalStorageAvailable()) {
  14693. var simplemde = this;
  14694. if(this.options.autosave.uniqueId == undefined || this.options.autosave.uniqueId == "") {
  14695. console.log("SimpleMDE: You must set a uniqueId to use the autosave feature");
  14696. return;
  14697. }
  14698. if(simplemde.element.form != null && simplemde.element.form != undefined) {
  14699. simplemde.element.form.addEventListener("submit", function() {
  14700. localStorage.removeItem("smde_" + simplemde.options.autosave.uniqueId);
  14701. });
  14702. }
  14703. if(this.options.autosave.loaded !== true) {
  14704. if(typeof localStorage.getItem("smde_" + this.options.autosave.uniqueId) == "string" && localStorage.getItem("smde_" + this.options.autosave.uniqueId) != "") {
  14705. this.codemirror.setValue(localStorage.getItem("smde_" + this.options.autosave.uniqueId));
  14706. this.options.autosave.foundSavedValue = true;
  14707. }
  14708. this.options.autosave.loaded = true;
  14709. }
  14710. localStorage.setItem("smde_" + this.options.autosave.uniqueId, simplemde.value());
  14711. var el = document.getElementById("autosaved");
  14712. if(el != null && el != undefined && el != "") {
  14713. var d = new Date();
  14714. var hh = d.getHours();
  14715. var m = d.getMinutes();
  14716. var dd = "am";
  14717. var h = hh;
  14718. if(h >= 12) {
  14719. h = hh - 12;
  14720. dd = "pm";
  14721. }
  14722. if(h == 0) {
  14723. h = 12;
  14724. }
  14725. m = m < 10 ? "0" + m : m;
  14726. el.innerHTML = "Autosaved: " + h + ":" + m + " " + dd;
  14727. }
  14728. this.autosaveTimeoutId = setTimeout(function() {
  14729. simplemde.autosave();
  14730. }, this.options.autosave.delay || 10000);
  14731. } else {
  14732. console.log("SimpleMDE: localStorage not available, cannot autosave");
  14733. }
  14734. };
  14735. SimpleMDE.prototype.clearAutosavedValue = function() {
  14736. if(isLocalStorageAvailable()) {
  14737. if(this.options.autosave == undefined || this.options.autosave.uniqueId == undefined || this.options.autosave.uniqueId == "") {
  14738. console.log("SimpleMDE: You must set a uniqueId to clear the autosave value");
  14739. return;
  14740. }
  14741. localStorage.removeItem("smde_" + this.options.autosave.uniqueId);
  14742. } else {
  14743. console.log("SimpleMDE: localStorage not available, cannot autosave");
  14744. }
  14745. };
  14746. SimpleMDE.prototype.createSideBySide = function() {
  14747. var cm = this.codemirror;
  14748. var wrapper = cm.getWrapperElement();
  14749. var preview = wrapper.nextSibling;
  14750. if(!preview || !/editor-preview-side/.test(preview.className)) {
  14751. preview = document.createElement("div");
  14752. preview.className = "editor-preview-side";
  14753. wrapper.parentNode.insertBefore(preview, wrapper.nextSibling);
  14754. }
  14755. // Syncs scroll editor -> preview
  14756. var cScroll = false;
  14757. var pScroll = false;
  14758. cm.on("scroll", function(v) {
  14759. if(cScroll) {
  14760. cScroll = false;
  14761. return;
  14762. }
  14763. pScroll = true;
  14764. var height = v.getScrollInfo().height - v.getScrollInfo().clientHeight;
  14765. var ratio = parseFloat(v.getScrollInfo().top) / height;
  14766. var move = (preview.scrollHeight - preview.clientHeight) * ratio;
  14767. preview.scrollTop = move;
  14768. });
  14769. // Syncs scroll preview -> editor
  14770. preview.onscroll = function() {
  14771. if(pScroll) {
  14772. pScroll = false;
  14773. return;
  14774. }
  14775. cScroll = true;
  14776. var height = preview.scrollHeight - preview.clientHeight;
  14777. var ratio = parseFloat(preview.scrollTop) / height;
  14778. var move = (cm.getScrollInfo().height - cm.getScrollInfo().clientHeight) * ratio;
  14779. cm.scrollTo(0, move);
  14780. };
  14781. return preview;
  14782. };
  14783. SimpleMDE.prototype.createToolbar = function(items) {
  14784. items = items || this.options.toolbar;
  14785. if(!items || items.length === 0) {
  14786. return;
  14787. }
  14788. var i;
  14789. for(i = 0; i < items.length; i++) {
  14790. if(toolbarBuiltInButtons[items[i]] != undefined) {
  14791. items[i] = toolbarBuiltInButtons[items[i]];
  14792. }
  14793. }
  14794. var bar = document.createElement("div");
  14795. bar.className = "editor-toolbar";
  14796. var self = this;
  14797. var toolbarData = {};
  14798. self.toolbar = items;
  14799. for(i = 0; i < items.length; i++) {
  14800. if(items[i].name == "guide" && self.options.toolbarGuideIcon === false)
  14801. continue;
  14802. if(self.options.hideIcons && self.options.hideIcons.indexOf(items[i].name) != -1)
  14803. continue;
  14804. // Fullscreen does not work well on mobile devices (even tablets)
  14805. // In the future, hopefully this can be resolved
  14806. if((items[i].name == "fullscreen" || items[i].name == "side-by-side") && isMobile())
  14807. continue;
  14808. // Don't include trailing separators
  14809. if(items[i] === "|") {
  14810. var nonSeparatorIconsFollow = false;
  14811. for(var x = (i + 1); x < items.length; x++) {
  14812. if(items[x] !== "|" && (!self.options.hideIcons || self.options.hideIcons.indexOf(items[x].name) == -1)) {
  14813. nonSeparatorIconsFollow = true;
  14814. }
  14815. }
  14816. if(!nonSeparatorIconsFollow)
  14817. continue;
  14818. }
  14819. // Create the icon and append to the toolbar
  14820. (function(item) {
  14821. var el;
  14822. if(item === "|") {
  14823. el = createSep();
  14824. } else {
  14825. el = createIcon(item, self.options.toolbarTips, self.options.shortcuts);
  14826. }
  14827. // bind events, special for info
  14828. if(item.action) {
  14829. if(typeof item.action === "function") {
  14830. el.onclick = function(e) {
  14831. e.preventDefault();
  14832. item.action(self);
  14833. };
  14834. } else if(typeof item.action === "string") {
  14835. el.href = item.action;
  14836. el.target = "_blank";
  14837. }
  14838. }
  14839. toolbarData[item.name || item] = el;
  14840. bar.appendChild(el);
  14841. })(items[i]);
  14842. }
  14843. self.toolbarElements = toolbarData;
  14844. var cm = this.codemirror;
  14845. cm.on("cursorActivity", function() {
  14846. var stat = getState(cm);
  14847. for(var key in toolbarData) {
  14848. (function(key) {
  14849. var el = toolbarData[key];
  14850. if(stat[key]) {
  14851. el.className += " active";
  14852. } else if(key != "fullscreen" && key != "side-by-side") {
  14853. el.className = el.className.replace(/\s*active\s*/g, "");
  14854. }
  14855. })(key);
  14856. }
  14857. });
  14858. var cmWrapper = cm.getWrapperElement();
  14859. cmWrapper.parentNode.insertBefore(bar, cmWrapper);
  14860. return bar;
  14861. };
  14862. SimpleMDE.prototype.createStatusbar = function(status) {
  14863. // Initialize
  14864. status = status || this.options.status;
  14865. var options = this.options;
  14866. var cm = this.codemirror;
  14867. // Make sure the status variable is valid
  14868. if(!status || status.length === 0)
  14869. return;
  14870. // Set up the built-in items
  14871. var items = [];
  14872. var i, onUpdate, defaultValue;
  14873. for(i = 0; i < status.length; i++) {
  14874. // Reset some values
  14875. onUpdate = undefined;
  14876. defaultValue = undefined;
  14877. // Handle if custom or not
  14878. if(typeof status[i] === "object") {
  14879. items.push({
  14880. className: status[i].className,
  14881. defaultValue: status[i].defaultValue,
  14882. onUpdate: status[i].onUpdate
  14883. });
  14884. } else {
  14885. var name = status[i];
  14886. if(name === "words") {
  14887. defaultValue = function(el) {
  14888. el.innerHTML = wordCount(cm.getValue());
  14889. };
  14890. onUpdate = function(el) {
  14891. el.innerHTML = wordCount(cm.getValue());
  14892. };
  14893. } else if(name === "lines") {
  14894. defaultValue = function(el) {
  14895. el.innerHTML = cm.lineCount();
  14896. };
  14897. onUpdate = function(el) {
  14898. el.innerHTML = cm.lineCount();
  14899. };
  14900. } else if(name === "cursor") {
  14901. defaultValue = function(el) {
  14902. el.innerHTML = "0:0";
  14903. };
  14904. onUpdate = function(el) {
  14905. var pos = cm.getCursor();
  14906. el.innerHTML = pos.line + ":" + pos.ch;
  14907. };
  14908. } else if(name === "autosave") {
  14909. defaultValue = function(el) {
  14910. if(options.autosave != undefined && options.autosave.enabled === true) {
  14911. el.setAttribute("id", "autosaved");
  14912. }
  14913. };
  14914. }
  14915. items.push({
  14916. className: name,
  14917. defaultValue: defaultValue,
  14918. onUpdate: onUpdate
  14919. });
  14920. }
  14921. }
  14922. // Create element for the status bar
  14923. var bar = document.createElement("div");
  14924. bar.className = "editor-statusbar";
  14925. // Create a new span for each item
  14926. for(i = 0; i < items.length; i++) {
  14927. // Store in temporary variable
  14928. var item = items[i];
  14929. // Create span element
  14930. var el = document.createElement("span");
  14931. el.className = item.className;
  14932. // Ensure the defaultValue is a function
  14933. if(typeof item.defaultValue === "function") {
  14934. item.defaultValue(el);
  14935. }
  14936. // Ensure the onUpdate is a function
  14937. if(typeof item.onUpdate === "function") {
  14938. // Create a closure around the span of the current action, then execute the onUpdate handler
  14939. this.codemirror.on("update", (function(el, item) {
  14940. return function() {
  14941. item.onUpdate(el);
  14942. };
  14943. }(el, item)));
  14944. }
  14945. // Append the item to the status bar
  14946. bar.appendChild(el);
  14947. }
  14948. // Insert the status bar into the DOM
  14949. var cmWrapper = this.codemirror.getWrapperElement();
  14950. cmWrapper.parentNode.insertBefore(bar, cmWrapper.nextSibling);
  14951. return bar;
  14952. };
  14953. /**
  14954. * Get or set the text content.
  14955. */
  14956. SimpleMDE.prototype.value = function(val) {
  14957. if(val === undefined) {
  14958. return this.codemirror.getValue();
  14959. } else {
  14960. this.codemirror.getDoc().setValue(val);
  14961. return this;
  14962. }
  14963. };
  14964. /**
  14965. * Bind static methods for exports.
  14966. */
  14967. SimpleMDE.toggleBold = toggleBold;
  14968. SimpleMDE.toggleItalic = toggleItalic;
  14969. SimpleMDE.toggleStrikethrough = toggleStrikethrough;
  14970. SimpleMDE.toggleBlockquote = toggleBlockquote;
  14971. SimpleMDE.toggleHeadingSmaller = toggleHeadingSmaller;
  14972. SimpleMDE.toggleHeadingBigger = toggleHeadingBigger;
  14973. SimpleMDE.toggleHeading1 = toggleHeading1;
  14974. SimpleMDE.toggleHeading2 = toggleHeading2;
  14975. SimpleMDE.toggleHeading3 = toggleHeading3;
  14976. SimpleMDE.toggleCodeBlock = toggleCodeBlock;
  14977. SimpleMDE.toggleUnorderedList = toggleUnorderedList;
  14978. SimpleMDE.toggleOrderedList = toggleOrderedList;
  14979. SimpleMDE.cleanBlock = cleanBlock;
  14980. SimpleMDE.drawLink = drawLink;
  14981. SimpleMDE.drawImage = drawImage;
  14982. SimpleMDE.drawTable = drawTable;
  14983. SimpleMDE.drawHorizontalRule = drawHorizontalRule;
  14984. SimpleMDE.undo = undo;
  14985. SimpleMDE.redo = redo;
  14986. SimpleMDE.togglePreview = togglePreview;
  14987. SimpleMDE.toggleSideBySide = toggleSideBySide;
  14988. SimpleMDE.toggleFullScreen = toggleFullScreen;
  14989. /**
  14990. * Bind instance methods for exports.
  14991. */
  14992. SimpleMDE.prototype.toggleBold = function() {
  14993. toggleBold(this);
  14994. };
  14995. SimpleMDE.prototype.toggleItalic = function() {
  14996. toggleItalic(this);
  14997. };
  14998. SimpleMDE.prototype.toggleStrikethrough = function() {
  14999. toggleStrikethrough(this);
  15000. };
  15001. SimpleMDE.prototype.toggleBlockquote = function() {
  15002. toggleBlockquote(this);
  15003. };
  15004. SimpleMDE.prototype.toggleHeadingSmaller = function() {
  15005. toggleHeadingSmaller(this);
  15006. };
  15007. SimpleMDE.prototype.toggleHeadingBigger = function() {
  15008. toggleHeadingBigger(this);
  15009. };
  15010. SimpleMDE.prototype.toggleHeading1 = function() {
  15011. toggleHeading1(this);
  15012. };
  15013. SimpleMDE.prototype.toggleHeading2 = function() {
  15014. toggleHeading2(this);
  15015. };
  15016. SimpleMDE.prototype.toggleHeading3 = function() {
  15017. toggleHeading3(this);
  15018. };
  15019. SimpleMDE.prototype.toggleCodeBlock = function() {
  15020. toggleCodeBlock(this);
  15021. };
  15022. SimpleMDE.prototype.toggleUnorderedList = function() {
  15023. toggleUnorderedList(this);
  15024. };
  15025. SimpleMDE.prototype.toggleOrderedList = function() {
  15026. toggleOrderedList(this);
  15027. };
  15028. SimpleMDE.prototype.cleanBlock = function() {
  15029. cleanBlock(this);
  15030. };
  15031. SimpleMDE.prototype.drawLink = function() {
  15032. drawLink(this);
  15033. };
  15034. SimpleMDE.prototype.drawImage = function() {
  15035. drawImage(this);
  15036. };
  15037. SimpleMDE.prototype.drawTable = function() {
  15038. drawTable(this);
  15039. };
  15040. SimpleMDE.prototype.drawHorizontalRule = function() {
  15041. drawHorizontalRule(this);
  15042. };
  15043. SimpleMDE.prototype.undo = function() {
  15044. undo(this);
  15045. };
  15046. SimpleMDE.prototype.redo = function() {
  15047. redo(this);
  15048. };
  15049. SimpleMDE.prototype.togglePreview = function() {
  15050. togglePreview(this);
  15051. };
  15052. SimpleMDE.prototype.toggleSideBySide = function() {
  15053. toggleSideBySide(this);
  15054. };
  15055. SimpleMDE.prototype.toggleFullScreen = function() {
  15056. toggleFullScreen(this);
  15057. };
  15058. SimpleMDE.prototype.isPreviewActive = function() {
  15059. var cm = this.codemirror;
  15060. var wrapper = cm.getWrapperElement();
  15061. var preview = wrapper.lastChild;
  15062. return /editor-preview-active/.test(preview.className);
  15063. };
  15064. SimpleMDE.prototype.isSideBySideActive = function() {
  15065. var cm = this.codemirror;
  15066. var wrapper = cm.getWrapperElement();
  15067. var preview = wrapper.nextSibling;
  15068. return /editor-preview-active-side/.test(preview.className);
  15069. };
  15070. SimpleMDE.prototype.isFullscreenActive = function() {
  15071. var cm = this.codemirror;
  15072. return cm.getOption("fullScreen");
  15073. };
  15074. SimpleMDE.prototype.getState = function() {
  15075. var cm = this.codemirror;
  15076. return getState(cm);
  15077. };
  15078. SimpleMDE.prototype.toTextArea = function() {
  15079. var cm = this.codemirror;
  15080. var wrapper = cm.getWrapperElement();
  15081. if(wrapper.parentNode) {
  15082. if(this.gui.toolbar) {
  15083. wrapper.parentNode.removeChild(this.gui.toolbar);
  15084. }
  15085. if(this.gui.statusbar) {
  15086. wrapper.parentNode.removeChild(this.gui.statusbar);
  15087. }
  15088. if(this.gui.sideBySide) {
  15089. wrapper.parentNode.removeChild(this.gui.sideBySide);
  15090. }
  15091. }
  15092. cm.toTextArea();
  15093. if(this.autosaveTimeoutId) {
  15094. clearTimeout(this.autosaveTimeoutId);
  15095. this.autosaveTimeoutId = undefined;
  15096. this.clearAutosavedValue();
  15097. }
  15098. };
  15099. module.exports = SimpleMDE;
  15100. },{"./codemirror/tablist":19,"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":17}]},{},[20])(20)
  15101. });