simplemde.js 572 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019
  1. /**
  2. * simplemde v1.11.2
  3. * Copyright Next Step Webs, Inc.
  4. * @link https://github.com/NextStepWebs/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.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 (length === undefined) {
  319. array = new Uint8Array(array, byteOffset)
  320. } else {
  321. array = new Uint8Array(array, byteOffset, length)
  322. }
  323. if (Buffer.TYPED_ARRAY_SUPPORT) {
  324. // Return an augmented `Uint8Array` instance, for best performance
  325. that = array
  326. that.__proto__ = Buffer.prototype
  327. } else {
  328. // Fallback: Return an object instance of the Buffer class
  329. that = fromArrayLike(that, array)
  330. }
  331. return that
  332. }
  333. function fromObject (that, obj) {
  334. if (Buffer.isBuffer(obj)) {
  335. var len = checked(obj.length) | 0
  336. that = createBuffer(that, len)
  337. if (that.length === 0) {
  338. return that
  339. }
  340. obj.copy(that, 0, 0, len)
  341. return that
  342. }
  343. if (obj) {
  344. if ((typeof ArrayBuffer !== 'undefined' &&
  345. obj.buffer instanceof ArrayBuffer) || 'length' in obj) {
  346. if (typeof obj.length !== 'number' || isnan(obj.length)) {
  347. return createBuffer(that, 0)
  348. }
  349. return fromArrayLike(that, obj)
  350. }
  351. if (obj.type === 'Buffer' && isArray(obj.data)) {
  352. return fromArrayLike(that, obj.data)
  353. }
  354. }
  355. throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')
  356. }
  357. function checked (length) {
  358. // Note: cannot use `length < kMaxLength` here because that fails when
  359. // length is NaN (which is otherwise coerced to zero.)
  360. if (length >= kMaxLength()) {
  361. throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
  362. 'size: 0x' + kMaxLength().toString(16) + ' bytes')
  363. }
  364. return length | 0
  365. }
  366. function SlowBuffer (length) {
  367. if (+length != length) { // eslint-disable-line eqeqeq
  368. length = 0
  369. }
  370. return Buffer.alloc(+length)
  371. }
  372. Buffer.isBuffer = function isBuffer (b) {
  373. return !!(b != null && b._isBuffer)
  374. }
  375. Buffer.compare = function compare (a, b) {
  376. if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
  377. throw new TypeError('Arguments must be Buffers')
  378. }
  379. if (a === b) return 0
  380. var x = a.length
  381. var y = b.length
  382. for (var i = 0, len = Math.min(x, y); i < len; ++i) {
  383. if (a[i] !== b[i]) {
  384. x = a[i]
  385. y = b[i]
  386. break
  387. }
  388. }
  389. if (x < y) return -1
  390. if (y < x) return 1
  391. return 0
  392. }
  393. Buffer.isEncoding = function isEncoding (encoding) {
  394. switch (String(encoding).toLowerCase()) {
  395. case 'hex':
  396. case 'utf8':
  397. case 'utf-8':
  398. case 'ascii':
  399. case 'binary':
  400. case 'base64':
  401. case 'raw':
  402. case 'ucs2':
  403. case 'ucs-2':
  404. case 'utf16le':
  405. case 'utf-16le':
  406. return true
  407. default:
  408. return false
  409. }
  410. }
  411. Buffer.concat = function concat (list, length) {
  412. if (!isArray(list)) {
  413. throw new TypeError('"list" argument must be an Array of Buffers')
  414. }
  415. if (list.length === 0) {
  416. return Buffer.alloc(0)
  417. }
  418. var i
  419. if (length === undefined) {
  420. length = 0
  421. for (i = 0; i < list.length; i++) {
  422. length += list[i].length
  423. }
  424. }
  425. var buffer = Buffer.allocUnsafe(length)
  426. var pos = 0
  427. for (i = 0; i < list.length; i++) {
  428. var buf = list[i]
  429. if (!Buffer.isBuffer(buf)) {
  430. throw new TypeError('"list" argument must be an Array of Buffers')
  431. }
  432. buf.copy(buffer, pos)
  433. pos += buf.length
  434. }
  435. return buffer
  436. }
  437. function byteLength (string, encoding) {
  438. if (Buffer.isBuffer(string)) {
  439. return string.length
  440. }
  441. if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' &&
  442. (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) {
  443. return string.byteLength
  444. }
  445. if (typeof string !== 'string') {
  446. string = '' + string
  447. }
  448. var len = string.length
  449. if (len === 0) return 0
  450. // Use a for loop to avoid recursion
  451. var loweredCase = false
  452. for (;;) {
  453. switch (encoding) {
  454. case 'ascii':
  455. case 'binary':
  456. // Deprecated
  457. case 'raw':
  458. case 'raws':
  459. return len
  460. case 'utf8':
  461. case 'utf-8':
  462. case undefined:
  463. return utf8ToBytes(string).length
  464. case 'ucs2':
  465. case 'ucs-2':
  466. case 'utf16le':
  467. case 'utf-16le':
  468. return len * 2
  469. case 'hex':
  470. return len >>> 1
  471. case 'base64':
  472. return base64ToBytes(string).length
  473. default:
  474. if (loweredCase) return utf8ToBytes(string).length // assume utf8
  475. encoding = ('' + encoding).toLowerCase()
  476. loweredCase = true
  477. }
  478. }
  479. }
  480. Buffer.byteLength = byteLength
  481. function slowToString (encoding, start, end) {
  482. var loweredCase = false
  483. // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
  484. // property of a typed array.
  485. // This behaves neither like String nor Uint8Array in that we set start/end
  486. // to their upper/lower bounds if the value passed is out of range.
  487. // undefined is handled specially as per ECMA-262 6th Edition,
  488. // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
  489. if (start === undefined || start < 0) {
  490. start = 0
  491. }
  492. // Return early if start > this.length. Done here to prevent potential uint32
  493. // coercion fail below.
  494. if (start > this.length) {
  495. return ''
  496. }
  497. if (end === undefined || end > this.length) {
  498. end = this.length
  499. }
  500. if (end <= 0) {
  501. return ''
  502. }
  503. // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
  504. end >>>= 0
  505. start >>>= 0
  506. if (end <= start) {
  507. return ''
  508. }
  509. if (!encoding) encoding = 'utf8'
  510. while (true) {
  511. switch (encoding) {
  512. case 'hex':
  513. return hexSlice(this, start, end)
  514. case 'utf8':
  515. case 'utf-8':
  516. return utf8Slice(this, start, end)
  517. case 'ascii':
  518. return asciiSlice(this, start, end)
  519. case 'binary':
  520. return binarySlice(this, start, end)
  521. case 'base64':
  522. return base64Slice(this, start, end)
  523. case 'ucs2':
  524. case 'ucs-2':
  525. case 'utf16le':
  526. case 'utf-16le':
  527. return utf16leSlice(this, start, end)
  528. default:
  529. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  530. encoding = (encoding + '').toLowerCase()
  531. loweredCase = true
  532. }
  533. }
  534. }
  535. // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect
  536. // Buffer instances.
  537. Buffer.prototype._isBuffer = true
  538. function swap (b, n, m) {
  539. var i = b[n]
  540. b[n] = b[m]
  541. b[m] = i
  542. }
  543. Buffer.prototype.swap16 = function swap16 () {
  544. var len = this.length
  545. if (len % 2 !== 0) {
  546. throw new RangeError('Buffer size must be a multiple of 16-bits')
  547. }
  548. for (var i = 0; i < len; i += 2) {
  549. swap(this, i, i + 1)
  550. }
  551. return this
  552. }
  553. Buffer.prototype.swap32 = function swap32 () {
  554. var len = this.length
  555. if (len % 4 !== 0) {
  556. throw new RangeError('Buffer size must be a multiple of 32-bits')
  557. }
  558. for (var i = 0; i < len; i += 4) {
  559. swap(this, i, i + 3)
  560. swap(this, i + 1, i + 2)
  561. }
  562. return this
  563. }
  564. Buffer.prototype.toString = function toString () {
  565. var length = this.length | 0
  566. if (length === 0) return ''
  567. if (arguments.length === 0) return utf8Slice(this, 0, length)
  568. return slowToString.apply(this, arguments)
  569. }
  570. Buffer.prototype.equals = function equals (b) {
  571. if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
  572. if (this === b) return true
  573. return Buffer.compare(this, b) === 0
  574. }
  575. Buffer.prototype.inspect = function inspect () {
  576. var str = ''
  577. var max = exports.INSPECT_MAX_BYTES
  578. if (this.length > 0) {
  579. str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')
  580. if (this.length > max) str += ' ... '
  581. }
  582. return '<Buffer ' + str + '>'
  583. }
  584. Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
  585. if (!Buffer.isBuffer(target)) {
  586. throw new TypeError('Argument must be a Buffer')
  587. }
  588. if (start === undefined) {
  589. start = 0
  590. }
  591. if (end === undefined) {
  592. end = target ? target.length : 0
  593. }
  594. if (thisStart === undefined) {
  595. thisStart = 0
  596. }
  597. if (thisEnd === undefined) {
  598. thisEnd = this.length
  599. }
  600. if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
  601. throw new RangeError('out of range index')
  602. }
  603. if (thisStart >= thisEnd && start >= end) {
  604. return 0
  605. }
  606. if (thisStart >= thisEnd) {
  607. return -1
  608. }
  609. if (start >= end) {
  610. return 1
  611. }
  612. start >>>= 0
  613. end >>>= 0
  614. thisStart >>>= 0
  615. thisEnd >>>= 0
  616. if (this === target) return 0
  617. var x = thisEnd - thisStart
  618. var y = end - start
  619. var len = Math.min(x, y)
  620. var thisCopy = this.slice(thisStart, thisEnd)
  621. var targetCopy = target.slice(start, end)
  622. for (var i = 0; i < len; ++i) {
  623. if (thisCopy[i] !== targetCopy[i]) {
  624. x = thisCopy[i]
  625. y = targetCopy[i]
  626. break
  627. }
  628. }
  629. if (x < y) return -1
  630. if (y < x) return 1
  631. return 0
  632. }
  633. function arrayIndexOf (arr, val, byteOffset, encoding) {
  634. var indexSize = 1
  635. var arrLength = arr.length
  636. var valLength = val.length
  637. if (encoding !== undefined) {
  638. encoding = String(encoding).toLowerCase()
  639. if (encoding === 'ucs2' || encoding === 'ucs-2' ||
  640. encoding === 'utf16le' || encoding === 'utf-16le') {
  641. if (arr.length < 2 || val.length < 2) {
  642. return -1
  643. }
  644. indexSize = 2
  645. arrLength /= 2
  646. valLength /= 2
  647. byteOffset /= 2
  648. }
  649. }
  650. function read (buf, i) {
  651. if (indexSize === 1) {
  652. return buf[i]
  653. } else {
  654. return buf.readUInt16BE(i * indexSize)
  655. }
  656. }
  657. var foundIndex = -1
  658. for (var i = 0; byteOffset + i < arrLength; i++) {
  659. if (read(arr, byteOffset + i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
  660. if (foundIndex === -1) foundIndex = i
  661. if (i - foundIndex + 1 === valLength) return (byteOffset + foundIndex) * indexSize
  662. } else {
  663. if (foundIndex !== -1) i -= i - foundIndex
  664. foundIndex = -1
  665. }
  666. }
  667. return -1
  668. }
  669. Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
  670. if (typeof byteOffset === 'string') {
  671. encoding = byteOffset
  672. byteOffset = 0
  673. } else if (byteOffset > 0x7fffffff) {
  674. byteOffset = 0x7fffffff
  675. } else if (byteOffset < -0x80000000) {
  676. byteOffset = -0x80000000
  677. }
  678. byteOffset >>= 0
  679. if (this.length === 0) return -1
  680. if (byteOffset >= this.length) return -1
  681. // Negative offsets start from the end of the buffer
  682. if (byteOffset < 0) byteOffset = Math.max(this.length + byteOffset, 0)
  683. if (typeof val === 'string') {
  684. val = Buffer.from(val, encoding)
  685. }
  686. if (Buffer.isBuffer(val)) {
  687. // special case: looking for empty string/buffer always fails
  688. if (val.length === 0) {
  689. return -1
  690. }
  691. return arrayIndexOf(this, val, byteOffset, encoding)
  692. }
  693. if (typeof val === 'number') {
  694. if (Buffer.TYPED_ARRAY_SUPPORT && Uint8Array.prototype.indexOf === 'function') {
  695. return Uint8Array.prototype.indexOf.call(this, val, byteOffset)
  696. }
  697. return arrayIndexOf(this, [ val ], byteOffset, encoding)
  698. }
  699. throw new TypeError('val must be string, number or Buffer')
  700. }
  701. Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
  702. return this.indexOf(val, byteOffset, encoding) !== -1
  703. }
  704. function hexWrite (buf, string, offset, length) {
  705. offset = Number(offset) || 0
  706. var remaining = buf.length - offset
  707. if (!length) {
  708. length = remaining
  709. } else {
  710. length = Number(length)
  711. if (length > remaining) {
  712. length = remaining
  713. }
  714. }
  715. // must be an even number of digits
  716. var strLen = string.length
  717. if (strLen % 2 !== 0) throw new Error('Invalid hex string')
  718. if (length > strLen / 2) {
  719. length = strLen / 2
  720. }
  721. for (var i = 0; i < length; i++) {
  722. var parsed = parseInt(string.substr(i * 2, 2), 16)
  723. if (isNaN(parsed)) return i
  724. buf[offset + i] = parsed
  725. }
  726. return i
  727. }
  728. function utf8Write (buf, string, offset, length) {
  729. return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
  730. }
  731. function asciiWrite (buf, string, offset, length) {
  732. return blitBuffer(asciiToBytes(string), buf, offset, length)
  733. }
  734. function binaryWrite (buf, string, offset, length) {
  735. return asciiWrite(buf, string, offset, length)
  736. }
  737. function base64Write (buf, string, offset, length) {
  738. return blitBuffer(base64ToBytes(string), buf, offset, length)
  739. }
  740. function ucs2Write (buf, string, offset, length) {
  741. return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
  742. }
  743. Buffer.prototype.write = function write (string, offset, length, encoding) {
  744. // Buffer#write(string)
  745. if (offset === undefined) {
  746. encoding = 'utf8'
  747. length = this.length
  748. offset = 0
  749. // Buffer#write(string, encoding)
  750. } else if (length === undefined && typeof offset === 'string') {
  751. encoding = offset
  752. length = this.length
  753. offset = 0
  754. // Buffer#write(string, offset[, length][, encoding])
  755. } else if (isFinite(offset)) {
  756. offset = offset | 0
  757. if (isFinite(length)) {
  758. length = length | 0
  759. if (encoding === undefined) encoding = 'utf8'
  760. } else {
  761. encoding = length
  762. length = undefined
  763. }
  764. // legacy write(string, encoding, offset, length) - remove in v0.13
  765. } else {
  766. throw new Error(
  767. 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
  768. )
  769. }
  770. var remaining = this.length - offset
  771. if (length === undefined || length > remaining) length = remaining
  772. if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
  773. throw new RangeError('Attempt to write outside buffer bounds')
  774. }
  775. if (!encoding) encoding = 'utf8'
  776. var loweredCase = false
  777. for (;;) {
  778. switch (encoding) {
  779. case 'hex':
  780. return hexWrite(this, string, offset, length)
  781. case 'utf8':
  782. case 'utf-8':
  783. return utf8Write(this, string, offset, length)
  784. case 'ascii':
  785. return asciiWrite(this, string, offset, length)
  786. case 'binary':
  787. return binaryWrite(this, string, offset, length)
  788. case 'base64':
  789. // Warning: maxLength not taken into account in base64Write
  790. return base64Write(this, string, offset, length)
  791. case 'ucs2':
  792. case 'ucs-2':
  793. case 'utf16le':
  794. case 'utf-16le':
  795. return ucs2Write(this, string, offset, length)
  796. default:
  797. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  798. encoding = ('' + encoding).toLowerCase()
  799. loweredCase = true
  800. }
  801. }
  802. }
  803. Buffer.prototype.toJSON = function toJSON () {
  804. return {
  805. type: 'Buffer',
  806. data: Array.prototype.slice.call(this._arr || this, 0)
  807. }
  808. }
  809. function base64Slice (buf, start, end) {
  810. if (start === 0 && end === buf.length) {
  811. return base64.fromByteArray(buf)
  812. } else {
  813. return base64.fromByteArray(buf.slice(start, end))
  814. }
  815. }
  816. function utf8Slice (buf, start, end) {
  817. end = Math.min(buf.length, end)
  818. var res = []
  819. var i = start
  820. while (i < end) {
  821. var firstByte = buf[i]
  822. var codePoint = null
  823. var bytesPerSequence = (firstByte > 0xEF) ? 4
  824. : (firstByte > 0xDF) ? 3
  825. : (firstByte > 0xBF) ? 2
  826. : 1
  827. if (i + bytesPerSequence <= end) {
  828. var secondByte, thirdByte, fourthByte, tempCodePoint
  829. switch (bytesPerSequence) {
  830. case 1:
  831. if (firstByte < 0x80) {
  832. codePoint = firstByte
  833. }
  834. break
  835. case 2:
  836. secondByte = buf[i + 1]
  837. if ((secondByte & 0xC0) === 0x80) {
  838. tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
  839. if (tempCodePoint > 0x7F) {
  840. codePoint = tempCodePoint
  841. }
  842. }
  843. break
  844. case 3:
  845. secondByte = buf[i + 1]
  846. thirdByte = buf[i + 2]
  847. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
  848. tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
  849. if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
  850. codePoint = tempCodePoint
  851. }
  852. }
  853. break
  854. case 4:
  855. secondByte = buf[i + 1]
  856. thirdByte = buf[i + 2]
  857. fourthByte = buf[i + 3]
  858. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
  859. tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
  860. if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
  861. codePoint = tempCodePoint
  862. }
  863. }
  864. }
  865. }
  866. if (codePoint === null) {
  867. // we did not generate a valid codePoint so insert a
  868. // replacement char (U+FFFD) and advance only 1 byte
  869. codePoint = 0xFFFD
  870. bytesPerSequence = 1
  871. } else if (codePoint > 0xFFFF) {
  872. // encode to utf16 (surrogate pair dance)
  873. codePoint -= 0x10000
  874. res.push(codePoint >>> 10 & 0x3FF | 0xD800)
  875. codePoint = 0xDC00 | codePoint & 0x3FF
  876. }
  877. res.push(codePoint)
  878. i += bytesPerSequence
  879. }
  880. return decodeCodePointsArray(res)
  881. }
  882. // Based on http://stackoverflow.com/a/22747272/680742, the browser with
  883. // the lowest limit is Chrome, with 0x10000 args.
  884. // We go 1 magnitude less, for safety
  885. var MAX_ARGUMENTS_LENGTH = 0x1000
  886. function decodeCodePointsArray (codePoints) {
  887. var len = codePoints.length
  888. if (len <= MAX_ARGUMENTS_LENGTH) {
  889. return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
  890. }
  891. // Decode in chunks to avoid "call stack size exceeded".
  892. var res = ''
  893. var i = 0
  894. while (i < len) {
  895. res += String.fromCharCode.apply(
  896. String,
  897. codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
  898. )
  899. }
  900. return res
  901. }
  902. function asciiSlice (buf, start, end) {
  903. var ret = ''
  904. end = Math.min(buf.length, end)
  905. for (var i = start; i < end; i++) {
  906. ret += String.fromCharCode(buf[i] & 0x7F)
  907. }
  908. return ret
  909. }
  910. function binarySlice (buf, start, end) {
  911. var ret = ''
  912. end = Math.min(buf.length, end)
  913. for (var i = start; i < end; i++) {
  914. ret += String.fromCharCode(buf[i])
  915. }
  916. return ret
  917. }
  918. function hexSlice (buf, start, end) {
  919. var len = buf.length
  920. if (!start || start < 0) start = 0
  921. if (!end || end < 0 || end > len) end = len
  922. var out = ''
  923. for (var i = start; i < end; i++) {
  924. out += toHex(buf[i])
  925. }
  926. return out
  927. }
  928. function utf16leSlice (buf, start, end) {
  929. var bytes = buf.slice(start, end)
  930. var res = ''
  931. for (var i = 0; i < bytes.length; i += 2) {
  932. res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)
  933. }
  934. return res
  935. }
  936. Buffer.prototype.slice = function slice (start, end) {
  937. var len = this.length
  938. start = ~~start
  939. end = end === undefined ? len : ~~end
  940. if (start < 0) {
  941. start += len
  942. if (start < 0) start = 0
  943. } else if (start > len) {
  944. start = len
  945. }
  946. if (end < 0) {
  947. end += len
  948. if (end < 0) end = 0
  949. } else if (end > len) {
  950. end = len
  951. }
  952. if (end < start) end = start
  953. var newBuf
  954. if (Buffer.TYPED_ARRAY_SUPPORT) {
  955. newBuf = this.subarray(start, end)
  956. newBuf.__proto__ = Buffer.prototype
  957. } else {
  958. var sliceLen = end - start
  959. newBuf = new Buffer(sliceLen, undefined)
  960. for (var i = 0; i < sliceLen; i++) {
  961. newBuf[i] = this[i + start]
  962. }
  963. }
  964. return newBuf
  965. }
  966. /*
  967. * Need to make sure that buffer isn't trying to write out of bounds.
  968. */
  969. function checkOffset (offset, ext, length) {
  970. if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
  971. if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
  972. }
  973. Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
  974. offset = offset | 0
  975. byteLength = byteLength | 0
  976. if (!noAssert) checkOffset(offset, byteLength, this.length)
  977. var val = this[offset]
  978. var mul = 1
  979. var i = 0
  980. while (++i < byteLength && (mul *= 0x100)) {
  981. val += this[offset + i] * mul
  982. }
  983. return val
  984. }
  985. Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
  986. offset = offset | 0
  987. byteLength = byteLength | 0
  988. if (!noAssert) {
  989. checkOffset(offset, byteLength, this.length)
  990. }
  991. var val = this[offset + --byteLength]
  992. var mul = 1
  993. while (byteLength > 0 && (mul *= 0x100)) {
  994. val += this[offset + --byteLength] * mul
  995. }
  996. return val
  997. }
  998. Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
  999. if (!noAssert) checkOffset(offset, 1, this.length)
  1000. return this[offset]
  1001. }
  1002. Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
  1003. if (!noAssert) checkOffset(offset, 2, this.length)
  1004. return this[offset] | (this[offset + 1] << 8)
  1005. }
  1006. Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
  1007. if (!noAssert) checkOffset(offset, 2, this.length)
  1008. return (this[offset] << 8) | this[offset + 1]
  1009. }
  1010. Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
  1011. if (!noAssert) checkOffset(offset, 4, this.length)
  1012. return ((this[offset]) |
  1013. (this[offset + 1] << 8) |
  1014. (this[offset + 2] << 16)) +
  1015. (this[offset + 3] * 0x1000000)
  1016. }
  1017. Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
  1018. if (!noAssert) checkOffset(offset, 4, this.length)
  1019. return (this[offset] * 0x1000000) +
  1020. ((this[offset + 1] << 16) |
  1021. (this[offset + 2] << 8) |
  1022. this[offset + 3])
  1023. }
  1024. Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
  1025. offset = offset | 0
  1026. byteLength = byteLength | 0
  1027. if (!noAssert) checkOffset(offset, byteLength, this.length)
  1028. var val = this[offset]
  1029. var mul = 1
  1030. var i = 0
  1031. while (++i < byteLength && (mul *= 0x100)) {
  1032. val += this[offset + i] * mul
  1033. }
  1034. mul *= 0x80
  1035. if (val >= mul) val -= Math.pow(2, 8 * byteLength)
  1036. return val
  1037. }
  1038. Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
  1039. offset = offset | 0
  1040. byteLength = byteLength | 0
  1041. if (!noAssert) checkOffset(offset, byteLength, this.length)
  1042. var i = byteLength
  1043. var mul = 1
  1044. var val = this[offset + --i]
  1045. while (i > 0 && (mul *= 0x100)) {
  1046. val += this[offset + --i] * mul
  1047. }
  1048. mul *= 0x80
  1049. if (val >= mul) val -= Math.pow(2, 8 * byteLength)
  1050. return val
  1051. }
  1052. Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
  1053. if (!noAssert) checkOffset(offset, 1, this.length)
  1054. if (!(this[offset] & 0x80)) return (this[offset])
  1055. return ((0xff - this[offset] + 1) * -1)
  1056. }
  1057. Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
  1058. if (!noAssert) checkOffset(offset, 2, this.length)
  1059. var val = this[offset] | (this[offset + 1] << 8)
  1060. return (val & 0x8000) ? val | 0xFFFF0000 : val
  1061. }
  1062. Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
  1063. if (!noAssert) checkOffset(offset, 2, this.length)
  1064. var val = this[offset + 1] | (this[offset] << 8)
  1065. return (val & 0x8000) ? val | 0xFFFF0000 : val
  1066. }
  1067. Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
  1068. if (!noAssert) checkOffset(offset, 4, this.length)
  1069. return (this[offset]) |
  1070. (this[offset + 1] << 8) |
  1071. (this[offset + 2] << 16) |
  1072. (this[offset + 3] << 24)
  1073. }
  1074. Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
  1075. if (!noAssert) checkOffset(offset, 4, this.length)
  1076. return (this[offset] << 24) |
  1077. (this[offset + 1] << 16) |
  1078. (this[offset + 2] << 8) |
  1079. (this[offset + 3])
  1080. }
  1081. Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
  1082. if (!noAssert) checkOffset(offset, 4, this.length)
  1083. return ieee754.read(this, offset, true, 23, 4)
  1084. }
  1085. Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
  1086. if (!noAssert) checkOffset(offset, 4, this.length)
  1087. return ieee754.read(this, offset, false, 23, 4)
  1088. }
  1089. Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
  1090. if (!noAssert) checkOffset(offset, 8, this.length)
  1091. return ieee754.read(this, offset, true, 52, 8)
  1092. }
  1093. Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
  1094. if (!noAssert) checkOffset(offset, 8, this.length)
  1095. return ieee754.read(this, offset, false, 52, 8)
  1096. }
  1097. function checkInt (buf, value, offset, ext, max, min) {
  1098. if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
  1099. if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
  1100. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  1101. }
  1102. Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
  1103. value = +value
  1104. offset = offset | 0
  1105. byteLength = byteLength | 0
  1106. if (!noAssert) {
  1107. var maxBytes = Math.pow(2, 8 * byteLength) - 1
  1108. checkInt(this, value, offset, byteLength, maxBytes, 0)
  1109. }
  1110. var mul = 1
  1111. var i = 0
  1112. this[offset] = value & 0xFF
  1113. while (++i < byteLength && (mul *= 0x100)) {
  1114. this[offset + i] = (value / mul) & 0xFF
  1115. }
  1116. return offset + byteLength
  1117. }
  1118. Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
  1119. value = +value
  1120. offset = offset | 0
  1121. byteLength = byteLength | 0
  1122. if (!noAssert) {
  1123. var maxBytes = Math.pow(2, 8 * byteLength) - 1
  1124. checkInt(this, value, offset, byteLength, maxBytes, 0)
  1125. }
  1126. var i = byteLength - 1
  1127. var mul = 1
  1128. this[offset + i] = value & 0xFF
  1129. while (--i >= 0 && (mul *= 0x100)) {
  1130. this[offset + i] = (value / mul) & 0xFF
  1131. }
  1132. return offset + byteLength
  1133. }
  1134. Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
  1135. value = +value
  1136. offset = offset | 0
  1137. if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
  1138. if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
  1139. this[offset] = (value & 0xff)
  1140. return offset + 1
  1141. }
  1142. function objectWriteUInt16 (buf, value, offset, littleEndian) {
  1143. if (value < 0) value = 0xffff + value + 1
  1144. for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; i++) {
  1145. buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
  1146. (littleEndian ? i : 1 - i) * 8
  1147. }
  1148. }
  1149. Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
  1150. value = +value
  1151. offset = offset | 0
  1152. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  1153. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1154. this[offset] = (value & 0xff)
  1155. this[offset + 1] = (value >>> 8)
  1156. } else {
  1157. objectWriteUInt16(this, value, offset, true)
  1158. }
  1159. return offset + 2
  1160. }
  1161. Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
  1162. value = +value
  1163. offset = offset | 0
  1164. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  1165. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1166. this[offset] = (value >>> 8)
  1167. this[offset + 1] = (value & 0xff)
  1168. } else {
  1169. objectWriteUInt16(this, value, offset, false)
  1170. }
  1171. return offset + 2
  1172. }
  1173. function objectWriteUInt32 (buf, value, offset, littleEndian) {
  1174. if (value < 0) value = 0xffffffff + value + 1
  1175. for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; i++) {
  1176. buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff
  1177. }
  1178. }
  1179. Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
  1180. value = +value
  1181. offset = offset | 0
  1182. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  1183. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1184. this[offset + 3] = (value >>> 24)
  1185. this[offset + 2] = (value >>> 16)
  1186. this[offset + 1] = (value >>> 8)
  1187. this[offset] = (value & 0xff)
  1188. } else {
  1189. objectWriteUInt32(this, value, offset, true)
  1190. }
  1191. return offset + 4
  1192. }
  1193. Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
  1194. value = +value
  1195. offset = offset | 0
  1196. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  1197. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1198. this[offset] = (value >>> 24)
  1199. this[offset + 1] = (value >>> 16)
  1200. this[offset + 2] = (value >>> 8)
  1201. this[offset + 3] = (value & 0xff)
  1202. } else {
  1203. objectWriteUInt32(this, value, offset, false)
  1204. }
  1205. return offset + 4
  1206. }
  1207. Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
  1208. value = +value
  1209. offset = offset | 0
  1210. if (!noAssert) {
  1211. var limit = Math.pow(2, 8 * byteLength - 1)
  1212. checkInt(this, value, offset, byteLength, limit - 1, -limit)
  1213. }
  1214. var i = 0
  1215. var mul = 1
  1216. var sub = 0
  1217. this[offset] = value & 0xFF
  1218. while (++i < byteLength && (mul *= 0x100)) {
  1219. if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
  1220. sub = 1
  1221. }
  1222. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  1223. }
  1224. return offset + byteLength
  1225. }
  1226. Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
  1227. value = +value
  1228. offset = offset | 0
  1229. if (!noAssert) {
  1230. var limit = Math.pow(2, 8 * byteLength - 1)
  1231. checkInt(this, value, offset, byteLength, limit - 1, -limit)
  1232. }
  1233. var i = byteLength - 1
  1234. var mul = 1
  1235. var sub = 0
  1236. this[offset + i] = value & 0xFF
  1237. while (--i >= 0 && (mul *= 0x100)) {
  1238. if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
  1239. sub = 1
  1240. }
  1241. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  1242. }
  1243. return offset + byteLength
  1244. }
  1245. Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
  1246. value = +value
  1247. offset = offset | 0
  1248. if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
  1249. if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
  1250. if (value < 0) value = 0xff + value + 1
  1251. this[offset] = (value & 0xff)
  1252. return offset + 1
  1253. }
  1254. Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
  1255. value = +value
  1256. offset = offset | 0
  1257. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  1258. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1259. this[offset] = (value & 0xff)
  1260. this[offset + 1] = (value >>> 8)
  1261. } else {
  1262. objectWriteUInt16(this, value, offset, true)
  1263. }
  1264. return offset + 2
  1265. }
  1266. Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
  1267. value = +value
  1268. offset = offset | 0
  1269. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  1270. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1271. this[offset] = (value >>> 8)
  1272. this[offset + 1] = (value & 0xff)
  1273. } else {
  1274. objectWriteUInt16(this, value, offset, false)
  1275. }
  1276. return offset + 2
  1277. }
  1278. Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
  1279. value = +value
  1280. offset = offset | 0
  1281. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  1282. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1283. this[offset] = (value & 0xff)
  1284. this[offset + 1] = (value >>> 8)
  1285. this[offset + 2] = (value >>> 16)
  1286. this[offset + 3] = (value >>> 24)
  1287. } else {
  1288. objectWriteUInt32(this, value, offset, true)
  1289. }
  1290. return offset + 4
  1291. }
  1292. Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
  1293. value = +value
  1294. offset = offset | 0
  1295. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  1296. if (value < 0) value = 0xffffffff + value + 1
  1297. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1298. this[offset] = (value >>> 24)
  1299. this[offset + 1] = (value >>> 16)
  1300. this[offset + 2] = (value >>> 8)
  1301. this[offset + 3] = (value & 0xff)
  1302. } else {
  1303. objectWriteUInt32(this, value, offset, false)
  1304. }
  1305. return offset + 4
  1306. }
  1307. function checkIEEE754 (buf, value, offset, ext, max, min) {
  1308. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  1309. if (offset < 0) throw new RangeError('Index out of range')
  1310. }
  1311. function writeFloat (buf, value, offset, littleEndian, noAssert) {
  1312. if (!noAssert) {
  1313. checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
  1314. }
  1315. ieee754.write(buf, value, offset, littleEndian, 23, 4)
  1316. return offset + 4
  1317. }
  1318. Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
  1319. return writeFloat(this, value, offset, true, noAssert)
  1320. }
  1321. Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
  1322. return writeFloat(this, value, offset, false, noAssert)
  1323. }
  1324. function writeDouble (buf, value, offset, littleEndian, noAssert) {
  1325. if (!noAssert) {
  1326. checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
  1327. }
  1328. ieee754.write(buf, value, offset, littleEndian, 52, 8)
  1329. return offset + 8
  1330. }
  1331. Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
  1332. return writeDouble(this, value, offset, true, noAssert)
  1333. }
  1334. Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
  1335. return writeDouble(this, value, offset, false, noAssert)
  1336. }
  1337. // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
  1338. Buffer.prototype.copy = function copy (target, targetStart, start, end) {
  1339. if (!start) start = 0
  1340. if (!end && end !== 0) end = this.length
  1341. if (targetStart >= target.length) targetStart = target.length
  1342. if (!targetStart) targetStart = 0
  1343. if (end > 0 && end < start) end = start
  1344. // Copy 0 bytes; we're done
  1345. if (end === start) return 0
  1346. if (target.length === 0 || this.length === 0) return 0
  1347. // Fatal error conditions
  1348. if (targetStart < 0) {
  1349. throw new RangeError('targetStart out of bounds')
  1350. }
  1351. if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
  1352. if (end < 0) throw new RangeError('sourceEnd out of bounds')
  1353. // Are we oob?
  1354. if (end > this.length) end = this.length
  1355. if (target.length - targetStart < end - start) {
  1356. end = target.length - targetStart + start
  1357. }
  1358. var len = end - start
  1359. var i
  1360. if (this === target && start < targetStart && targetStart < end) {
  1361. // descending copy from end
  1362. for (i = len - 1; i >= 0; i--) {
  1363. target[i + targetStart] = this[i + start]
  1364. }
  1365. } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {
  1366. // ascending copy from start
  1367. for (i = 0; i < len; i++) {
  1368. target[i + targetStart] = this[i + start]
  1369. }
  1370. } else {
  1371. Uint8Array.prototype.set.call(
  1372. target,
  1373. this.subarray(start, start + len),
  1374. targetStart
  1375. )
  1376. }
  1377. return len
  1378. }
  1379. // Usage:
  1380. // buffer.fill(number[, offset[, end]])
  1381. // buffer.fill(buffer[, offset[, end]])
  1382. // buffer.fill(string[, offset[, end]][, encoding])
  1383. Buffer.prototype.fill = function fill (val, start, end, encoding) {
  1384. // Handle string cases:
  1385. if (typeof val === 'string') {
  1386. if (typeof start === 'string') {
  1387. encoding = start
  1388. start = 0
  1389. end = this.length
  1390. } else if (typeof end === 'string') {
  1391. encoding = end
  1392. end = this.length
  1393. }
  1394. if (val.length === 1) {
  1395. var code = val.charCodeAt(0)
  1396. if (code < 256) {
  1397. val = code
  1398. }
  1399. }
  1400. if (encoding !== undefined && typeof encoding !== 'string') {
  1401. throw new TypeError('encoding must be a string')
  1402. }
  1403. if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
  1404. throw new TypeError('Unknown encoding: ' + encoding)
  1405. }
  1406. } else if (typeof val === 'number') {
  1407. val = val & 255
  1408. }
  1409. // Invalid ranges are not set to a default, so can range check early.
  1410. if (start < 0 || this.length < start || this.length < end) {
  1411. throw new RangeError('Out of range index')
  1412. }
  1413. if (end <= start) {
  1414. return this
  1415. }
  1416. start = start >>> 0
  1417. end = end === undefined ? this.length : end >>> 0
  1418. if (!val) val = 0
  1419. var i
  1420. if (typeof val === 'number') {
  1421. for (i = start; i < end; i++) {
  1422. this[i] = val
  1423. }
  1424. } else {
  1425. var bytes = Buffer.isBuffer(val)
  1426. ? val
  1427. : utf8ToBytes(new Buffer(val, encoding).toString())
  1428. var len = bytes.length
  1429. for (i = 0; i < end - start; i++) {
  1430. this[i + start] = bytes[i % len]
  1431. }
  1432. }
  1433. return this
  1434. }
  1435. // HELPER FUNCTIONS
  1436. // ================
  1437. var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g
  1438. function base64clean (str) {
  1439. // Node strips out invalid characters like \n and \t from the string, base64-js does not
  1440. str = stringtrim(str).replace(INVALID_BASE64_RE, '')
  1441. // Node converts strings with length < 2 to ''
  1442. if (str.length < 2) return ''
  1443. // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
  1444. while (str.length % 4 !== 0) {
  1445. str = str + '='
  1446. }
  1447. return str
  1448. }
  1449. function stringtrim (str) {
  1450. if (str.trim) return str.trim()
  1451. return str.replace(/^\s+|\s+$/g, '')
  1452. }
  1453. function toHex (n) {
  1454. if (n < 16) return '0' + n.toString(16)
  1455. return n.toString(16)
  1456. }
  1457. function utf8ToBytes (string, units) {
  1458. units = units || Infinity
  1459. var codePoint
  1460. var length = string.length
  1461. var leadSurrogate = null
  1462. var bytes = []
  1463. for (var i = 0; i < length; i++) {
  1464. codePoint = string.charCodeAt(i)
  1465. // is surrogate component
  1466. if (codePoint > 0xD7FF && codePoint < 0xE000) {
  1467. // last char was a lead
  1468. if (!leadSurrogate) {
  1469. // no lead yet
  1470. if (codePoint > 0xDBFF) {
  1471. // unexpected trail
  1472. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  1473. continue
  1474. } else if (i + 1 === length) {
  1475. // unpaired lead
  1476. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  1477. continue
  1478. }
  1479. // valid lead
  1480. leadSurrogate = codePoint
  1481. continue
  1482. }
  1483. // 2 leads in a row
  1484. if (codePoint < 0xDC00) {
  1485. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  1486. leadSurrogate = codePoint
  1487. continue
  1488. }
  1489. // valid surrogate pair
  1490. codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
  1491. } else if (leadSurrogate) {
  1492. // valid bmp char, but last char was a lead
  1493. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  1494. }
  1495. leadSurrogate = null
  1496. // encode utf8
  1497. if (codePoint < 0x80) {
  1498. if ((units -= 1) < 0) break
  1499. bytes.push(codePoint)
  1500. } else if (codePoint < 0x800) {
  1501. if ((units -= 2) < 0) break
  1502. bytes.push(
  1503. codePoint >> 0x6 | 0xC0,
  1504. codePoint & 0x3F | 0x80
  1505. )
  1506. } else if (codePoint < 0x10000) {
  1507. if ((units -= 3) < 0) break
  1508. bytes.push(
  1509. codePoint >> 0xC | 0xE0,
  1510. codePoint >> 0x6 & 0x3F | 0x80,
  1511. codePoint & 0x3F | 0x80
  1512. )
  1513. } else if (codePoint < 0x110000) {
  1514. if ((units -= 4) < 0) break
  1515. bytes.push(
  1516. codePoint >> 0x12 | 0xF0,
  1517. codePoint >> 0xC & 0x3F | 0x80,
  1518. codePoint >> 0x6 & 0x3F | 0x80,
  1519. codePoint & 0x3F | 0x80
  1520. )
  1521. } else {
  1522. throw new Error('Invalid code point')
  1523. }
  1524. }
  1525. return bytes
  1526. }
  1527. function asciiToBytes (str) {
  1528. var byteArray = []
  1529. for (var i = 0; i < str.length; i++) {
  1530. // Node's code seems to be doing this and not & 0x7F..
  1531. byteArray.push(str.charCodeAt(i) & 0xFF)
  1532. }
  1533. return byteArray
  1534. }
  1535. function utf16leToBytes (str, units) {
  1536. var c, hi, lo
  1537. var byteArray = []
  1538. for (var i = 0; i < str.length; i++) {
  1539. if ((units -= 2) < 0) break
  1540. c = str.charCodeAt(i)
  1541. hi = c >> 8
  1542. lo = c % 256
  1543. byteArray.push(lo)
  1544. byteArray.push(hi)
  1545. }
  1546. return byteArray
  1547. }
  1548. function base64ToBytes (str) {
  1549. return base64.toByteArray(base64clean(str))
  1550. }
  1551. function blitBuffer (src, dst, offset, length) {
  1552. for (var i = 0; i < length; i++) {
  1553. if ((i + offset >= dst.length) || (i >= src.length)) break
  1554. dst[i + offset] = src[i]
  1555. }
  1556. return i
  1557. }
  1558. function isnan (val) {
  1559. return val !== val // eslint-disable-line no-self-compare
  1560. }
  1561. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  1562. },{"base64-js":1,"ieee754":15,"isarray":16}],4:[function(require,module,exports){
  1563. // Use strict mode (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode)
  1564. "use strict";
  1565. // Requires
  1566. var Typo = require("typo-js");
  1567. // Create function
  1568. function CodeMirrorSpellChecker(options) {
  1569. // Initialize
  1570. options = options || {};
  1571. // Verify
  1572. if(typeof options.codeMirrorInstance !== "function" || typeof options.codeMirrorInstance.defineMode !== "function") {
  1573. console.log("CodeMirror Spell Checker: You must provide an instance of CodeMirror via the option `codeMirrorInstance`");
  1574. return;
  1575. }
  1576. // Because some browsers don't support this functionality yet
  1577. if(!String.prototype.includes) {
  1578. String.prototype.includes = function() {
  1579. "use strict";
  1580. return String.prototype.indexOf.apply(this, arguments) !== -1;
  1581. };
  1582. }
  1583. // Define the new mode
  1584. options.codeMirrorInstance.defineMode("spell-checker", function(config) {
  1585. // Load AFF/DIC data
  1586. if(!CodeMirrorSpellChecker.aff_loading) {
  1587. CodeMirrorSpellChecker.aff_loading = true;
  1588. var xhr_aff = new XMLHttpRequest();
  1589. xhr_aff.open("GET", "https://cdn.jsdelivr.net/codemirror.spell-checker/latest/en_US.aff", true);
  1590. xhr_aff.onload = function() {
  1591. if(xhr_aff.readyState === 4 && xhr_aff.status === 200) {
  1592. CodeMirrorSpellChecker.aff_data = xhr_aff.responseText;
  1593. CodeMirrorSpellChecker.num_loaded++;
  1594. if(CodeMirrorSpellChecker.num_loaded == 2) {
  1595. CodeMirrorSpellChecker.typo = new Typo("en_US", CodeMirrorSpellChecker.aff_data, CodeMirrorSpellChecker.dic_data, {
  1596. platform: "any"
  1597. });
  1598. }
  1599. }
  1600. };
  1601. xhr_aff.send(null);
  1602. }
  1603. if(!CodeMirrorSpellChecker.dic_loading) {
  1604. CodeMirrorSpellChecker.dic_loading = true;
  1605. var xhr_dic = new XMLHttpRequest();
  1606. xhr_dic.open("GET", "https://cdn.jsdelivr.net/codemirror.spell-checker/latest/en_US.dic", true);
  1607. xhr_dic.onload = function() {
  1608. if(xhr_dic.readyState === 4 && xhr_dic.status === 200) {
  1609. CodeMirrorSpellChecker.dic_data = xhr_dic.responseText;
  1610. CodeMirrorSpellChecker.num_loaded++;
  1611. if(CodeMirrorSpellChecker.num_loaded == 2) {
  1612. CodeMirrorSpellChecker.typo = new Typo("en_US", CodeMirrorSpellChecker.aff_data, CodeMirrorSpellChecker.dic_data, {
  1613. platform: "any"
  1614. });
  1615. }
  1616. }
  1617. };
  1618. xhr_dic.send(null);
  1619. }
  1620. // Define what separates a word
  1621. var rx_word = "!\"#$%&()*+,-./:;<=>?@[\\]^_`{|}~ ";
  1622. // Create the overlay and such
  1623. var overlay = {
  1624. token: function(stream) {
  1625. var ch = stream.peek();
  1626. var word = "";
  1627. if(rx_word.includes(ch)) {
  1628. stream.next();
  1629. return null;
  1630. }
  1631. while((ch = stream.peek()) != null && !rx_word.includes(ch)) {
  1632. word += ch;
  1633. stream.next();
  1634. }
  1635. if(CodeMirrorSpellChecker.typo && !CodeMirrorSpellChecker.typo.check(word))
  1636. return "spell-error"; // CSS class: cm-spell-error
  1637. return null;
  1638. }
  1639. };
  1640. var mode = options.codeMirrorInstance.getMode(
  1641. config, config.backdrop || "text/plain"
  1642. );
  1643. return options.codeMirrorInstance.overlayMode(mode, overlay, true);
  1644. });
  1645. }
  1646. // Initialize data globally to reduce memory consumption
  1647. CodeMirrorSpellChecker.num_loaded = 0;
  1648. CodeMirrorSpellChecker.aff_loading = false;
  1649. CodeMirrorSpellChecker.dic_loading = false;
  1650. CodeMirrorSpellChecker.aff_data = "";
  1651. CodeMirrorSpellChecker.dic_data = "";
  1652. CodeMirrorSpellChecker.typo;
  1653. // Export
  1654. module.exports = CodeMirrorSpellChecker;
  1655. },{"typo-js":18}],5:[function(require,module,exports){
  1656. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  1657. // Distributed under an MIT license: http://codemirror.net/LICENSE
  1658. (function(mod) {
  1659. if (typeof exports == "object" && typeof module == "object") // CommonJS
  1660. mod(require("../../lib/codemirror"));
  1661. else if (typeof define == "function" && define.amd) // AMD
  1662. define(["../../lib/codemirror"], mod);
  1663. else // Plain browser env
  1664. mod(CodeMirror);
  1665. })(function(CodeMirror) {
  1666. "use strict";
  1667. CodeMirror.defineOption("fullScreen", false, function(cm, val, old) {
  1668. if (old == CodeMirror.Init) old = false;
  1669. if (!old == !val) return;
  1670. if (val) setFullscreen(cm);
  1671. else setNormal(cm);
  1672. });
  1673. function setFullscreen(cm) {
  1674. var wrap = cm.getWrapperElement();
  1675. cm.state.fullScreenRestore = {scrollTop: window.pageYOffset, scrollLeft: window.pageXOffset,
  1676. width: wrap.style.width, height: wrap.style.height};
  1677. wrap.style.width = "";
  1678. wrap.style.height = "auto";
  1679. wrap.className += " CodeMirror-fullscreen";
  1680. document.documentElement.style.overflow = "hidden";
  1681. cm.refresh();
  1682. }
  1683. function setNormal(cm) {
  1684. var wrap = cm.getWrapperElement();
  1685. wrap.className = wrap.className.replace(/\s*CodeMirror-fullscreen\b/, "");
  1686. document.documentElement.style.overflow = "";
  1687. var info = cm.state.fullScreenRestore;
  1688. wrap.style.width = info.width; wrap.style.height = info.height;
  1689. window.scrollTo(info.scrollLeft, info.scrollTop);
  1690. cm.refresh();
  1691. }
  1692. });
  1693. },{"../../lib/codemirror":10}],6:[function(require,module,exports){
  1694. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  1695. // Distributed under an MIT license: http://codemirror.net/LICENSE
  1696. (function(mod) {
  1697. if (typeof exports == "object" && typeof module == "object") // CommonJS
  1698. mod(require("../../lib/codemirror"));
  1699. else if (typeof define == "function" && define.amd) // AMD
  1700. define(["../../lib/codemirror"], mod);
  1701. else // Plain browser env
  1702. mod(CodeMirror);
  1703. })(function(CodeMirror) {
  1704. CodeMirror.defineOption("placeholder", "", function(cm, val, old) {
  1705. var prev = old && old != CodeMirror.Init;
  1706. if (val && !prev) {
  1707. cm.on("blur", onBlur);
  1708. cm.on("change", onChange);
  1709. cm.on("swapDoc", onChange);
  1710. onChange(cm);
  1711. } else if (!val && prev) {
  1712. cm.off("blur", onBlur);
  1713. cm.off("change", onChange);
  1714. cm.off("swapDoc", onChange);
  1715. clearPlaceholder(cm);
  1716. var wrapper = cm.getWrapperElement();
  1717. wrapper.className = wrapper.className.replace(" CodeMirror-empty", "");
  1718. }
  1719. if (val && !cm.hasFocus()) onBlur(cm);
  1720. });
  1721. function clearPlaceholder(cm) {
  1722. if (cm.state.placeholder) {
  1723. cm.state.placeholder.parentNode.removeChild(cm.state.placeholder);
  1724. cm.state.placeholder = null;
  1725. }
  1726. }
  1727. function setPlaceholder(cm) {
  1728. clearPlaceholder(cm);
  1729. var elt = cm.state.placeholder = document.createElement("pre");
  1730. elt.style.cssText = "height: 0; overflow: visible";
  1731. elt.className = "CodeMirror-placeholder";
  1732. var placeHolder = cm.getOption("placeholder")
  1733. if (typeof placeHolder == "string") placeHolder = document.createTextNode(placeHolder)
  1734. elt.appendChild(placeHolder)
  1735. cm.display.lineSpace.insertBefore(elt, cm.display.lineSpace.firstChild);
  1736. }
  1737. function onBlur(cm) {
  1738. if (isEmpty(cm)) setPlaceholder(cm);
  1739. }
  1740. function onChange(cm) {
  1741. var wrapper = cm.getWrapperElement(), empty = isEmpty(cm);
  1742. wrapper.className = wrapper.className.replace(" CodeMirror-empty", "") + (empty ? " CodeMirror-empty" : "");
  1743. if (empty) setPlaceholder(cm);
  1744. else clearPlaceholder(cm);
  1745. }
  1746. function isEmpty(cm) {
  1747. return (cm.lineCount() === 1) && (cm.getLine(0) === "");
  1748. }
  1749. });
  1750. },{"../../lib/codemirror":10}],7:[function(require,module,exports){
  1751. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  1752. // Distributed under an MIT license: http://codemirror.net/LICENSE
  1753. (function(mod) {
  1754. if (typeof exports == "object" && typeof module == "object") // CommonJS
  1755. mod(require("../../lib/codemirror"));
  1756. else if (typeof define == "function" && define.amd) // AMD
  1757. define(["../../lib/codemirror"], mod);
  1758. else // Plain browser env
  1759. mod(CodeMirror);
  1760. })(function(CodeMirror) {
  1761. "use strict";
  1762. var listRE = /^(\s*)(>[> ]*|[*+-]\s|(\d+)([.)]))(\s*)/,
  1763. emptyListRE = /^(\s*)(>[> ]*|[*+-]|(\d+)[.)])(\s*)$/,
  1764. unorderedListRE = /[*+-]\s/;
  1765. CodeMirror.commands.newlineAndIndentContinueMarkdownList = function(cm) {
  1766. if (cm.getOption("disableInput")) return CodeMirror.Pass;
  1767. var ranges = cm.listSelections(), replacements = [];
  1768. for (var i = 0; i < ranges.length; i++) {
  1769. var pos = ranges[i].head;
  1770. var eolState = cm.getStateAfter(pos.line);
  1771. var inList = eolState.list !== false;
  1772. var inQuote = eolState.quote !== 0;
  1773. var line = cm.getLine(pos.line), match = listRE.exec(line);
  1774. if (!ranges[i].empty() || (!inList && !inQuote) || !match) {
  1775. cm.execCommand("newlineAndIndent");
  1776. return;
  1777. }
  1778. if (emptyListRE.test(line)) {
  1779. cm.replaceRange("", {
  1780. line: pos.line, ch: 0
  1781. }, {
  1782. line: pos.line, ch: pos.ch + 1
  1783. });
  1784. replacements[i] = "\n";
  1785. } else {
  1786. var indent = match[1], after = match[5];
  1787. var bullet = unorderedListRE.test(match[2]) || match[2].indexOf(">") >= 0
  1788. ? match[2]
  1789. : (parseInt(match[3], 10) + 1) + match[4];
  1790. replacements[i] = "\n" + indent + bullet + after;
  1791. }
  1792. }
  1793. cm.replaceSelections(replacements);
  1794. };
  1795. });
  1796. },{"../../lib/codemirror":10}],8:[function(require,module,exports){
  1797. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  1798. // Distributed under an MIT license: http://codemirror.net/LICENSE
  1799. // Utility function that allows modes to be combined. The mode given
  1800. // as the base argument takes care of most of the normal mode
  1801. // functionality, but a second (typically simple) mode is used, which
  1802. // can override the style of text. Both modes get to parse all of the
  1803. // text, but when both assign a non-null style to a piece of code, the
  1804. // overlay wins, unless the combine argument was true and not overridden,
  1805. // or state.overlay.combineTokens was true, in which case the styles are
  1806. // combined.
  1807. (function(mod) {
  1808. if (typeof exports == "object" && typeof module == "object") // CommonJS
  1809. mod(require("../../lib/codemirror"));
  1810. else if (typeof define == "function" && define.amd) // AMD
  1811. define(["../../lib/codemirror"], mod);
  1812. else // Plain browser env
  1813. mod(CodeMirror);
  1814. })(function(CodeMirror) {
  1815. "use strict";
  1816. CodeMirror.overlayMode = function(base, overlay, combine) {
  1817. return {
  1818. startState: function() {
  1819. return {
  1820. base: CodeMirror.startState(base),
  1821. overlay: CodeMirror.startState(overlay),
  1822. basePos: 0, baseCur: null,
  1823. overlayPos: 0, overlayCur: null,
  1824. streamSeen: null
  1825. };
  1826. },
  1827. copyState: function(state) {
  1828. return {
  1829. base: CodeMirror.copyState(base, state.base),
  1830. overlay: CodeMirror.copyState(overlay, state.overlay),
  1831. basePos: state.basePos, baseCur: null,
  1832. overlayPos: state.overlayPos, overlayCur: null
  1833. };
  1834. },
  1835. token: function(stream, state) {
  1836. if (stream != state.streamSeen ||
  1837. Math.min(state.basePos, state.overlayPos) < stream.start) {
  1838. state.streamSeen = stream;
  1839. state.basePos = state.overlayPos = stream.start;
  1840. }
  1841. if (stream.start == state.basePos) {
  1842. state.baseCur = base.token(stream, state.base);
  1843. state.basePos = stream.pos;
  1844. }
  1845. if (stream.start == state.overlayPos) {
  1846. stream.pos = stream.start;
  1847. state.overlayCur = overlay.token(stream, state.overlay);
  1848. state.overlayPos = stream.pos;
  1849. }
  1850. stream.pos = Math.min(state.basePos, state.overlayPos);
  1851. // state.overlay.combineTokens always takes precedence over combine,
  1852. // unless set to null
  1853. if (state.overlayCur == null) return state.baseCur;
  1854. else if (state.baseCur != null &&
  1855. state.overlay.combineTokens ||
  1856. combine && state.overlay.combineTokens == null)
  1857. return state.baseCur + " " + state.overlayCur;
  1858. else return state.overlayCur;
  1859. },
  1860. indent: base.indent && function(state, textAfter) {
  1861. return base.indent(state.base, textAfter);
  1862. },
  1863. electricChars: base.electricChars,
  1864. innerMode: function(state) { return {state: state.base, mode: base}; },
  1865. blankLine: function(state) {
  1866. if (base.blankLine) base.blankLine(state.base);
  1867. if (overlay.blankLine) overlay.blankLine(state.overlay);
  1868. }
  1869. };
  1870. };
  1871. });
  1872. },{"../../lib/codemirror":10}],9:[function(require,module,exports){
  1873. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  1874. // Distributed under an MIT license: http://codemirror.net/LICENSE
  1875. // Because sometimes you need to mark the selected *text*.
  1876. //
  1877. // Adds an option 'styleSelectedText' which, when enabled, gives
  1878. // selected text the CSS class given as option value, or
  1879. // "CodeMirror-selectedtext" when the value is not a string.
  1880. (function(mod) {
  1881. if (typeof exports == "object" && typeof module == "object") // CommonJS
  1882. mod(require("../../lib/codemirror"));
  1883. else if (typeof define == "function" && define.amd) // AMD
  1884. define(["../../lib/codemirror"], mod);
  1885. else // Plain browser env
  1886. mod(CodeMirror);
  1887. })(function(CodeMirror) {
  1888. "use strict";
  1889. CodeMirror.defineOption("styleSelectedText", false, function(cm, val, old) {
  1890. var prev = old && old != CodeMirror.Init;
  1891. if (val && !prev) {
  1892. cm.state.markedSelection = [];
  1893. cm.state.markedSelectionStyle = typeof val == "string" ? val : "CodeMirror-selectedtext";
  1894. reset(cm);
  1895. cm.on("cursorActivity", onCursorActivity);
  1896. cm.on("change", onChange);
  1897. } else if (!val && prev) {
  1898. cm.off("cursorActivity", onCursorActivity);
  1899. cm.off("change", onChange);
  1900. clear(cm);
  1901. cm.state.markedSelection = cm.state.markedSelectionStyle = null;
  1902. }
  1903. });
  1904. function onCursorActivity(cm) {
  1905. cm.operation(function() { update(cm); });
  1906. }
  1907. function onChange(cm) {
  1908. if (cm.state.markedSelection.length)
  1909. cm.operation(function() { clear(cm); });
  1910. }
  1911. var CHUNK_SIZE = 8;
  1912. var Pos = CodeMirror.Pos;
  1913. var cmp = CodeMirror.cmpPos;
  1914. function coverRange(cm, from, to, addAt) {
  1915. if (cmp(from, to) == 0) return;
  1916. var array = cm.state.markedSelection;
  1917. var cls = cm.state.markedSelectionStyle;
  1918. for (var line = from.line;;) {
  1919. var start = line == from.line ? from : Pos(line, 0);
  1920. var endLine = line + CHUNK_SIZE, atEnd = endLine >= to.line;
  1921. var end = atEnd ? to : Pos(endLine, 0);
  1922. var mark = cm.markText(start, end, {className: cls});
  1923. if (addAt == null) array.push(mark);
  1924. else array.splice(addAt++, 0, mark);
  1925. if (atEnd) break;
  1926. line = endLine;
  1927. }
  1928. }
  1929. function clear(cm) {
  1930. var array = cm.state.markedSelection;
  1931. for (var i = 0; i < array.length; ++i) array[i].clear();
  1932. array.length = 0;
  1933. }
  1934. function reset(cm) {
  1935. clear(cm);
  1936. var ranges = cm.listSelections();
  1937. for (var i = 0; i < ranges.length; i++)
  1938. coverRange(cm, ranges[i].from(), ranges[i].to());
  1939. }
  1940. function update(cm) {
  1941. if (!cm.somethingSelected()) return clear(cm);
  1942. if (cm.listSelections().length > 1) return reset(cm);
  1943. var from = cm.getCursor("start"), to = cm.getCursor("end");
  1944. var array = cm.state.markedSelection;
  1945. if (!array.length) return coverRange(cm, from, to);
  1946. var coverStart = array[0].find(), coverEnd = array[array.length - 1].find();
  1947. if (!coverStart || !coverEnd || to.line - from.line < CHUNK_SIZE ||
  1948. cmp(from, coverEnd.to) >= 0 || cmp(to, coverStart.from) <= 0)
  1949. return reset(cm);
  1950. while (cmp(from, coverStart.from) > 0) {
  1951. array.shift().clear();
  1952. coverStart = array[0].find();
  1953. }
  1954. if (cmp(from, coverStart.from) < 0) {
  1955. if (coverStart.to.line - from.line < CHUNK_SIZE) {
  1956. array.shift().clear();
  1957. coverRange(cm, from, coverStart.to, 0);
  1958. } else {
  1959. coverRange(cm, from, coverStart.from, 0);
  1960. }
  1961. }
  1962. while (cmp(to, coverEnd.to) < 0) {
  1963. array.pop().clear();
  1964. coverEnd = array[array.length - 1].find();
  1965. }
  1966. if (cmp(to, coverEnd.to) > 0) {
  1967. if (to.line - coverEnd.from.line < CHUNK_SIZE) {
  1968. array.pop().clear();
  1969. coverRange(cm, coverEnd.from, to);
  1970. } else {
  1971. coverRange(cm, coverEnd.to, to);
  1972. }
  1973. }
  1974. }
  1975. });
  1976. },{"../../lib/codemirror":10}],10:[function(require,module,exports){
  1977. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  1978. // Distributed under an MIT license: http://codemirror.net/LICENSE
  1979. // This is CodeMirror (http://codemirror.net), a code editor
  1980. // implemented in JavaScript on top of the browser's DOM.
  1981. //
  1982. // You can find some technical background for some of the code below
  1983. // at http://marijnhaverbeke.nl/blog/#cm-internals .
  1984. (function(mod) {
  1985. if (typeof exports == "object" && typeof module == "object") // CommonJS
  1986. module.exports = mod();
  1987. else if (typeof define == "function" && define.amd) // AMD
  1988. return define([], mod);
  1989. else // Plain browser env
  1990. (this || window).CodeMirror = mod();
  1991. })(function() {
  1992. "use strict";
  1993. // BROWSER SNIFFING
  1994. // Kludges for bugs and behavior differences that can't be feature
  1995. // detected are enabled based on userAgent etc sniffing.
  1996. var userAgent = navigator.userAgent;
  1997. var platform = navigator.platform;
  1998. var gecko = /gecko\/\d/i.test(userAgent);
  1999. var ie_upto10 = /MSIE \d/.test(userAgent);
  2000. var ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(userAgent);
  2001. var ie = ie_upto10 || ie_11up;
  2002. var ie_version = ie && (ie_upto10 ? document.documentMode || 6 : ie_11up[1]);
  2003. var webkit = /WebKit\//.test(userAgent);
  2004. var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(userAgent);
  2005. var chrome = /Chrome\//.test(userAgent);
  2006. var presto = /Opera\//.test(userAgent);
  2007. var safari = /Apple Computer/.test(navigator.vendor);
  2008. var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(userAgent);
  2009. var phantom = /PhantomJS/.test(userAgent);
  2010. var ios = /AppleWebKit/.test(userAgent) && /Mobile\/\w+/.test(userAgent);
  2011. // This is woefully incomplete. Suggestions for alternative methods welcome.
  2012. var mobile = ios || /Android|webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(userAgent);
  2013. var mac = ios || /Mac/.test(platform);
  2014. var chromeOS = /\bCrOS\b/.test(userAgent);
  2015. var windows = /win/i.test(platform);
  2016. var presto_version = presto && userAgent.match(/Version\/(\d*\.\d*)/);
  2017. if (presto_version) presto_version = Number(presto_version[1]);
  2018. if (presto_version && presto_version >= 15) { presto = false; webkit = true; }
  2019. // Some browsers use the wrong event properties to signal cmd/ctrl on OS X
  2020. var flipCtrlCmd = mac && (qtwebkit || presto && (presto_version == null || presto_version < 12.11));
  2021. var captureRightClick = gecko || (ie && ie_version >= 9);
  2022. // Optimize some code when these features are not used.
  2023. var sawReadOnlySpans = false, sawCollapsedSpans = false;
  2024. // EDITOR CONSTRUCTOR
  2025. // A CodeMirror instance represents an editor. This is the object
  2026. // that user code is usually dealing with.
  2027. function CodeMirror(place, options) {
  2028. if (!(this instanceof CodeMirror)) return new CodeMirror(place, options);
  2029. this.options = options = options ? copyObj(options) : {};
  2030. // Determine effective options based on given values and defaults.
  2031. copyObj(defaults, options, false);
  2032. setGuttersForLineNumbers(options);
  2033. var doc = options.value;
  2034. if (typeof doc == "string") doc = new Doc(doc, options.mode, null, options.lineSeparator);
  2035. this.doc = doc;
  2036. var input = new CodeMirror.inputStyles[options.inputStyle](this);
  2037. var display = this.display = new Display(place, doc, input);
  2038. display.wrapper.CodeMirror = this;
  2039. updateGutters(this);
  2040. themeChanged(this);
  2041. if (options.lineWrapping)
  2042. this.display.wrapper.className += " CodeMirror-wrap";
  2043. if (options.autofocus && !mobile) display.input.focus();
  2044. initScrollbars(this);
  2045. this.state = {
  2046. keyMaps: [], // stores maps added by addKeyMap
  2047. overlays: [], // highlighting overlays, as added by addOverlay
  2048. modeGen: 0, // bumped when mode/overlay changes, used to invalidate highlighting info
  2049. overwrite: false,
  2050. delayingBlurEvent: false,
  2051. focused: false,
  2052. suppressEdits: false, // used to disable editing during key handlers when in readOnly mode
  2053. pasteIncoming: false, cutIncoming: false, // help recognize paste/cut edits in input.poll
  2054. selectingText: false,
  2055. draggingText: false,
  2056. highlight: new Delayed(), // stores highlight worker timeout
  2057. keySeq: null, // Unfinished key sequence
  2058. specialChars: null
  2059. };
  2060. var cm = this;
  2061. // Override magic textarea content restore that IE sometimes does
  2062. // on our hidden textarea on reload
  2063. if (ie && ie_version < 11) setTimeout(function() { cm.display.input.reset(true); }, 20);
  2064. registerEventHandlers(this);
  2065. ensureGlobalHandlers();
  2066. startOperation(this);
  2067. this.curOp.forceUpdate = true;
  2068. attachDoc(this, doc);
  2069. if ((options.autofocus && !mobile) || cm.hasFocus())
  2070. setTimeout(bind(onFocus, this), 20);
  2071. else
  2072. onBlur(this);
  2073. for (var opt in optionHandlers) if (optionHandlers.hasOwnProperty(opt))
  2074. optionHandlers[opt](this, options[opt], Init);
  2075. maybeUpdateLineNumberWidth(this);
  2076. if (options.finishInit) options.finishInit(this);
  2077. for (var i = 0; i < initHooks.length; ++i) initHooks[i](this);
  2078. endOperation(this);
  2079. // Suppress optimizelegibility in Webkit, since it breaks text
  2080. // measuring on line wrapping boundaries.
  2081. if (webkit && options.lineWrapping &&
  2082. getComputedStyle(display.lineDiv).textRendering == "optimizelegibility")
  2083. display.lineDiv.style.textRendering = "auto";
  2084. }
  2085. // DISPLAY CONSTRUCTOR
  2086. // The display handles the DOM integration, both for input reading
  2087. // and content drawing. It holds references to DOM nodes and
  2088. // display-related state.
  2089. function Display(place, doc, input) {
  2090. var d = this;
  2091. this.input = input;
  2092. // Covers bottom-right square when both scrollbars are present.
  2093. d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler");
  2094. d.scrollbarFiller.setAttribute("cm-not-content", "true");
  2095. // Covers bottom of gutter when coverGutterNextToScrollbar is on
  2096. // and h scrollbar is present.
  2097. d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler");
  2098. d.gutterFiller.setAttribute("cm-not-content", "true");
  2099. // Will contain the actual code, positioned to cover the viewport.
  2100. d.lineDiv = elt("div", null, "CodeMirror-code");
  2101. // Elements are added to these to represent selection and cursors.
  2102. d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1");
  2103. d.cursorDiv = elt("div", null, "CodeMirror-cursors");
  2104. // A visibility: hidden element used to find the size of things.
  2105. d.measure = elt("div", null, "CodeMirror-measure");
  2106. // When lines outside of the viewport are measured, they are drawn in this.
  2107. d.lineMeasure = elt("div", null, "CodeMirror-measure");
  2108. // Wraps everything that needs to exist inside the vertically-padded coordinate system
  2109. d.lineSpace = elt("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv],
  2110. null, "position: relative; outline: none");
  2111. // Moved around its parent to cover visible view.
  2112. d.mover = elt("div", [elt("div", [d.lineSpace], "CodeMirror-lines")], null, "position: relative");
  2113. // Set to the height of the document, allowing scrolling.
  2114. d.sizer = elt("div", [d.mover], "CodeMirror-sizer");
  2115. d.sizerWidth = null;
  2116. // Behavior of elts with overflow: auto and padding is
  2117. // inconsistent across browsers. This is used to ensure the
  2118. // scrollable area is big enough.
  2119. d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerGap + "px; width: 1px;");
  2120. // Will contain the gutters, if any.
  2121. d.gutters = elt("div", null, "CodeMirror-gutters");
  2122. d.lineGutter = null;
  2123. // Actual scrollable element.
  2124. d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll");
  2125. d.scroller.setAttribute("tabIndex", "-1");
  2126. // The element in which the editor lives.
  2127. d.wrapper = elt("div", [d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror");
  2128. // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported)
  2129. if (ie && ie_version < 8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; }
  2130. if (!webkit && !(gecko && mobile)) d.scroller.draggable = true;
  2131. if (place) {
  2132. if (place.appendChild) place.appendChild(d.wrapper);
  2133. else place(d.wrapper);
  2134. }
  2135. // Current rendered range (may be bigger than the view window).
  2136. d.viewFrom = d.viewTo = doc.first;
  2137. d.reportedViewFrom = d.reportedViewTo = doc.first;
  2138. // Information about the rendered lines.
  2139. d.view = [];
  2140. d.renderedView = null;
  2141. // Holds info about a single rendered line when it was rendered
  2142. // for measurement, while not in view.
  2143. d.externalMeasured = null;
  2144. // Empty space (in pixels) above the view
  2145. d.viewOffset = 0;
  2146. d.lastWrapHeight = d.lastWrapWidth = 0;
  2147. d.updateLineNumbers = null;
  2148. d.nativeBarWidth = d.barHeight = d.barWidth = 0;
  2149. d.scrollbarsClipped = false;
  2150. // Used to only resize the line number gutter when necessary (when
  2151. // the amount of lines crosses a boundary that makes its width change)
  2152. d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null;
  2153. // Set to true when a non-horizontal-scrolling line widget is
  2154. // added. As an optimization, line widget aligning is skipped when
  2155. // this is false.
  2156. d.alignWidgets = false;
  2157. d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
  2158. // Tracks the maximum line length so that the horizontal scrollbar
  2159. // can be kept static when scrolling.
  2160. d.maxLine = null;
  2161. d.maxLineLength = 0;
  2162. d.maxLineChanged = false;
  2163. // Used for measuring wheel scrolling granularity
  2164. d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null;
  2165. // True when shift is held down.
  2166. d.shift = false;
  2167. // Used to track whether anything happened since the context menu
  2168. // was opened.
  2169. d.selForContextMenu = null;
  2170. d.activeTouch = null;
  2171. input.init(d);
  2172. }
  2173. // STATE UPDATES
  2174. // Used to get the editor into a consistent state again when options change.
  2175. function loadMode(cm) {
  2176. cm.doc.mode = CodeMirror.getMode(cm.options, cm.doc.modeOption);
  2177. resetModeState(cm);
  2178. }
  2179. function resetModeState(cm) {
  2180. cm.doc.iter(function(line) {
  2181. if (line.stateAfter) line.stateAfter = null;
  2182. if (line.styles) line.styles = null;
  2183. });
  2184. cm.doc.frontier = cm.doc.first;
  2185. startWorker(cm, 100);
  2186. cm.state.modeGen++;
  2187. if (cm.curOp) regChange(cm);
  2188. }
  2189. function wrappingChanged(cm) {
  2190. if (cm.options.lineWrapping) {
  2191. addClass(cm.display.wrapper, "CodeMirror-wrap");
  2192. cm.display.sizer.style.minWidth = "";
  2193. cm.display.sizerWidth = null;
  2194. } else {
  2195. rmClass(cm.display.wrapper, "CodeMirror-wrap");
  2196. findMaxLine(cm);
  2197. }
  2198. estimateLineHeights(cm);
  2199. regChange(cm);
  2200. clearCaches(cm);
  2201. setTimeout(function(){updateScrollbars(cm);}, 100);
  2202. }
  2203. // Returns a function that estimates the height of a line, to use as
  2204. // first approximation until the line becomes visible (and is thus
  2205. // properly measurable).
  2206. function estimateHeight(cm) {
  2207. var th = textHeight(cm.display), wrapping = cm.options.lineWrapping;
  2208. var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3);
  2209. return function(line) {
  2210. if (lineIsHidden(cm.doc, line)) return 0;
  2211. var widgetsHeight = 0;
  2212. if (line.widgets) for (var i = 0; i < line.widgets.length; i++) {
  2213. if (line.widgets[i].height) widgetsHeight += line.widgets[i].height;
  2214. }
  2215. if (wrapping)
  2216. return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th;
  2217. else
  2218. return widgetsHeight + th;
  2219. };
  2220. }
  2221. function estimateLineHeights(cm) {
  2222. var doc = cm.doc, est = estimateHeight(cm);
  2223. doc.iter(function(line) {
  2224. var estHeight = est(line);
  2225. if (estHeight != line.height) updateLineHeight(line, estHeight);
  2226. });
  2227. }
  2228. function themeChanged(cm) {
  2229. cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") +
  2230. cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-");
  2231. clearCaches(cm);
  2232. }
  2233. function guttersChanged(cm) {
  2234. updateGutters(cm);
  2235. regChange(cm);
  2236. setTimeout(function(){alignHorizontally(cm);}, 20);
  2237. }
  2238. // Rebuild the gutter elements, ensure the margin to the left of the
  2239. // code matches their width.
  2240. function updateGutters(cm) {
  2241. var gutters = cm.display.gutters, specs = cm.options.gutters;
  2242. removeChildren(gutters);
  2243. for (var i = 0; i < specs.length; ++i) {
  2244. var gutterClass = specs[i];
  2245. var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + gutterClass));
  2246. if (gutterClass == "CodeMirror-linenumbers") {
  2247. cm.display.lineGutter = gElt;
  2248. gElt.style.width = (cm.display.lineNumWidth || 1) + "px";
  2249. }
  2250. }
  2251. gutters.style.display = i ? "" : "none";
  2252. updateGutterSpace(cm);
  2253. }
  2254. function updateGutterSpace(cm) {
  2255. var width = cm.display.gutters.offsetWidth;
  2256. cm.display.sizer.style.marginLeft = width + "px";
  2257. }
  2258. // Compute the character length of a line, taking into account
  2259. // collapsed ranges (see markText) that might hide parts, and join
  2260. // other lines onto it.
  2261. function lineLength(line) {
  2262. if (line.height == 0) return 0;
  2263. var len = line.text.length, merged, cur = line;
  2264. while (merged = collapsedSpanAtStart(cur)) {
  2265. var found = merged.find(0, true);
  2266. cur = found.from.line;
  2267. len += found.from.ch - found.to.ch;
  2268. }
  2269. cur = line;
  2270. while (merged = collapsedSpanAtEnd(cur)) {
  2271. var found = merged.find(0, true);
  2272. len -= cur.text.length - found.from.ch;
  2273. cur = found.to.line;
  2274. len += cur.text.length - found.to.ch;
  2275. }
  2276. return len;
  2277. }
  2278. // Find the longest line in the document.
  2279. function findMaxLine(cm) {
  2280. var d = cm.display, doc = cm.doc;
  2281. d.maxLine = getLine(doc, doc.first);
  2282. d.maxLineLength = lineLength(d.maxLine);
  2283. d.maxLineChanged = true;
  2284. doc.iter(function(line) {
  2285. var len = lineLength(line);
  2286. if (len > d.maxLineLength) {
  2287. d.maxLineLength = len;
  2288. d.maxLine = line;
  2289. }
  2290. });
  2291. }
  2292. // Make sure the gutters options contains the element
  2293. // "CodeMirror-linenumbers" when the lineNumbers option is true.
  2294. function setGuttersForLineNumbers(options) {
  2295. var found = indexOf(options.gutters, "CodeMirror-linenumbers");
  2296. if (found == -1 && options.lineNumbers) {
  2297. options.gutters = options.gutters.concat(["CodeMirror-linenumbers"]);
  2298. } else if (found > -1 && !options.lineNumbers) {
  2299. options.gutters = options.gutters.slice(0);
  2300. options.gutters.splice(found, 1);
  2301. }
  2302. }
  2303. // SCROLLBARS
  2304. // Prepare DOM reads needed to update the scrollbars. Done in one
  2305. // shot to minimize update/measure roundtrips.
  2306. function measureForScrollbars(cm) {
  2307. var d = cm.display, gutterW = d.gutters.offsetWidth;
  2308. var docH = Math.round(cm.doc.height + paddingVert(cm.display));
  2309. return {
  2310. clientHeight: d.scroller.clientHeight,
  2311. viewHeight: d.wrapper.clientHeight,
  2312. scrollWidth: d.scroller.scrollWidth, clientWidth: d.scroller.clientWidth,
  2313. viewWidth: d.wrapper.clientWidth,
  2314. barLeft: cm.options.fixedGutter ? gutterW : 0,
  2315. docHeight: docH,
  2316. scrollHeight: docH + scrollGap(cm) + d.barHeight,
  2317. nativeBarWidth: d.nativeBarWidth,
  2318. gutterWidth: gutterW
  2319. };
  2320. }
  2321. function NativeScrollbars(place, scroll, cm) {
  2322. this.cm = cm;
  2323. var vert = this.vert = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar");
  2324. var horiz = this.horiz = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar");
  2325. place(vert); place(horiz);
  2326. on(vert, "scroll", function() {
  2327. if (vert.clientHeight) scroll(vert.scrollTop, "vertical");
  2328. });
  2329. on(horiz, "scroll", function() {
  2330. if (horiz.clientWidth) scroll(horiz.scrollLeft, "horizontal");
  2331. });
  2332. this.checkedZeroWidth = false;
  2333. // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8).
  2334. if (ie && ie_version < 8) this.horiz.style.minHeight = this.vert.style.minWidth = "18px";
  2335. }
  2336. NativeScrollbars.prototype = copyObj({
  2337. update: function(measure) {
  2338. var needsH = measure.scrollWidth > measure.clientWidth + 1;
  2339. var needsV = measure.scrollHeight > measure.clientHeight + 1;
  2340. var sWidth = measure.nativeBarWidth;
  2341. if (needsV) {
  2342. this.vert.style.display = "block";
  2343. this.vert.style.bottom = needsH ? sWidth + "px" : "0";
  2344. var totalHeight = measure.viewHeight - (needsH ? sWidth : 0);
  2345. // A bug in IE8 can cause this value to be negative, so guard it.
  2346. this.vert.firstChild.style.height =
  2347. Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + "px";
  2348. } else {
  2349. this.vert.style.display = "";
  2350. this.vert.firstChild.style.height = "0";
  2351. }
  2352. if (needsH) {
  2353. this.horiz.style.display = "block";
  2354. this.horiz.style.right = needsV ? sWidth + "px" : "0";
  2355. this.horiz.style.left = measure.barLeft + "px";
  2356. var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0);
  2357. this.horiz.firstChild.style.width =
  2358. (measure.scrollWidth - measure.clientWidth + totalWidth) + "px";
  2359. } else {
  2360. this.horiz.style.display = "";
  2361. this.horiz.firstChild.style.width = "0";
  2362. }
  2363. if (!this.checkedZeroWidth && measure.clientHeight > 0) {
  2364. if (sWidth == 0) this.zeroWidthHack();
  2365. this.checkedZeroWidth = true;
  2366. }
  2367. return {right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0};
  2368. },
  2369. setScrollLeft: function(pos) {
  2370. if (this.horiz.scrollLeft != pos) this.horiz.scrollLeft = pos;
  2371. if (this.disableHoriz) this.enableZeroWidthBar(this.horiz, this.disableHoriz);
  2372. },
  2373. setScrollTop: function(pos) {
  2374. if (this.vert.scrollTop != pos) this.vert.scrollTop = pos;
  2375. if (this.disableVert) this.enableZeroWidthBar(this.vert, this.disableVert);
  2376. },
  2377. zeroWidthHack: function() {
  2378. var w = mac && !mac_geMountainLion ? "12px" : "18px";
  2379. this.horiz.style.height = this.vert.style.width = w;
  2380. this.horiz.style.pointerEvents = this.vert.style.pointerEvents = "none";
  2381. this.disableHoriz = new Delayed;
  2382. this.disableVert = new Delayed;
  2383. },
  2384. enableZeroWidthBar: function(bar, delay) {
  2385. bar.style.pointerEvents = "auto";
  2386. function maybeDisable() {
  2387. // To find out whether the scrollbar is still visible, we
  2388. // check whether the element under the pixel in the bottom
  2389. // left corner of the scrollbar box is the scrollbar box
  2390. // itself (when the bar is still visible) or its filler child
  2391. // (when the bar is hidden). If it is still visible, we keep
  2392. // it enabled, if it's hidden, we disable pointer events.
  2393. var box = bar.getBoundingClientRect();
  2394. var elt = document.elementFromPoint(box.left + 1, box.bottom - 1);
  2395. if (elt != bar) bar.style.pointerEvents = "none";
  2396. else delay.set(1000, maybeDisable);
  2397. }
  2398. delay.set(1000, maybeDisable);
  2399. },
  2400. clear: function() {
  2401. var parent = this.horiz.parentNode;
  2402. parent.removeChild(this.horiz);
  2403. parent.removeChild(this.vert);
  2404. }
  2405. }, NativeScrollbars.prototype);
  2406. function NullScrollbars() {}
  2407. NullScrollbars.prototype = copyObj({
  2408. update: function() { return {bottom: 0, right: 0}; },
  2409. setScrollLeft: function() {},
  2410. setScrollTop: function() {},
  2411. clear: function() {}
  2412. }, NullScrollbars.prototype);
  2413. CodeMirror.scrollbarModel = {"native": NativeScrollbars, "null": NullScrollbars};
  2414. function initScrollbars(cm) {
  2415. if (cm.display.scrollbars) {
  2416. cm.display.scrollbars.clear();
  2417. if (cm.display.scrollbars.addClass)
  2418. rmClass(cm.display.wrapper, cm.display.scrollbars.addClass);
  2419. }
  2420. cm.display.scrollbars = new CodeMirror.scrollbarModel[cm.options.scrollbarStyle](function(node) {
  2421. cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller);
  2422. // Prevent clicks in the scrollbars from killing focus
  2423. on(node, "mousedown", function() {
  2424. if (cm.state.focused) setTimeout(function() { cm.display.input.focus(); }, 0);
  2425. });
  2426. node.setAttribute("cm-not-content", "true");
  2427. }, function(pos, axis) {
  2428. if (axis == "horizontal") setScrollLeft(cm, pos);
  2429. else setScrollTop(cm, pos);
  2430. }, cm);
  2431. if (cm.display.scrollbars.addClass)
  2432. addClass(cm.display.wrapper, cm.display.scrollbars.addClass);
  2433. }
  2434. function updateScrollbars(cm, measure) {
  2435. if (!measure) measure = measureForScrollbars(cm);
  2436. var startWidth = cm.display.barWidth, startHeight = cm.display.barHeight;
  2437. updateScrollbarsInner(cm, measure);
  2438. for (var i = 0; i < 4 && startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i++) {
  2439. if (startWidth != cm.display.barWidth && cm.options.lineWrapping)
  2440. updateHeightsInViewport(cm);
  2441. updateScrollbarsInner(cm, measureForScrollbars(cm));
  2442. startWidth = cm.display.barWidth; startHeight = cm.display.barHeight;
  2443. }
  2444. }
  2445. // Re-synchronize the fake scrollbars with the actual size of the
  2446. // content.
  2447. function updateScrollbarsInner(cm, measure) {
  2448. var d = cm.display;
  2449. var sizes = d.scrollbars.update(measure);
  2450. d.sizer.style.paddingRight = (d.barWidth = sizes.right) + "px";
  2451. d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + "px";
  2452. d.heightForcer.style.borderBottom = sizes.bottom + "px solid transparent"
  2453. if (sizes.right && sizes.bottom) {
  2454. d.scrollbarFiller.style.display = "block";
  2455. d.scrollbarFiller.style.height = sizes.bottom + "px";
  2456. d.scrollbarFiller.style.width = sizes.right + "px";
  2457. } else d.scrollbarFiller.style.display = "";
  2458. if (sizes.bottom && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) {
  2459. d.gutterFiller.style.display = "block";
  2460. d.gutterFiller.style.height = sizes.bottom + "px";
  2461. d.gutterFiller.style.width = measure.gutterWidth + "px";
  2462. } else d.gutterFiller.style.display = "";
  2463. }
  2464. // Compute the lines that are visible in a given viewport (defaults
  2465. // the the current scroll position). viewport may contain top,
  2466. // height, and ensure (see op.scrollToPos) properties.
  2467. function visibleLines(display, doc, viewport) {
  2468. var top = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop;
  2469. top = Math.floor(top - paddingTop(display));
  2470. var bottom = viewport && viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight;
  2471. var from = lineAtHeight(doc, top), to = lineAtHeight(doc, bottom);
  2472. // Ensure is a {from: {line, ch}, to: {line, ch}} object, and
  2473. // forces those lines into the viewport (if possible).
  2474. if (viewport && viewport.ensure) {
  2475. var ensureFrom = viewport.ensure.from.line, ensureTo = viewport.ensure.to.line;
  2476. if (ensureFrom < from) {
  2477. from = ensureFrom;
  2478. to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight);
  2479. } else if (Math.min(ensureTo, doc.lastLine()) >= to) {
  2480. from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight);
  2481. to = ensureTo;
  2482. }
  2483. }
  2484. return {from: from, to: Math.max(to, from + 1)};
  2485. }
  2486. // LINE NUMBERS
  2487. // Re-align line numbers and gutter marks to compensate for
  2488. // horizontal scrolling.
  2489. function alignHorizontally(cm) {
  2490. var display = cm.display, view = display.view;
  2491. if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) return;
  2492. var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft;
  2493. var gutterW = display.gutters.offsetWidth, left = comp + "px";
  2494. for (var i = 0; i < view.length; i++) if (!view[i].hidden) {
  2495. if (cm.options.fixedGutter && view[i].gutter)
  2496. view[i].gutter.style.left = left;
  2497. var align = view[i].alignable;
  2498. if (align) for (var j = 0; j < align.length; j++)
  2499. align[j].style.left = left;
  2500. }
  2501. if (cm.options.fixedGutter)
  2502. display.gutters.style.left = (comp + gutterW) + "px";
  2503. }
  2504. // Used to ensure that the line number gutter is still the right
  2505. // size for the current document size. Returns true when an update
  2506. // is needed.
  2507. function maybeUpdateLineNumberWidth(cm) {
  2508. if (!cm.options.lineNumbers) return false;
  2509. var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display;
  2510. if (last.length != display.lineNumChars) {
  2511. var test = display.measure.appendChild(elt("div", [elt("div", last)],
  2512. "CodeMirror-linenumber CodeMirror-gutter-elt"));
  2513. var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW;
  2514. display.lineGutter.style.width = "";
  2515. display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding) + 1;
  2516. display.lineNumWidth = display.lineNumInnerWidth + padding;
  2517. display.lineNumChars = display.lineNumInnerWidth ? last.length : -1;
  2518. display.lineGutter.style.width = display.lineNumWidth + "px";
  2519. updateGutterSpace(cm);
  2520. return true;
  2521. }
  2522. return false;
  2523. }
  2524. function lineNumberFor(options, i) {
  2525. return String(options.lineNumberFormatter(i + options.firstLineNumber));
  2526. }
  2527. // Computes display.scroller.scrollLeft + display.gutters.offsetWidth,
  2528. // but using getBoundingClientRect to get a sub-pixel-accurate
  2529. // result.
  2530. function compensateForHScroll(display) {
  2531. return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left;
  2532. }
  2533. // DISPLAY DRAWING
  2534. function DisplayUpdate(cm, viewport, force) {
  2535. var display = cm.display;
  2536. this.viewport = viewport;
  2537. // Store some values that we'll need later (but don't want to force a relayout for)
  2538. this.visible = visibleLines(display, cm.doc, viewport);
  2539. this.editorIsHidden = !display.wrapper.offsetWidth;
  2540. this.wrapperHeight = display.wrapper.clientHeight;
  2541. this.wrapperWidth = display.wrapper.clientWidth;
  2542. this.oldDisplayWidth = displayWidth(cm);
  2543. this.force = force;
  2544. this.dims = getDimensions(cm);
  2545. this.events = [];
  2546. }
  2547. DisplayUpdate.prototype.signal = function(emitter, type) {
  2548. if (hasHandler(emitter, type))
  2549. this.events.push(arguments);
  2550. };
  2551. DisplayUpdate.prototype.finish = function() {
  2552. for (var i = 0; i < this.events.length; i++)
  2553. signal.apply(null, this.events[i]);
  2554. };
  2555. function maybeClipScrollbars(cm) {
  2556. var display = cm.display;
  2557. if (!display.scrollbarsClipped && display.scroller.offsetWidth) {
  2558. display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth;
  2559. display.heightForcer.style.height = scrollGap(cm) + "px";
  2560. display.sizer.style.marginBottom = -display.nativeBarWidth + "px";
  2561. display.sizer.style.borderRightWidth = scrollGap(cm) + "px";
  2562. display.scrollbarsClipped = true;
  2563. }
  2564. }
  2565. // Does the actual updating of the line display. Bails out
  2566. // (returning false) when there is nothing to be done and forced is
  2567. // false.
  2568. function updateDisplayIfNeeded(cm, update) {
  2569. var display = cm.display, doc = cm.doc;
  2570. if (update.editorIsHidden) {
  2571. resetView(cm);
  2572. return false;
  2573. }
  2574. // Bail out if the visible area is already rendered and nothing changed.
  2575. if (!update.force &&
  2576. update.visible.from >= display.viewFrom && update.visible.to <= display.viewTo &&
  2577. (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) &&
  2578. display.renderedView == display.view && countDirtyView(cm) == 0)
  2579. return false;
  2580. if (maybeUpdateLineNumberWidth(cm)) {
  2581. resetView(cm);
  2582. update.dims = getDimensions(cm);
  2583. }
  2584. // Compute a suitable new viewport (from & to)
  2585. var end = doc.first + doc.size;
  2586. var from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first);
  2587. var to = Math.min(end, update.visible.to + cm.options.viewportMargin);
  2588. if (display.viewFrom < from && from - display.viewFrom < 20) from = Math.max(doc.first, display.viewFrom);
  2589. if (display.viewTo > to && display.viewTo - to < 20) to = Math.min(end, display.viewTo);
  2590. if (sawCollapsedSpans) {
  2591. from = visualLineNo(cm.doc, from);
  2592. to = visualLineEndNo(cm.doc, to);
  2593. }
  2594. var different = from != display.viewFrom || to != display.viewTo ||
  2595. display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth;
  2596. adjustView(cm, from, to);
  2597. display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom));
  2598. // Position the mover div to align with the current scroll position
  2599. cm.display.mover.style.top = display.viewOffset + "px";
  2600. var toUpdate = countDirtyView(cm);
  2601. if (!different && toUpdate == 0 && !update.force && display.renderedView == display.view &&
  2602. (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo))
  2603. return false;
  2604. // For big changes, we hide the enclosing element during the
  2605. // update, since that speeds up the operations on most browsers.
  2606. var focused = activeElt();
  2607. if (toUpdate > 4) display.lineDiv.style.display = "none";
  2608. patchDisplay(cm, display.updateLineNumbers, update.dims);
  2609. if (toUpdate > 4) display.lineDiv.style.display = "";
  2610. display.renderedView = display.view;
  2611. // There might have been a widget with a focused element that got
  2612. // hidden or updated, if so re-focus it.
  2613. if (focused && activeElt() != focused && focused.offsetHeight) focused.focus();
  2614. // Prevent selection and cursors from interfering with the scroll
  2615. // width and height.
  2616. removeChildren(display.cursorDiv);
  2617. removeChildren(display.selectionDiv);
  2618. display.gutters.style.height = display.sizer.style.minHeight = 0;
  2619. if (different) {
  2620. display.lastWrapHeight = update.wrapperHeight;
  2621. display.lastWrapWidth = update.wrapperWidth;
  2622. startWorker(cm, 400);
  2623. }
  2624. display.updateLineNumbers = null;
  2625. return true;
  2626. }
  2627. function postUpdateDisplay(cm, update) {
  2628. var viewport = update.viewport;
  2629. for (var first = true;; first = false) {
  2630. if (!first || !cm.options.lineWrapping || update.oldDisplayWidth == displayWidth(cm)) {
  2631. // Clip forced viewport to actual scrollable area.
  2632. if (viewport && viewport.top != null)
  2633. viewport = {top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top)};
  2634. // Updated line heights might result in the drawn area not
  2635. // actually covering the viewport. Keep looping until it does.
  2636. update.visible = visibleLines(cm.display, cm.doc, viewport);
  2637. if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo)
  2638. break;
  2639. }
  2640. if (!updateDisplayIfNeeded(cm, update)) break;
  2641. updateHeightsInViewport(cm);
  2642. var barMeasure = measureForScrollbars(cm);
  2643. updateSelection(cm);
  2644. updateScrollbars(cm, barMeasure);
  2645. setDocumentHeight(cm, barMeasure);
  2646. }
  2647. update.signal(cm, "update", cm);
  2648. if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) {
  2649. update.signal(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo);
  2650. cm.display.reportedViewFrom = cm.display.viewFrom; cm.display.reportedViewTo = cm.display.viewTo;
  2651. }
  2652. }
  2653. function updateDisplaySimple(cm, viewport) {
  2654. var update = new DisplayUpdate(cm, viewport);
  2655. if (updateDisplayIfNeeded(cm, update)) {
  2656. updateHeightsInViewport(cm);
  2657. postUpdateDisplay(cm, update);
  2658. var barMeasure = measureForScrollbars(cm);
  2659. updateSelection(cm);
  2660. updateScrollbars(cm, barMeasure);
  2661. setDocumentHeight(cm, barMeasure);
  2662. update.finish();
  2663. }
  2664. }
  2665. function setDocumentHeight(cm, measure) {
  2666. cm.display.sizer.style.minHeight = measure.docHeight + "px";
  2667. cm.display.heightForcer.style.top = measure.docHeight + "px";
  2668. cm.display.gutters.style.height = (measure.docHeight + cm.display.barHeight + scrollGap(cm)) + "px";
  2669. }
  2670. // Read the actual heights of the rendered lines, and update their
  2671. // stored heights to match.
  2672. function updateHeightsInViewport(cm) {
  2673. var display = cm.display;
  2674. var prevBottom = display.lineDiv.offsetTop;
  2675. for (var i = 0; i < display.view.length; i++) {
  2676. var cur = display.view[i], height;
  2677. if (cur.hidden) continue;
  2678. if (ie && ie_version < 8) {
  2679. var bot = cur.node.offsetTop + cur.node.offsetHeight;
  2680. height = bot - prevBottom;
  2681. prevBottom = bot;
  2682. } else {
  2683. var box = cur.node.getBoundingClientRect();
  2684. height = box.bottom - box.top;
  2685. }
  2686. var diff = cur.line.height - height;
  2687. if (height < 2) height = textHeight(display);
  2688. if (diff > .001 || diff < -.001) {
  2689. updateLineHeight(cur.line, height);
  2690. updateWidgetHeight(cur.line);
  2691. if (cur.rest) for (var j = 0; j < cur.rest.length; j++)
  2692. updateWidgetHeight(cur.rest[j]);
  2693. }
  2694. }
  2695. }
  2696. // Read and store the height of line widgets associated with the
  2697. // given line.
  2698. function updateWidgetHeight(line) {
  2699. if (line.widgets) for (var i = 0; i < line.widgets.length; ++i)
  2700. line.widgets[i].height = line.widgets[i].node.parentNode.offsetHeight;
  2701. }
  2702. // Do a bulk-read of the DOM positions and sizes needed to draw the
  2703. // view, so that we don't interleave reading and writing to the DOM.
  2704. function getDimensions(cm) {
  2705. var d = cm.display, left = {}, width = {};
  2706. var gutterLeft = d.gutters.clientLeft;
  2707. for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) {
  2708. left[cm.options.gutters[i]] = n.offsetLeft + n.clientLeft + gutterLeft;
  2709. width[cm.options.gutters[i]] = n.clientWidth;
  2710. }
  2711. return {fixedPos: compensateForHScroll(d),
  2712. gutterTotalWidth: d.gutters.offsetWidth,
  2713. gutterLeft: left,
  2714. gutterWidth: width,
  2715. wrapperWidth: d.wrapper.clientWidth};
  2716. }
  2717. // Sync the actual display DOM structure with display.view, removing
  2718. // nodes for lines that are no longer in view, and creating the ones
  2719. // that are not there yet, and updating the ones that are out of
  2720. // date.
  2721. function patchDisplay(cm, updateNumbersFrom, dims) {
  2722. var display = cm.display, lineNumbers = cm.options.lineNumbers;
  2723. var container = display.lineDiv, cur = container.firstChild;
  2724. function rm(node) {
  2725. var next = node.nextSibling;
  2726. // Works around a throw-scroll bug in OS X Webkit
  2727. if (webkit && mac && cm.display.currentWheelTarget == node)
  2728. node.style.display = "none";
  2729. else
  2730. node.parentNode.removeChild(node);
  2731. return next;
  2732. }
  2733. var view = display.view, lineN = display.viewFrom;
  2734. // Loop over the elements in the view, syncing cur (the DOM nodes
  2735. // in display.lineDiv) with the view as we go.
  2736. for (var i = 0; i < view.length; i++) {
  2737. var lineView = view[i];
  2738. if (lineView.hidden) {
  2739. } else if (!lineView.node || lineView.node.parentNode != container) { // Not drawn yet
  2740. var node = buildLineElement(cm, lineView, lineN, dims);
  2741. container.insertBefore(node, cur);
  2742. } else { // Already drawn
  2743. while (cur != lineView.node) cur = rm(cur);
  2744. var updateNumber = lineNumbers && updateNumbersFrom != null &&
  2745. updateNumbersFrom <= lineN && lineView.lineNumber;
  2746. if (lineView.changes) {
  2747. if (indexOf(lineView.changes, "gutter") > -1) updateNumber = false;
  2748. updateLineForChanges(cm, lineView, lineN, dims);
  2749. }
  2750. if (updateNumber) {
  2751. removeChildren(lineView.lineNumber);
  2752. lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN)));
  2753. }
  2754. cur = lineView.node.nextSibling;
  2755. }
  2756. lineN += lineView.size;
  2757. }
  2758. while (cur) cur = rm(cur);
  2759. }
  2760. // When an aspect of a line changes, a string is added to
  2761. // lineView.changes. This updates the relevant part of the line's
  2762. // DOM structure.
  2763. function updateLineForChanges(cm, lineView, lineN, dims) {
  2764. for (var j = 0; j < lineView.changes.length; j++) {
  2765. var type = lineView.changes[j];
  2766. if (type == "text") updateLineText(cm, lineView);
  2767. else if (type == "gutter") updateLineGutter(cm, lineView, lineN, dims);
  2768. else if (type == "class") updateLineClasses(lineView);
  2769. else if (type == "widget") updateLineWidgets(cm, lineView, dims);
  2770. }
  2771. lineView.changes = null;
  2772. }
  2773. // Lines with gutter elements, widgets or a background class need to
  2774. // be wrapped, and have the extra elements added to the wrapper div
  2775. function ensureLineWrapped(lineView) {
  2776. if (lineView.node == lineView.text) {
  2777. lineView.node = elt("div", null, null, "position: relative");
  2778. if (lineView.text.parentNode)
  2779. lineView.text.parentNode.replaceChild(lineView.node, lineView.text);
  2780. lineView.node.appendChild(lineView.text);
  2781. if (ie && ie_version < 8) lineView.node.style.zIndex = 2;
  2782. }
  2783. return lineView.node;
  2784. }
  2785. function updateLineBackground(lineView) {
  2786. var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass;
  2787. if (cls) cls += " CodeMirror-linebackground";
  2788. if (lineView.background) {
  2789. if (cls) lineView.background.className = cls;
  2790. else { lineView.background.parentNode.removeChild(lineView.background); lineView.background = null; }
  2791. } else if (cls) {
  2792. var wrap = ensureLineWrapped(lineView);
  2793. lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild);
  2794. }
  2795. }
  2796. // Wrapper around buildLineContent which will reuse the structure
  2797. // in display.externalMeasured when possible.
  2798. function getLineContent(cm, lineView) {
  2799. var ext = cm.display.externalMeasured;
  2800. if (ext && ext.line == lineView.line) {
  2801. cm.display.externalMeasured = null;
  2802. lineView.measure = ext.measure;
  2803. return ext.built;
  2804. }
  2805. return buildLineContent(cm, lineView);
  2806. }
  2807. // Redraw the line's text. Interacts with the background and text
  2808. // classes because the mode may output tokens that influence these
  2809. // classes.
  2810. function updateLineText(cm, lineView) {
  2811. var cls = lineView.text.className;
  2812. var built = getLineContent(cm, lineView);
  2813. if (lineView.text == lineView.node) lineView.node = built.pre;
  2814. lineView.text.parentNode.replaceChild(built.pre, lineView.text);
  2815. lineView.text = built.pre;
  2816. if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) {
  2817. lineView.bgClass = built.bgClass;
  2818. lineView.textClass = built.textClass;
  2819. updateLineClasses(lineView);
  2820. } else if (cls) {
  2821. lineView.text.className = cls;
  2822. }
  2823. }
  2824. function updateLineClasses(lineView) {
  2825. updateLineBackground(lineView);
  2826. if (lineView.line.wrapClass)
  2827. ensureLineWrapped(lineView).className = lineView.line.wrapClass;
  2828. else if (lineView.node != lineView.text)
  2829. lineView.node.className = "";
  2830. var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass;
  2831. lineView.text.className = textClass || "";
  2832. }
  2833. function updateLineGutter(cm, lineView, lineN, dims) {
  2834. if (lineView.gutter) {
  2835. lineView.node.removeChild(lineView.gutter);
  2836. lineView.gutter = null;
  2837. }
  2838. if (lineView.gutterBackground) {
  2839. lineView.node.removeChild(lineView.gutterBackground);
  2840. lineView.gutterBackground = null;
  2841. }
  2842. if (lineView.line.gutterClass) {
  2843. var wrap = ensureLineWrapped(lineView);
  2844. lineView.gutterBackground = elt("div", null, "CodeMirror-gutter-background " + lineView.line.gutterClass,
  2845. "left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) +
  2846. "px; width: " + dims.gutterTotalWidth + "px");
  2847. wrap.insertBefore(lineView.gutterBackground, lineView.text);
  2848. }
  2849. var markers = lineView.line.gutterMarkers;
  2850. if (cm.options.lineNumbers || markers) {
  2851. var wrap = ensureLineWrapped(lineView);
  2852. var gutterWrap = lineView.gutter = elt("div", null, "CodeMirror-gutter-wrapper", "left: " +
  2853. (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px");
  2854. cm.display.input.setUneditable(gutterWrap);
  2855. wrap.insertBefore(gutterWrap, lineView.text);
  2856. if (lineView.line.gutterClass)
  2857. gutterWrap.className += " " + lineView.line.gutterClass;
  2858. if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"]))
  2859. lineView.lineNumber = gutterWrap.appendChild(
  2860. elt("div", lineNumberFor(cm.options, lineN),
  2861. "CodeMirror-linenumber CodeMirror-gutter-elt",
  2862. "left: " + dims.gutterLeft["CodeMirror-linenumbers"] + "px; width: "
  2863. + cm.display.lineNumInnerWidth + "px"));
  2864. if (markers) for (var k = 0; k < cm.options.gutters.length; ++k) {
  2865. var id = cm.options.gutters[k], found = markers.hasOwnProperty(id) && markers[id];
  2866. if (found)
  2867. gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt", "left: " +
  2868. dims.gutterLeft[id] + "px; width: " + dims.gutterWidth[id] + "px"));
  2869. }
  2870. }
  2871. }
  2872. function updateLineWidgets(cm, lineView, dims) {
  2873. if (lineView.alignable) lineView.alignable = null;
  2874. for (var node = lineView.node.firstChild, next; node; node = next) {
  2875. var next = node.nextSibling;
  2876. if (node.className == "CodeMirror-linewidget")
  2877. lineView.node.removeChild(node);
  2878. }
  2879. insertLineWidgets(cm, lineView, dims);
  2880. }
  2881. // Build a line's DOM representation from scratch
  2882. function buildLineElement(cm, lineView, lineN, dims) {
  2883. var built = getLineContent(cm, lineView);
  2884. lineView.text = lineView.node = built.pre;
  2885. if (built.bgClass) lineView.bgClass = built.bgClass;
  2886. if (built.textClass) lineView.textClass = built.textClass;
  2887. updateLineClasses(lineView);
  2888. updateLineGutter(cm, lineView, lineN, dims);
  2889. insertLineWidgets(cm, lineView, dims);
  2890. return lineView.node;
  2891. }
  2892. // A lineView may contain multiple logical lines (when merged by
  2893. // collapsed spans). The widgets for all of them need to be drawn.
  2894. function insertLineWidgets(cm, lineView, dims) {
  2895. insertLineWidgetsFor(cm, lineView.line, lineView, dims, true);
  2896. if (lineView.rest) for (var i = 0; i < lineView.rest.length; i++)
  2897. insertLineWidgetsFor(cm, lineView.rest[i], lineView, dims, false);
  2898. }
  2899. function insertLineWidgetsFor(cm, line, lineView, dims, allowAbove) {
  2900. if (!line.widgets) return;
  2901. var wrap = ensureLineWrapped(lineView);
  2902. for (var i = 0, ws = line.widgets; i < ws.length; ++i) {
  2903. var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget");
  2904. if (!widget.handleMouseEvents) node.setAttribute("cm-ignore-events", "true");
  2905. positionLineWidget(widget, node, lineView, dims);
  2906. cm.display.input.setUneditable(node);
  2907. if (allowAbove && widget.above)
  2908. wrap.insertBefore(node, lineView.gutter || lineView.text);
  2909. else
  2910. wrap.appendChild(node);
  2911. signalLater(widget, "redraw");
  2912. }
  2913. }
  2914. function positionLineWidget(widget, node, lineView, dims) {
  2915. if (widget.noHScroll) {
  2916. (lineView.alignable || (lineView.alignable = [])).push(node);
  2917. var width = dims.wrapperWidth;
  2918. node.style.left = dims.fixedPos + "px";
  2919. if (!widget.coverGutter) {
  2920. width -= dims.gutterTotalWidth;
  2921. node.style.paddingLeft = dims.gutterTotalWidth + "px";
  2922. }
  2923. node.style.width = width + "px";
  2924. }
  2925. if (widget.coverGutter) {
  2926. node.style.zIndex = 5;
  2927. node.style.position = "relative";
  2928. if (!widget.noHScroll) node.style.marginLeft = -dims.gutterTotalWidth + "px";
  2929. }
  2930. }
  2931. // POSITION OBJECT
  2932. // A Pos instance represents a position within the text.
  2933. var Pos = CodeMirror.Pos = function(line, ch) {
  2934. if (!(this instanceof Pos)) return new Pos(line, ch);
  2935. this.line = line; this.ch = ch;
  2936. };
  2937. // Compare two positions, return 0 if they are the same, a negative
  2938. // number when a is less, and a positive number otherwise.
  2939. var cmp = CodeMirror.cmpPos = function(a, b) { return a.line - b.line || a.ch - b.ch; };
  2940. function copyPos(x) {return Pos(x.line, x.ch);}
  2941. function maxPos(a, b) { return cmp(a, b) < 0 ? b : a; }
  2942. function minPos(a, b) { return cmp(a, b) < 0 ? a : b; }
  2943. // INPUT HANDLING
  2944. function ensureFocus(cm) {
  2945. if (!cm.state.focused) { cm.display.input.focus(); onFocus(cm); }
  2946. }
  2947. // This will be set to a {lineWise: bool, text: [string]} object, so
  2948. // that, when pasting, we know what kind of selections the copied
  2949. // text was made out of.
  2950. var lastCopied = null;
  2951. function applyTextInput(cm, inserted, deleted, sel, origin) {
  2952. var doc = cm.doc;
  2953. cm.display.shift = false;
  2954. if (!sel) sel = doc.sel;
  2955. var paste = cm.state.pasteIncoming || origin == "paste";
  2956. var textLines = doc.splitLines(inserted), multiPaste = null
  2957. // When pasing N lines into N selections, insert one line per selection
  2958. if (paste && sel.ranges.length > 1) {
  2959. if (lastCopied && lastCopied.text.join("\n") == inserted) {
  2960. if (sel.ranges.length % lastCopied.text.length == 0) {
  2961. multiPaste = [];
  2962. for (var i = 0; i < lastCopied.text.length; i++)
  2963. multiPaste.push(doc.splitLines(lastCopied.text[i]));
  2964. }
  2965. } else if (textLines.length == sel.ranges.length) {
  2966. multiPaste = map(textLines, function(l) { return [l]; });
  2967. }
  2968. }
  2969. // Normal behavior is to insert the new text into every selection
  2970. for (var i = sel.ranges.length - 1; i >= 0; i--) {
  2971. var range = sel.ranges[i];
  2972. var from = range.from(), to = range.to();
  2973. if (range.empty()) {
  2974. if (deleted && deleted > 0) // Handle deletion
  2975. from = Pos(from.line, from.ch - deleted);
  2976. else if (cm.state.overwrite && !paste) // Handle overwrite
  2977. to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length));
  2978. else if (lastCopied && lastCopied.lineWise && lastCopied.text.join("\n") == inserted)
  2979. from = to = Pos(from.line, 0)
  2980. }
  2981. var updateInput = cm.curOp.updateInput;
  2982. var changeEvent = {from: from, to: to, text: multiPaste ? multiPaste[i % multiPaste.length] : textLines,
  2983. origin: origin || (paste ? "paste" : cm.state.cutIncoming ? "cut" : "+input")};
  2984. makeChange(cm.doc, changeEvent);
  2985. signalLater(cm, "inputRead", cm, changeEvent);
  2986. }
  2987. if (inserted && !paste)
  2988. triggerElectric(cm, inserted);
  2989. ensureCursorVisible(cm);
  2990. cm.curOp.updateInput = updateInput;
  2991. cm.curOp.typing = true;
  2992. cm.state.pasteIncoming = cm.state.cutIncoming = false;
  2993. }
  2994. function handlePaste(e, cm) {
  2995. var pasted = e.clipboardData && e.clipboardData.getData("text/plain");
  2996. if (pasted) {
  2997. e.preventDefault();
  2998. if (!cm.isReadOnly() && !cm.options.disableInput)
  2999. runInOp(cm, function() { applyTextInput(cm, pasted, 0, null, "paste"); });
  3000. return true;
  3001. }
  3002. }
  3003. function triggerElectric(cm, inserted) {
  3004. // When an 'electric' character is inserted, immediately trigger a reindent
  3005. if (!cm.options.electricChars || !cm.options.smartIndent) return;
  3006. var sel = cm.doc.sel;
  3007. for (var i = sel.ranges.length - 1; i >= 0; i--) {
  3008. var range = sel.ranges[i];
  3009. if (range.head.ch > 100 || (i && sel.ranges[i - 1].head.line == range.head.line)) continue;
  3010. var mode = cm.getModeAt(range.head);
  3011. var indented = false;
  3012. if (mode.electricChars) {
  3013. for (var j = 0; j < mode.electricChars.length; j++)
  3014. if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) {
  3015. indented = indentLine(cm, range.head.line, "smart");
  3016. break;
  3017. }
  3018. } else if (mode.electricInput) {
  3019. if (mode.electricInput.test(getLine(cm.doc, range.head.line).text.slice(0, range.head.ch)))
  3020. indented = indentLine(cm, range.head.line, "smart");
  3021. }
  3022. if (indented) signalLater(cm, "electricInput", cm, range.head.line);
  3023. }
  3024. }
  3025. function copyableRanges(cm) {
  3026. var text = [], ranges = [];
  3027. for (var i = 0; i < cm.doc.sel.ranges.length; i++) {
  3028. var line = cm.doc.sel.ranges[i].head.line;
  3029. var lineRange = {anchor: Pos(line, 0), head: Pos(line + 1, 0)};
  3030. ranges.push(lineRange);
  3031. text.push(cm.getRange(lineRange.anchor, lineRange.head));
  3032. }
  3033. return {text: text, ranges: ranges};
  3034. }
  3035. function disableBrowserMagic(field) {
  3036. field.setAttribute("autocorrect", "off");
  3037. field.setAttribute("autocapitalize", "off");
  3038. field.setAttribute("spellcheck", "false");
  3039. }
  3040. // TEXTAREA INPUT STYLE
  3041. function TextareaInput(cm) {
  3042. this.cm = cm;
  3043. // See input.poll and input.reset
  3044. this.prevInput = "";
  3045. // Flag that indicates whether we expect input to appear real soon
  3046. // now (after some event like 'keypress' or 'input') and are
  3047. // polling intensively.
  3048. this.pollingFast = false;
  3049. // Self-resetting timeout for the poller
  3050. this.polling = new Delayed();
  3051. // Tracks when input.reset has punted to just putting a short
  3052. // string into the textarea instead of the full selection.
  3053. this.inaccurateSelection = false;
  3054. // Used to work around IE issue with selection being forgotten when focus moves away from textarea
  3055. this.hasSelection = false;
  3056. this.composing = null;
  3057. };
  3058. function hiddenTextarea() {
  3059. var te = elt("textarea", null, null, "position: absolute; padding: 0; width: 1px; height: 1em; outline: none");
  3060. var div = elt("div", [te], null, "overflow: hidden; position: relative; width: 3px; height: 0px;");
  3061. // The textarea is kept positioned near the cursor to prevent the
  3062. // fact that it'll be scrolled into view on input from scrolling
  3063. // our fake cursor out of view. On webkit, when wrap=off, paste is
  3064. // very slow. So make the area wide instead.
  3065. if (webkit) te.style.width = "1000px";
  3066. else te.setAttribute("wrap", "off");
  3067. // If border: 0; -- iOS fails to open keyboard (issue #1287)
  3068. if (ios) te.style.border = "1px solid black";
  3069. disableBrowserMagic(te);
  3070. return div;
  3071. }
  3072. TextareaInput.prototype = copyObj({
  3073. init: function(display) {
  3074. var input = this, cm = this.cm;
  3075. // Wraps and hides input textarea
  3076. var div = this.wrapper = hiddenTextarea();
  3077. // The semihidden textarea that is focused when the editor is
  3078. // focused, and receives input.
  3079. var te = this.textarea = div.firstChild;
  3080. display.wrapper.insertBefore(div, display.wrapper.firstChild);
  3081. // Needed to hide big blue blinking cursor on Mobile Safari (doesn't seem to work in iOS 8 anymore)
  3082. if (ios) te.style.width = "0px";
  3083. on(te, "input", function() {
  3084. if (ie && ie_version >= 9 && input.hasSelection) input.hasSelection = null;
  3085. input.poll();
  3086. });
  3087. on(te, "paste", function(e) {
  3088. if (signalDOMEvent(cm, e) || handlePaste(e, cm)) return
  3089. cm.state.pasteIncoming = true;
  3090. input.fastPoll();
  3091. });
  3092. function prepareCopyCut(e) {
  3093. if (signalDOMEvent(cm, e)) return
  3094. if (cm.somethingSelected()) {
  3095. lastCopied = {lineWise: false, text: cm.getSelections()};
  3096. if (input.inaccurateSelection) {
  3097. input.prevInput = "";
  3098. input.inaccurateSelection = false;
  3099. te.value = lastCopied.text.join("\n");
  3100. selectInput(te);
  3101. }
  3102. } else if (!cm.options.lineWiseCopyCut) {
  3103. return;
  3104. } else {
  3105. var ranges = copyableRanges(cm);
  3106. lastCopied = {lineWise: true, text: ranges.text};
  3107. if (e.type == "cut") {
  3108. cm.setSelections(ranges.ranges, null, sel_dontScroll);
  3109. } else {
  3110. input.prevInput = "";
  3111. te.value = ranges.text.join("\n");
  3112. selectInput(te);
  3113. }
  3114. }
  3115. if (e.type == "cut") cm.state.cutIncoming = true;
  3116. }
  3117. on(te, "cut", prepareCopyCut);
  3118. on(te, "copy", prepareCopyCut);
  3119. on(display.scroller, "paste", function(e) {
  3120. if (eventInWidget(display, e) || signalDOMEvent(cm, e)) return;
  3121. cm.state.pasteIncoming = true;
  3122. input.focus();
  3123. });
  3124. // Prevent normal selection in the editor (we handle our own)
  3125. on(display.lineSpace, "selectstart", function(e) {
  3126. if (!eventInWidget(display, e)) e_preventDefault(e);
  3127. });
  3128. on(te, "compositionstart", function() {
  3129. var start = cm.getCursor("from");
  3130. if (input.composing) input.composing.range.clear()
  3131. input.composing = {
  3132. start: start,
  3133. range: cm.markText(start, cm.getCursor("to"), {className: "CodeMirror-composing"})
  3134. };
  3135. });
  3136. on(te, "compositionend", function() {
  3137. if (input.composing) {
  3138. input.poll();
  3139. input.composing.range.clear();
  3140. input.composing = null;
  3141. }
  3142. });
  3143. },
  3144. prepareSelection: function() {
  3145. // Redraw the selection and/or cursor
  3146. var cm = this.cm, display = cm.display, doc = cm.doc;
  3147. var result = prepareSelection(cm);
  3148. // Move the hidden textarea near the cursor to prevent scrolling artifacts
  3149. if (cm.options.moveInputWithCursor) {
  3150. var headPos = cursorCoords(cm, doc.sel.primary().head, "div");
  3151. var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect();
  3152. result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10,
  3153. headPos.top + lineOff.top - wrapOff.top));
  3154. result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10,
  3155. headPos.left + lineOff.left - wrapOff.left));
  3156. }
  3157. return result;
  3158. },
  3159. showSelection: function(drawn) {
  3160. var cm = this.cm, display = cm.display;
  3161. removeChildrenAndAdd(display.cursorDiv, drawn.cursors);
  3162. removeChildrenAndAdd(display.selectionDiv, drawn.selection);
  3163. if (drawn.teTop != null) {
  3164. this.wrapper.style.top = drawn.teTop + "px";
  3165. this.wrapper.style.left = drawn.teLeft + "px";
  3166. }
  3167. },
  3168. // Reset the input to correspond to the selection (or to be empty,
  3169. // when not typing and nothing is selected)
  3170. reset: function(typing) {
  3171. if (this.contextMenuPending) return;
  3172. var minimal, selected, cm = this.cm, doc = cm.doc;
  3173. if (cm.somethingSelected()) {
  3174. this.prevInput = "";
  3175. var range = doc.sel.primary();
  3176. minimal = hasCopyEvent &&
  3177. (range.to().line - range.from().line > 100 || (selected = cm.getSelection()).length > 1000);
  3178. var content = minimal ? "-" : selected || cm.getSelection();
  3179. this.textarea.value = content;
  3180. if (cm.state.focused) selectInput(this.textarea);
  3181. if (ie && ie_version >= 9) this.hasSelection = content;
  3182. } else if (!typing) {
  3183. this.prevInput = this.textarea.value = "";
  3184. if (ie && ie_version >= 9) this.hasSelection = null;
  3185. }
  3186. this.inaccurateSelection = minimal;
  3187. },
  3188. getField: function() { return this.textarea; },
  3189. supportsTouch: function() { return false; },
  3190. focus: function() {
  3191. if (this.cm.options.readOnly != "nocursor" && (!mobile || activeElt() != this.textarea)) {
  3192. try { this.textarea.focus(); }
  3193. catch (e) {} // IE8 will throw if the textarea is display: none or not in DOM
  3194. }
  3195. },
  3196. blur: function() { this.textarea.blur(); },
  3197. resetPosition: function() {
  3198. this.wrapper.style.top = this.wrapper.style.left = 0;
  3199. },
  3200. receivedFocus: function() { this.slowPoll(); },
  3201. // Poll for input changes, using the normal rate of polling. This
  3202. // runs as long as the editor is focused.
  3203. slowPoll: function() {
  3204. var input = this;
  3205. if (input.pollingFast) return;
  3206. input.polling.set(this.cm.options.pollInterval, function() {
  3207. input.poll();
  3208. if (input.cm.state.focused) input.slowPoll();
  3209. });
  3210. },
  3211. // When an event has just come in that is likely to add or change
  3212. // something in the input textarea, we poll faster, to ensure that
  3213. // the change appears on the screen quickly.
  3214. fastPoll: function() {
  3215. var missed = false, input = this;
  3216. input.pollingFast = true;
  3217. function p() {
  3218. var changed = input.poll();
  3219. if (!changed && !missed) {missed = true; input.polling.set(60, p);}
  3220. else {input.pollingFast = false; input.slowPoll();}
  3221. }
  3222. input.polling.set(20, p);
  3223. },
  3224. // Read input from the textarea, and update the document to match.
  3225. // When something is selected, it is present in the textarea, and
  3226. // selected (unless it is huge, in which case a placeholder is
  3227. // used). When nothing is selected, the cursor sits after previously
  3228. // seen text (can be empty), which is stored in prevInput (we must
  3229. // not reset the textarea when typing, because that breaks IME).
  3230. poll: function() {
  3231. var cm = this.cm, input = this.textarea, prevInput = this.prevInput;
  3232. // Since this is called a *lot*, try to bail out as cheaply as
  3233. // possible when it is clear that nothing happened. hasSelection
  3234. // will be the case when there is a lot of text in the textarea,
  3235. // in which case reading its value would be expensive.
  3236. if (this.contextMenuPending || !cm.state.focused ||
  3237. (hasSelection(input) && !prevInput && !this.composing) ||
  3238. cm.isReadOnly() || cm.options.disableInput || cm.state.keySeq)
  3239. return false;
  3240. var text = input.value;
  3241. // If nothing changed, bail.
  3242. if (text == prevInput && !cm.somethingSelected()) return false;
  3243. // Work around nonsensical selection resetting in IE9/10, and
  3244. // inexplicable appearance of private area unicode characters on
  3245. // some key combos in Mac (#2689).
  3246. if (ie && ie_version >= 9 && this.hasSelection === text ||
  3247. mac && /[\uf700-\uf7ff]/.test(text)) {
  3248. cm.display.input.reset();
  3249. return false;
  3250. }
  3251. if (cm.doc.sel == cm.display.selForContextMenu) {
  3252. var first = text.charCodeAt(0);
  3253. if (first == 0x200b && !prevInput) prevInput = "\u200b";
  3254. if (first == 0x21da) { this.reset(); return this.cm.execCommand("undo"); }
  3255. }
  3256. // Find the part of the input that is actually new
  3257. var same = 0, l = Math.min(prevInput.length, text.length);
  3258. while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) ++same;
  3259. var self = this;
  3260. runInOp(cm, function() {
  3261. applyTextInput(cm, text.slice(same), prevInput.length - same,
  3262. null, self.composing ? "*compose" : null);
  3263. // Don't leave long text in the textarea, since it makes further polling slow
  3264. if (text.length > 1000 || text.indexOf("\n") > -1) input.value = self.prevInput = "";
  3265. else self.prevInput = text;
  3266. if (self.composing) {
  3267. self.composing.range.clear();
  3268. self.composing.range = cm.markText(self.composing.start, cm.getCursor("to"),
  3269. {className: "CodeMirror-composing"});
  3270. }
  3271. });
  3272. return true;
  3273. },
  3274. ensurePolled: function() {
  3275. if (this.pollingFast && this.poll()) this.pollingFast = false;
  3276. },
  3277. onKeyPress: function() {
  3278. if (ie && ie_version >= 9) this.hasSelection = null;
  3279. this.fastPoll();
  3280. },
  3281. onContextMenu: function(e) {
  3282. var input = this, cm = input.cm, display = cm.display, te = input.textarea;
  3283. var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop;
  3284. if (!pos || presto) return; // Opera is difficult.
  3285. // Reset the current text selection only if the click is done outside of the selection
  3286. // and 'resetSelectionOnContextMenu' option is true.
  3287. var reset = cm.options.resetSelectionOnContextMenu;
  3288. if (reset && cm.doc.sel.contains(pos) == -1)
  3289. operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll);
  3290. var oldCSS = te.style.cssText, oldWrapperCSS = input.wrapper.style.cssText;
  3291. input.wrapper.style.cssText = "position: absolute"
  3292. var wrapperBox = input.wrapper.getBoundingClientRect()
  3293. te.style.cssText = "position: absolute; width: 30px; height: 30px; top: " + (e.clientY - wrapperBox.top - 5) +
  3294. "px; left: " + (e.clientX - wrapperBox.left - 5) + "px; z-index: 1000; background: " +
  3295. (ie ? "rgba(255, 255, 255, .05)" : "transparent") +
  3296. "; outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);";
  3297. if (webkit) var oldScrollY = window.scrollY; // Work around Chrome issue (#2712)
  3298. display.input.focus();
  3299. if (webkit) window.scrollTo(null, oldScrollY);
  3300. display.input.reset();
  3301. // Adds "Select all" to context menu in FF
  3302. if (!cm.somethingSelected()) te.value = input.prevInput = " ";
  3303. input.contextMenuPending = true;
  3304. display.selForContextMenu = cm.doc.sel;
  3305. clearTimeout(display.detectingSelectAll);
  3306. // Select-all will be greyed out if there's nothing to select, so
  3307. // this adds a zero-width space so that we can later check whether
  3308. // it got selected.
  3309. function prepareSelectAllHack() {
  3310. if (te.selectionStart != null) {
  3311. var selected = cm.somethingSelected();
  3312. var extval = "\u200b" + (selected ? te.value : "");
  3313. te.value = "\u21da"; // Used to catch context-menu undo
  3314. te.value = extval;
  3315. input.prevInput = selected ? "" : "\u200b";
  3316. te.selectionStart = 1; te.selectionEnd = extval.length;
  3317. // Re-set this, in case some other handler touched the
  3318. // selection in the meantime.
  3319. display.selForContextMenu = cm.doc.sel;
  3320. }
  3321. }
  3322. function rehide() {
  3323. input.contextMenuPending = false;
  3324. input.wrapper.style.cssText = oldWrapperCSS
  3325. te.style.cssText = oldCSS;
  3326. if (ie && ie_version < 9) display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos);
  3327. // Try to detect the user choosing select-all
  3328. if (te.selectionStart != null) {
  3329. if (!ie || (ie && ie_version < 9)) prepareSelectAllHack();
  3330. var i = 0, poll = function() {
  3331. if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0 &&
  3332. te.selectionEnd > 0 && input.prevInput == "\u200b")
  3333. operation(cm, commands.selectAll)(cm);
  3334. else if (i++ < 10) display.detectingSelectAll = setTimeout(poll, 500);
  3335. else display.input.reset();
  3336. };
  3337. display.detectingSelectAll = setTimeout(poll, 200);
  3338. }
  3339. }
  3340. if (ie && ie_version >= 9) prepareSelectAllHack();
  3341. if (captureRightClick) {
  3342. e_stop(e);
  3343. var mouseup = function() {
  3344. off(window, "mouseup", mouseup);
  3345. setTimeout(rehide, 20);
  3346. };
  3347. on(window, "mouseup", mouseup);
  3348. } else {
  3349. setTimeout(rehide, 50);
  3350. }
  3351. },
  3352. readOnlyChanged: function(val) {
  3353. if (!val) this.reset();
  3354. },
  3355. setUneditable: nothing,
  3356. needsContentAttribute: false
  3357. }, TextareaInput.prototype);
  3358. // CONTENTEDITABLE INPUT STYLE
  3359. function ContentEditableInput(cm) {
  3360. this.cm = cm;
  3361. this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null;
  3362. this.polling = new Delayed();
  3363. this.gracePeriod = false;
  3364. }
  3365. ContentEditableInput.prototype = copyObj({
  3366. init: function(display) {
  3367. var input = this, cm = input.cm;
  3368. var div = input.div = display.lineDiv;
  3369. disableBrowserMagic(div);
  3370. on(div, "paste", function(e) {
  3371. if (!signalDOMEvent(cm, e)) handlePaste(e, cm);
  3372. })
  3373. on(div, "compositionstart", function(e) {
  3374. var data = e.data;
  3375. input.composing = {sel: cm.doc.sel, data: data, startData: data};
  3376. if (!data) return;
  3377. var prim = cm.doc.sel.primary();
  3378. var line = cm.getLine(prim.head.line);
  3379. var found = line.indexOf(data, Math.max(0, prim.head.ch - data.length));
  3380. if (found > -1 && found <= prim.head.ch)
  3381. input.composing.sel = simpleSelection(Pos(prim.head.line, found),
  3382. Pos(prim.head.line, found + data.length));
  3383. });
  3384. on(div, "compositionupdate", function(e) {
  3385. input.composing.data = e.data;
  3386. });
  3387. on(div, "compositionend", function(e) {
  3388. var ours = input.composing;
  3389. if (!ours) return;
  3390. if (e.data != ours.startData && !/\u200b/.test(e.data))
  3391. ours.data = e.data;
  3392. // Need a small delay to prevent other code (input event,
  3393. // selection polling) from doing damage when fired right after
  3394. // compositionend.
  3395. setTimeout(function() {
  3396. if (!ours.handled)
  3397. input.applyComposition(ours);
  3398. if (input.composing == ours)
  3399. input.composing = null;
  3400. }, 50);
  3401. });
  3402. on(div, "touchstart", function() {
  3403. input.forceCompositionEnd();
  3404. });
  3405. on(div, "input", function() {
  3406. if (input.composing) return;
  3407. if (cm.isReadOnly() || !input.pollContent())
  3408. runInOp(input.cm, function() {regChange(cm);});
  3409. });
  3410. function onCopyCut(e) {
  3411. if (signalDOMEvent(cm, e)) return
  3412. if (cm.somethingSelected()) {
  3413. lastCopied = {lineWise: false, text: cm.getSelections()};
  3414. if (e.type == "cut") cm.replaceSelection("", null, "cut");
  3415. } else if (!cm.options.lineWiseCopyCut) {
  3416. return;
  3417. } else {
  3418. var ranges = copyableRanges(cm);
  3419. lastCopied = {lineWise: true, text: ranges.text};
  3420. if (e.type == "cut") {
  3421. cm.operation(function() {
  3422. cm.setSelections(ranges.ranges, 0, sel_dontScroll);
  3423. cm.replaceSelection("", null, "cut");
  3424. });
  3425. }
  3426. }
  3427. // iOS exposes the clipboard API, but seems to discard content inserted into it
  3428. if (e.clipboardData && !ios) {
  3429. e.preventDefault();
  3430. e.clipboardData.clearData();
  3431. e.clipboardData.setData("text/plain", lastCopied.text.join("\n"));
  3432. } else {
  3433. // Old-fashioned briefly-focus-a-textarea hack
  3434. var kludge = hiddenTextarea(), te = kludge.firstChild;
  3435. cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild);
  3436. te.value = lastCopied.text.join("\n");
  3437. var hadFocus = document.activeElement;
  3438. selectInput(te);
  3439. setTimeout(function() {
  3440. cm.display.lineSpace.removeChild(kludge);
  3441. hadFocus.focus();
  3442. }, 50);
  3443. }
  3444. }
  3445. on(div, "copy", onCopyCut);
  3446. on(div, "cut", onCopyCut);
  3447. },
  3448. prepareSelection: function() {
  3449. var result = prepareSelection(this.cm, false);
  3450. result.focus = this.cm.state.focused;
  3451. return result;
  3452. },
  3453. showSelection: function(info, takeFocus) {
  3454. if (!info || !this.cm.display.view.length) return;
  3455. if (info.focus || takeFocus) this.showPrimarySelection();
  3456. this.showMultipleSelections(info);
  3457. },
  3458. showPrimarySelection: function() {
  3459. var sel = window.getSelection(), prim = this.cm.doc.sel.primary();
  3460. var curAnchor = domToPos(this.cm, sel.anchorNode, sel.anchorOffset);
  3461. var curFocus = domToPos(this.cm, sel.focusNode, sel.focusOffset);
  3462. if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad &&
  3463. cmp(minPos(curAnchor, curFocus), prim.from()) == 0 &&
  3464. cmp(maxPos(curAnchor, curFocus), prim.to()) == 0)
  3465. return;
  3466. var start = posToDOM(this.cm, prim.from());
  3467. var end = posToDOM(this.cm, prim.to());
  3468. if (!start && !end) return;
  3469. var view = this.cm.display.view;
  3470. var old = sel.rangeCount && sel.getRangeAt(0);
  3471. if (!start) {
  3472. start = {node: view[0].measure.map[2], offset: 0};
  3473. } else if (!end) { // FIXME dangerously hacky
  3474. var measure = view[view.length - 1].measure;
  3475. var map = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map;
  3476. end = {node: map[map.length - 1], offset: map[map.length - 2] - map[map.length - 3]};
  3477. }
  3478. try { var rng = range(start.node, start.offset, end.offset, end.node); }
  3479. catch(e) {} // Our model of the DOM might be outdated, in which case the range we try to set can be impossible
  3480. if (rng) {
  3481. if (!gecko && this.cm.state.focused) {
  3482. sel.collapse(start.node, start.offset);
  3483. if (!rng.collapsed) sel.addRange(rng);
  3484. } else {
  3485. sel.removeAllRanges();
  3486. sel.addRange(rng);
  3487. }
  3488. if (old && sel.anchorNode == null) sel.addRange(old);
  3489. else if (gecko) this.startGracePeriod();
  3490. }
  3491. this.rememberSelection();
  3492. },
  3493. startGracePeriod: function() {
  3494. var input = this;
  3495. clearTimeout(this.gracePeriod);
  3496. this.gracePeriod = setTimeout(function() {
  3497. input.gracePeriod = false;
  3498. if (input.selectionChanged())
  3499. input.cm.operation(function() { input.cm.curOp.selectionChanged = true; });
  3500. }, 20);
  3501. },
  3502. showMultipleSelections: function(info) {
  3503. removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors);
  3504. removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection);
  3505. },
  3506. rememberSelection: function() {
  3507. var sel = window.getSelection();
  3508. this.lastAnchorNode = sel.anchorNode; this.lastAnchorOffset = sel.anchorOffset;
  3509. this.lastFocusNode = sel.focusNode; this.lastFocusOffset = sel.focusOffset;
  3510. },
  3511. selectionInEditor: function() {
  3512. var sel = window.getSelection();
  3513. if (!sel.rangeCount) return false;
  3514. var node = sel.getRangeAt(0).commonAncestorContainer;
  3515. return contains(this.div, node);
  3516. },
  3517. focus: function() {
  3518. if (this.cm.options.readOnly != "nocursor") this.div.focus();
  3519. },
  3520. blur: function() { this.div.blur(); },
  3521. getField: function() { return this.div; },
  3522. supportsTouch: function() { return true; },
  3523. receivedFocus: function() {
  3524. var input = this;
  3525. if (this.selectionInEditor())
  3526. this.pollSelection();
  3527. else
  3528. runInOp(this.cm, function() { input.cm.curOp.selectionChanged = true; });
  3529. function poll() {
  3530. if (input.cm.state.focused) {
  3531. input.pollSelection();
  3532. input.polling.set(input.cm.options.pollInterval, poll);
  3533. }
  3534. }
  3535. this.polling.set(this.cm.options.pollInterval, poll);
  3536. },
  3537. selectionChanged: function() {
  3538. var sel = window.getSelection();
  3539. return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset ||
  3540. sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset;
  3541. },
  3542. pollSelection: function() {
  3543. if (!this.composing && !this.gracePeriod && this.selectionChanged()) {
  3544. var sel = window.getSelection(), cm = this.cm;
  3545. this.rememberSelection();
  3546. var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset);
  3547. var head = domToPos(cm, sel.focusNode, sel.focusOffset);
  3548. if (anchor && head) runInOp(cm, function() {
  3549. setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll);
  3550. if (anchor.bad || head.bad) cm.curOp.selectionChanged = true;
  3551. });
  3552. }
  3553. },
  3554. pollContent: function() {
  3555. var cm = this.cm, display = cm.display, sel = cm.doc.sel.primary();
  3556. var from = sel.from(), to = sel.to();
  3557. if (from.line < display.viewFrom || to.line > display.viewTo - 1) return false;
  3558. var fromIndex;
  3559. if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) {
  3560. var fromLine = lineNo(display.view[0].line);
  3561. var fromNode = display.view[0].node;
  3562. } else {
  3563. var fromLine = lineNo(display.view[fromIndex].line);
  3564. var fromNode = display.view[fromIndex - 1].node.nextSibling;
  3565. }
  3566. var toIndex = findViewIndex(cm, to.line);
  3567. if (toIndex == display.view.length - 1) {
  3568. var toLine = display.viewTo - 1;
  3569. var toNode = display.lineDiv.lastChild;
  3570. } else {
  3571. var toLine = lineNo(display.view[toIndex + 1].line) - 1;
  3572. var toNode = display.view[toIndex + 1].node.previousSibling;
  3573. }
  3574. var newText = cm.doc.splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine));
  3575. var oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length));
  3576. while (newText.length > 1 && oldText.length > 1) {
  3577. if (lst(newText) == lst(oldText)) { newText.pop(); oldText.pop(); toLine--; }
  3578. else if (newText[0] == oldText[0]) { newText.shift(); oldText.shift(); fromLine++; }
  3579. else break;
  3580. }
  3581. var cutFront = 0, cutEnd = 0;
  3582. var newTop = newText[0], oldTop = oldText[0], maxCutFront = Math.min(newTop.length, oldTop.length);
  3583. while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront))
  3584. ++cutFront;
  3585. var newBot = lst(newText), oldBot = lst(oldText);
  3586. var maxCutEnd = Math.min(newBot.length - (newText.length == 1 ? cutFront : 0),
  3587. oldBot.length - (oldText.length == 1 ? cutFront : 0));
  3588. while (cutEnd < maxCutEnd &&
  3589. newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1))
  3590. ++cutEnd;
  3591. newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd);
  3592. newText[0] = newText[0].slice(cutFront);
  3593. var chFrom = Pos(fromLine, cutFront);
  3594. var chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0);
  3595. if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) {
  3596. replaceRange(cm.doc, newText, chFrom, chTo, "+input");
  3597. return true;
  3598. }
  3599. },
  3600. ensurePolled: function() {
  3601. this.forceCompositionEnd();
  3602. },
  3603. reset: function() {
  3604. this.forceCompositionEnd();
  3605. },
  3606. forceCompositionEnd: function() {
  3607. if (!this.composing || this.composing.handled) return;
  3608. this.applyComposition(this.composing);
  3609. this.composing.handled = true;
  3610. this.div.blur();
  3611. this.div.focus();
  3612. },
  3613. applyComposition: function(composing) {
  3614. if (this.cm.isReadOnly())
  3615. operation(this.cm, regChange)(this.cm)
  3616. else if (composing.data && composing.data != composing.startData)
  3617. operation(this.cm, applyTextInput)(this.cm, composing.data, 0, composing.sel);
  3618. },
  3619. setUneditable: function(node) {
  3620. node.contentEditable = "false"
  3621. },
  3622. onKeyPress: function(e) {
  3623. e.preventDefault();
  3624. if (!this.cm.isReadOnly())
  3625. operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0);
  3626. },
  3627. readOnlyChanged: function(val) {
  3628. this.div.contentEditable = String(val != "nocursor")
  3629. },
  3630. onContextMenu: nothing,
  3631. resetPosition: nothing,
  3632. needsContentAttribute: true
  3633. }, ContentEditableInput.prototype);
  3634. function posToDOM(cm, pos) {
  3635. var view = findViewForLine(cm, pos.line);
  3636. if (!view || view.hidden) return null;
  3637. var line = getLine(cm.doc, pos.line);
  3638. var info = mapFromLineView(view, line, pos.line);
  3639. var order = getOrder(line), side = "left";
  3640. if (order) {
  3641. var partPos = getBidiPartAt(order, pos.ch);
  3642. side = partPos % 2 ? "right" : "left";
  3643. }
  3644. var result = nodeAndOffsetInLineMap(info.map, pos.ch, side);
  3645. result.offset = result.collapse == "right" ? result.end : result.start;
  3646. return result;
  3647. }
  3648. function badPos(pos, bad) { if (bad) pos.bad = true; return pos; }
  3649. function domToPos(cm, node, offset) {
  3650. var lineNode;
  3651. if (node == cm.display.lineDiv) {
  3652. lineNode = cm.display.lineDiv.childNodes[offset];
  3653. if (!lineNode) return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true);
  3654. node = null; offset = 0;
  3655. } else {
  3656. for (lineNode = node;; lineNode = lineNode.parentNode) {
  3657. if (!lineNode || lineNode == cm.display.lineDiv) return null;
  3658. if (lineNode.parentNode && lineNode.parentNode == cm.display.lineDiv) break;
  3659. }
  3660. }
  3661. for (var i = 0; i < cm.display.view.length; i++) {
  3662. var lineView = cm.display.view[i];
  3663. if (lineView.node == lineNode)
  3664. return locateNodeInLineView(lineView, node, offset);
  3665. }
  3666. }
  3667. function locateNodeInLineView(lineView, node, offset) {
  3668. var wrapper = lineView.text.firstChild, bad = false;
  3669. if (!node || !contains(wrapper, node)) return badPos(Pos(lineNo(lineView.line), 0), true);
  3670. if (node == wrapper) {
  3671. bad = true;
  3672. node = wrapper.childNodes[offset];
  3673. offset = 0;
  3674. if (!node) {
  3675. var line = lineView.rest ? lst(lineView.rest) : lineView.line;
  3676. return badPos(Pos(lineNo(line), line.text.length), bad);
  3677. }
  3678. }
  3679. var textNode = node.nodeType == 3 ? node : null, topNode = node;
  3680. if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) {
  3681. textNode = node.firstChild;
  3682. if (offset) offset = textNode.nodeValue.length;
  3683. }
  3684. while (topNode.parentNode != wrapper) topNode = topNode.parentNode;
  3685. var measure = lineView.measure, maps = measure.maps;
  3686. function find(textNode, topNode, offset) {
  3687. for (var i = -1; i < (maps ? maps.length : 0); i++) {
  3688. var map = i < 0 ? measure.map : maps[i];
  3689. for (var j = 0; j < map.length; j += 3) {
  3690. var curNode = map[j + 2];
  3691. if (curNode == textNode || curNode == topNode) {
  3692. var line = lineNo(i < 0 ? lineView.line : lineView.rest[i]);
  3693. var ch = map[j] + offset;
  3694. if (offset < 0 || curNode != textNode) ch = map[j + (offset ? 1 : 0)];
  3695. return Pos(line, ch);
  3696. }
  3697. }
  3698. }
  3699. }
  3700. var found = find(textNode, topNode, offset);
  3701. if (found) return badPos(found, bad);
  3702. // FIXME this is all really shaky. might handle the few cases it needs to handle, but likely to cause problems
  3703. for (var after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) {
  3704. found = find(after, after.firstChild, 0);
  3705. if (found)
  3706. return badPos(Pos(found.line, found.ch - dist), bad);
  3707. else
  3708. dist += after.textContent.length;
  3709. }
  3710. for (var before = topNode.previousSibling, dist = offset; before; before = before.previousSibling) {
  3711. found = find(before, before.firstChild, -1);
  3712. if (found)
  3713. return badPos(Pos(found.line, found.ch + dist), bad);
  3714. else
  3715. dist += after.textContent.length;
  3716. }
  3717. }
  3718. function domTextBetween(cm, from, to, fromLine, toLine) {
  3719. var text = "", closing = false, lineSep = cm.doc.lineSeparator();
  3720. function recognizeMarker(id) { return function(marker) { return marker.id == id; }; }
  3721. function walk(node) {
  3722. if (node.nodeType == 1) {
  3723. var cmText = node.getAttribute("cm-text");
  3724. if (cmText != null) {
  3725. if (cmText == "") cmText = node.textContent.replace(/\u200b/g, "");
  3726. text += cmText;
  3727. return;
  3728. }
  3729. var markerID = node.getAttribute("cm-marker"), range;
  3730. if (markerID) {
  3731. var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID));
  3732. if (found.length && (range = found[0].find()))
  3733. text += getBetween(cm.doc, range.from, range.to).join(lineSep);
  3734. return;
  3735. }
  3736. if (node.getAttribute("contenteditable") == "false") return;
  3737. for (var i = 0; i < node.childNodes.length; i++)
  3738. walk(node.childNodes[i]);
  3739. if (/^(pre|div|p)$/i.test(node.nodeName))
  3740. closing = true;
  3741. } else if (node.nodeType == 3) {
  3742. var val = node.nodeValue;
  3743. if (!val) return;
  3744. if (closing) {
  3745. text += lineSep;
  3746. closing = false;
  3747. }
  3748. text += val;
  3749. }
  3750. }
  3751. for (;;) {
  3752. walk(from);
  3753. if (from == to) break;
  3754. from = from.nextSibling;
  3755. }
  3756. return text;
  3757. }
  3758. CodeMirror.inputStyles = {"textarea": TextareaInput, "contenteditable": ContentEditableInput};
  3759. // SELECTION / CURSOR
  3760. // Selection objects are immutable. A new one is created every time
  3761. // the selection changes. A selection is one or more non-overlapping
  3762. // (and non-touching) ranges, sorted, and an integer that indicates
  3763. // which one is the primary selection (the one that's scrolled into
  3764. // view, that getCursor returns, etc).
  3765. function Selection(ranges, primIndex) {
  3766. this.ranges = ranges;
  3767. this.primIndex = primIndex;
  3768. }
  3769. Selection.prototype = {
  3770. primary: function() { return this.ranges[this.primIndex]; },
  3771. equals: function(other) {
  3772. if (other == this) return true;
  3773. if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) return false;
  3774. for (var i = 0; i < this.ranges.length; i++) {
  3775. var here = this.ranges[i], there = other.ranges[i];
  3776. if (cmp(here.anchor, there.anchor) != 0 || cmp(here.head, there.head) != 0) return false;
  3777. }
  3778. return true;
  3779. },
  3780. deepCopy: function() {
  3781. for (var out = [], i = 0; i < this.ranges.length; i++)
  3782. out[i] = new Range(copyPos(this.ranges[i].anchor), copyPos(this.ranges[i].head));
  3783. return new Selection(out, this.primIndex);
  3784. },
  3785. somethingSelected: function() {
  3786. for (var i = 0; i < this.ranges.length; i++)
  3787. if (!this.ranges[i].empty()) return true;
  3788. return false;
  3789. },
  3790. contains: function(pos, end) {
  3791. if (!end) end = pos;
  3792. for (var i = 0; i < this.ranges.length; i++) {
  3793. var range = this.ranges[i];
  3794. if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0)
  3795. return i;
  3796. }
  3797. return -1;
  3798. }
  3799. };
  3800. function Range(anchor, head) {
  3801. this.anchor = anchor; this.head = head;
  3802. }
  3803. Range.prototype = {
  3804. from: function() { return minPos(this.anchor, this.head); },
  3805. to: function() { return maxPos(this.anchor, this.head); },
  3806. empty: function() {
  3807. return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch;
  3808. }
  3809. };
  3810. // Take an unsorted, potentially overlapping set of ranges, and
  3811. // build a selection out of it. 'Consumes' ranges array (modifying
  3812. // it).
  3813. function normalizeSelection(ranges, primIndex) {
  3814. var prim = ranges[primIndex];
  3815. ranges.sort(function(a, b) { return cmp(a.from(), b.from()); });
  3816. primIndex = indexOf(ranges, prim);
  3817. for (var i = 1; i < ranges.length; i++) {
  3818. var cur = ranges[i], prev = ranges[i - 1];
  3819. if (cmp(prev.to(), cur.from()) >= 0) {
  3820. var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to());
  3821. var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head;
  3822. if (i <= primIndex) --primIndex;
  3823. ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to));
  3824. }
  3825. }
  3826. return new Selection(ranges, primIndex);
  3827. }
  3828. function simpleSelection(anchor, head) {
  3829. return new Selection([new Range(anchor, head || anchor)], 0);
  3830. }
  3831. // Most of the external API clips given positions to make sure they
  3832. // actually exist within the document.
  3833. function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1));}
  3834. function clipPos(doc, pos) {
  3835. if (pos.line < doc.first) return Pos(doc.first, 0);
  3836. var last = doc.first + doc.size - 1;
  3837. if (pos.line > last) return Pos(last, getLine(doc, last).text.length);
  3838. return clipToLen(pos, getLine(doc, pos.line).text.length);
  3839. }
  3840. function clipToLen(pos, linelen) {
  3841. var ch = pos.ch;
  3842. if (ch == null || ch > linelen) return Pos(pos.line, linelen);
  3843. else if (ch < 0) return Pos(pos.line, 0);
  3844. else return pos;
  3845. }
  3846. function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size;}
  3847. function clipPosArray(doc, array) {
  3848. for (var out = [], i = 0; i < array.length; i++) out[i] = clipPos(doc, array[i]);
  3849. return out;
  3850. }
  3851. // SELECTION UPDATES
  3852. // The 'scroll' parameter given to many of these indicated whether
  3853. // the new cursor position should be scrolled into view after
  3854. // modifying the selection.
  3855. // If shift is held or the extend flag is set, extends a range to
  3856. // include a given position (and optionally a second position).
  3857. // Otherwise, simply returns the range between the given positions.
  3858. // Used for cursor motion and such.
  3859. function extendRange(doc, range, head, other) {
  3860. if (doc.cm && doc.cm.display.shift || doc.extend) {
  3861. var anchor = range.anchor;
  3862. if (other) {
  3863. var posBefore = cmp(head, anchor) < 0;
  3864. if (posBefore != (cmp(other, anchor) < 0)) {
  3865. anchor = head;
  3866. head = other;
  3867. } else if (posBefore != (cmp(head, other) < 0)) {
  3868. head = other;
  3869. }
  3870. }
  3871. return new Range(anchor, head);
  3872. } else {
  3873. return new Range(other || head, head);
  3874. }
  3875. }
  3876. // Extend the primary selection range, discard the rest.
  3877. function extendSelection(doc, head, other, options) {
  3878. setSelection(doc, new Selection([extendRange(doc, doc.sel.primary(), head, other)], 0), options);
  3879. }
  3880. // Extend all selections (pos is an array of selections with length
  3881. // equal the number of selections)
  3882. function extendSelections(doc, heads, options) {
  3883. for (var out = [], i = 0; i < doc.sel.ranges.length; i++)
  3884. out[i] = extendRange(doc, doc.sel.ranges[i], heads[i], null);
  3885. var newSel = normalizeSelection(out, doc.sel.primIndex);
  3886. setSelection(doc, newSel, options);
  3887. }
  3888. // Updates a single range in the selection.
  3889. function replaceOneSelection(doc, i, range, options) {
  3890. var ranges = doc.sel.ranges.slice(0);
  3891. ranges[i] = range;
  3892. setSelection(doc, normalizeSelection(ranges, doc.sel.primIndex), options);
  3893. }
  3894. // Reset the selection to a single range.
  3895. function setSimpleSelection(doc, anchor, head, options) {
  3896. setSelection(doc, simpleSelection(anchor, head), options);
  3897. }
  3898. // Give beforeSelectionChange handlers a change to influence a
  3899. // selection update.
  3900. function filterSelectionChange(doc, sel, options) {
  3901. var obj = {
  3902. ranges: sel.ranges,
  3903. update: function(ranges) {
  3904. this.ranges = [];
  3905. for (var i = 0; i < ranges.length; i++)
  3906. this.ranges[i] = new Range(clipPos(doc, ranges[i].anchor),
  3907. clipPos(doc, ranges[i].head));
  3908. },
  3909. origin: options && options.origin
  3910. };
  3911. signal(doc, "beforeSelectionChange", doc, obj);
  3912. if (doc.cm) signal(doc.cm, "beforeSelectionChange", doc.cm, obj);
  3913. if (obj.ranges != sel.ranges) return normalizeSelection(obj.ranges, obj.ranges.length - 1);
  3914. else return sel;
  3915. }
  3916. function setSelectionReplaceHistory(doc, sel, options) {
  3917. var done = doc.history.done, last = lst(done);
  3918. if (last && last.ranges) {
  3919. done[done.length - 1] = sel;
  3920. setSelectionNoUndo(doc, sel, options);
  3921. } else {
  3922. setSelection(doc, sel, options);
  3923. }
  3924. }
  3925. // Set a new selection.
  3926. function setSelection(doc, sel, options) {
  3927. setSelectionNoUndo(doc, sel, options);
  3928. addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options);
  3929. }
  3930. function setSelectionNoUndo(doc, sel, options) {
  3931. if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange"))
  3932. sel = filterSelectionChange(doc, sel, options);
  3933. var bias = options && options.bias ||
  3934. (cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1);
  3935. setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true));
  3936. if (!(options && options.scroll === false) && doc.cm)
  3937. ensureCursorVisible(doc.cm);
  3938. }
  3939. function setSelectionInner(doc, sel) {
  3940. if (sel.equals(doc.sel)) return;
  3941. doc.sel = sel;
  3942. if (doc.cm) {
  3943. doc.cm.curOp.updateInput = doc.cm.curOp.selectionChanged = true;
  3944. signalCursorActivity(doc.cm);
  3945. }
  3946. signalLater(doc, "cursorActivity", doc);
  3947. }
  3948. // Verify that the selection does not partially select any atomic
  3949. // marked ranges.
  3950. function reCheckSelection(doc) {
  3951. setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false), sel_dontScroll);
  3952. }
  3953. // Return a selection that does not partially select any atomic
  3954. // ranges.
  3955. function skipAtomicInSelection(doc, sel, bias, mayClear) {
  3956. var out;
  3957. for (var i = 0; i < sel.ranges.length; i++) {
  3958. var range = sel.ranges[i];
  3959. var old = sel.ranges.length == doc.sel.ranges.length && doc.sel.ranges[i];
  3960. var newAnchor = skipAtomic(doc, range.anchor, old && old.anchor, bias, mayClear);
  3961. var newHead = skipAtomic(doc, range.head, old && old.head, bias, mayClear);
  3962. if (out || newAnchor != range.anchor || newHead != range.head) {
  3963. if (!out) out = sel.ranges.slice(0, i);
  3964. out[i] = new Range(newAnchor, newHead);
  3965. }
  3966. }
  3967. return out ? normalizeSelection(out, sel.primIndex) : sel;
  3968. }
  3969. function skipAtomicInner(doc, pos, oldPos, dir, mayClear) {
  3970. var line = getLine(doc, pos.line);
  3971. if (line.markedSpans) for (var i = 0; i < line.markedSpans.length; ++i) {
  3972. var sp = line.markedSpans[i], m = sp.marker;
  3973. if ((sp.from == null || (m.inclusiveLeft ? sp.from <= pos.ch : sp.from < pos.ch)) &&
  3974. (sp.to == null || (m.inclusiveRight ? sp.to >= pos.ch : sp.to > pos.ch))) {
  3975. if (mayClear) {
  3976. signal(m, "beforeCursorEnter");
  3977. if (m.explicitlyCleared) {
  3978. if (!line.markedSpans) break;
  3979. else {--i; continue;}
  3980. }
  3981. }
  3982. if (!m.atomic) continue;
  3983. if (oldPos) {
  3984. var near = m.find(dir < 0 ? 1 : -1), diff;
  3985. if (dir < 0 ? m.inclusiveRight : m.inclusiveLeft)
  3986. near = movePos(doc, near, -dir, near && near.line == pos.line ? line : null);
  3987. if (near && near.line == pos.line && (diff = cmp(near, oldPos)) && (dir < 0 ? diff < 0 : diff > 0))
  3988. return skipAtomicInner(doc, near, pos, dir, mayClear);
  3989. }
  3990. var far = m.find(dir < 0 ? -1 : 1);
  3991. if (dir < 0 ? m.inclusiveLeft : m.inclusiveRight)
  3992. far = movePos(doc, far, dir, far.line == pos.line ? line : null);
  3993. return far ? skipAtomicInner(doc, far, pos, dir, mayClear) : null;
  3994. }
  3995. }
  3996. return pos;
  3997. }
  3998. // Ensure a given position is not inside an atomic range.
  3999. function skipAtomic(doc, pos, oldPos, bias, mayClear) {
  4000. var dir = bias || 1;
  4001. var found = skipAtomicInner(doc, pos, oldPos, dir, mayClear) ||
  4002. (!mayClear && skipAtomicInner(doc, pos, oldPos, dir, true)) ||
  4003. skipAtomicInner(doc, pos, oldPos, -dir, mayClear) ||
  4004. (!mayClear && skipAtomicInner(doc, pos, oldPos, -dir, true));
  4005. if (!found) {
  4006. doc.cantEdit = true;
  4007. return Pos(doc.first, 0);
  4008. }
  4009. return found;
  4010. }
  4011. function movePos(doc, pos, dir, line) {
  4012. if (dir < 0 && pos.ch == 0) {
  4013. if (pos.line > doc.first) return clipPos(doc, Pos(pos.line - 1));
  4014. else return null;
  4015. } else if (dir > 0 && pos.ch == (line || getLine(doc, pos.line)).text.length) {
  4016. if (pos.line < doc.first + doc.size - 1) return Pos(pos.line + 1, 0);
  4017. else return null;
  4018. } else {
  4019. return new Pos(pos.line, pos.ch + dir);
  4020. }
  4021. }
  4022. // SELECTION DRAWING
  4023. function updateSelection(cm) {
  4024. cm.display.input.showSelection(cm.display.input.prepareSelection());
  4025. }
  4026. function prepareSelection(cm, primary) {
  4027. var doc = cm.doc, result = {};
  4028. var curFragment = result.cursors = document.createDocumentFragment();
  4029. var selFragment = result.selection = document.createDocumentFragment();
  4030. for (var i = 0; i < doc.sel.ranges.length; i++) {
  4031. if (primary === false && i == doc.sel.primIndex) continue;
  4032. var range = doc.sel.ranges[i];
  4033. if (range.from().line >= cm.display.viewTo || range.to().line < cm.display.viewFrom) continue;
  4034. var collapsed = range.empty();
  4035. if (collapsed || cm.options.showCursorWhenSelecting)
  4036. drawSelectionCursor(cm, range.head, curFragment);
  4037. if (!collapsed)
  4038. drawSelectionRange(cm, range, selFragment);
  4039. }
  4040. return result;
  4041. }
  4042. // Draws a cursor for the given range
  4043. function drawSelectionCursor(cm, head, output) {
  4044. var pos = cursorCoords(cm, head, "div", null, null, !cm.options.singleCursorHeightPerLine);
  4045. var cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor"));
  4046. cursor.style.left = pos.left + "px";
  4047. cursor.style.top = pos.top + "px";
  4048. cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px";
  4049. if (pos.other) {
  4050. // Secondary cursor, shown when on a 'jump' in bi-directional text
  4051. var otherCursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor"));
  4052. otherCursor.style.display = "";
  4053. otherCursor.style.left = pos.other.left + "px";
  4054. otherCursor.style.top = pos.other.top + "px";
  4055. otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px";
  4056. }
  4057. }
  4058. // Draws the given range as a highlighted selection
  4059. function drawSelectionRange(cm, range, output) {
  4060. var display = cm.display, doc = cm.doc;
  4061. var fragment = document.createDocumentFragment();
  4062. var padding = paddingH(cm.display), leftSide = padding.left;
  4063. var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right;
  4064. function add(left, top, width, bottom) {
  4065. if (top < 0) top = 0;
  4066. top = Math.round(top);
  4067. bottom = Math.round(bottom);
  4068. fragment.appendChild(elt("div", null, "CodeMirror-selected", "position: absolute; left: " + left +
  4069. "px; top: " + top + "px; width: " + (width == null ? rightSide - left : width) +
  4070. "px; height: " + (bottom - top) + "px"));
  4071. }
  4072. function drawForLine(line, fromArg, toArg) {
  4073. var lineObj = getLine(doc, line);
  4074. var lineLen = lineObj.text.length;
  4075. var start, end;
  4076. function coords(ch, bias) {
  4077. return charCoords(cm, Pos(line, ch), "div", lineObj, bias);
  4078. }
  4079. iterateBidiSections(getOrder(lineObj), fromArg || 0, toArg == null ? lineLen : toArg, function(from, to, dir) {
  4080. var leftPos = coords(from, "left"), rightPos, left, right;
  4081. if (from == to) {
  4082. rightPos = leftPos;
  4083. left = right = leftPos.left;
  4084. } else {
  4085. rightPos = coords(to - 1, "right");
  4086. if (dir == "rtl") { var tmp = leftPos; leftPos = rightPos; rightPos = tmp; }
  4087. left = leftPos.left;
  4088. right = rightPos.right;
  4089. }
  4090. if (fromArg == null && from == 0) left = leftSide;
  4091. if (rightPos.top - leftPos.top > 3) { // Different lines, draw top part
  4092. add(left, leftPos.top, null, leftPos.bottom);
  4093. left = leftSide;
  4094. if (leftPos.bottom < rightPos.top) add(left, leftPos.bottom, null, rightPos.top);
  4095. }
  4096. if (toArg == null && to == lineLen) right = rightSide;
  4097. if (!start || leftPos.top < start.top || leftPos.top == start.top && leftPos.left < start.left)
  4098. start = leftPos;
  4099. if (!end || rightPos.bottom > end.bottom || rightPos.bottom == end.bottom && rightPos.right > end.right)
  4100. end = rightPos;
  4101. if (left < leftSide + 1) left = leftSide;
  4102. add(left, rightPos.top, right - left, rightPos.bottom);
  4103. });
  4104. return {start: start, end: end};
  4105. }
  4106. var sFrom = range.from(), sTo = range.to();
  4107. if (sFrom.line == sTo.line) {
  4108. drawForLine(sFrom.line, sFrom.ch, sTo.ch);
  4109. } else {
  4110. var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line);
  4111. var singleVLine = visualLine(fromLine) == visualLine(toLine);
  4112. var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end;
  4113. var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start;
  4114. if (singleVLine) {
  4115. if (leftEnd.top < rightStart.top - 2) {
  4116. add(leftEnd.right, leftEnd.top, null, leftEnd.bottom);
  4117. add(leftSide, rightStart.top, rightStart.left, rightStart.bottom);
  4118. } else {
  4119. add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom);
  4120. }
  4121. }
  4122. if (leftEnd.bottom < rightStart.top)
  4123. add(leftSide, leftEnd.bottom, null, rightStart.top);
  4124. }
  4125. output.appendChild(fragment);
  4126. }
  4127. // Cursor-blinking
  4128. function restartBlink(cm) {
  4129. if (!cm.state.focused) return;
  4130. var display = cm.display;
  4131. clearInterval(display.blinker);
  4132. var on = true;
  4133. display.cursorDiv.style.visibility = "";
  4134. if (cm.options.cursorBlinkRate > 0)
  4135. display.blinker = setInterval(function() {
  4136. display.cursorDiv.style.visibility = (on = !on) ? "" : "hidden";
  4137. }, cm.options.cursorBlinkRate);
  4138. else if (cm.options.cursorBlinkRate < 0)
  4139. display.cursorDiv.style.visibility = "hidden";
  4140. }
  4141. // HIGHLIGHT WORKER
  4142. function startWorker(cm, time) {
  4143. if (cm.doc.mode.startState && cm.doc.frontier < cm.display.viewTo)
  4144. cm.state.highlight.set(time, bind(highlightWorker, cm));
  4145. }
  4146. function highlightWorker(cm) {
  4147. var doc = cm.doc;
  4148. if (doc.frontier < doc.first) doc.frontier = doc.first;
  4149. if (doc.frontier >= cm.display.viewTo) return;
  4150. var end = +new Date + cm.options.workTime;
  4151. var state = copyState(doc.mode, getStateBefore(cm, doc.frontier));
  4152. var changedLines = [];
  4153. doc.iter(doc.frontier, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function(line) {
  4154. if (doc.frontier >= cm.display.viewFrom) { // Visible
  4155. var oldStyles = line.styles, tooLong = line.text.length > cm.options.maxHighlightLength;
  4156. var highlighted = highlightLine(cm, line, tooLong ? copyState(doc.mode, state) : state, true);
  4157. line.styles = highlighted.styles;
  4158. var oldCls = line.styleClasses, newCls = highlighted.classes;
  4159. if (newCls) line.styleClasses = newCls;
  4160. else if (oldCls) line.styleClasses = null;
  4161. var ischange = !oldStyles || oldStyles.length != line.styles.length ||
  4162. oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass);
  4163. for (var i = 0; !ischange && i < oldStyles.length; ++i) ischange = oldStyles[i] != line.styles[i];
  4164. if (ischange) changedLines.push(doc.frontier);
  4165. line.stateAfter = tooLong ? state : copyState(doc.mode, state);
  4166. } else {
  4167. if (line.text.length <= cm.options.maxHighlightLength)
  4168. processLine(cm, line.text, state);
  4169. line.stateAfter = doc.frontier % 5 == 0 ? copyState(doc.mode, state) : null;
  4170. }
  4171. ++doc.frontier;
  4172. if (+new Date > end) {
  4173. startWorker(cm, cm.options.workDelay);
  4174. return true;
  4175. }
  4176. });
  4177. if (changedLines.length) runInOp(cm, function() {
  4178. for (var i = 0; i < changedLines.length; i++)
  4179. regLineChange(cm, changedLines[i], "text");
  4180. });
  4181. }
  4182. // Finds the line to start with when starting a parse. Tries to
  4183. // find a line with a stateAfter, so that it can start with a
  4184. // valid state. If that fails, it returns the line with the
  4185. // smallest indentation, which tends to need the least context to
  4186. // parse correctly.
  4187. function findStartLine(cm, n, precise) {
  4188. var minindent, minline, doc = cm.doc;
  4189. var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100);
  4190. for (var search = n; search > lim; --search) {
  4191. if (search <= doc.first) return doc.first;
  4192. var line = getLine(doc, search - 1);
  4193. if (line.stateAfter && (!precise || search <= doc.frontier)) return search;
  4194. var indented = countColumn(line.text, null, cm.options.tabSize);
  4195. if (minline == null || minindent > indented) {
  4196. minline = search - 1;
  4197. minindent = indented;
  4198. }
  4199. }
  4200. return minline;
  4201. }
  4202. function getStateBefore(cm, n, precise) {
  4203. var doc = cm.doc, display = cm.display;
  4204. if (!doc.mode.startState) return true;
  4205. var pos = findStartLine(cm, n, precise), state = pos > doc.first && getLine(doc, pos-1).stateAfter;
  4206. if (!state) state = startState(doc.mode);
  4207. else state = copyState(doc.mode, state);
  4208. doc.iter(pos, n, function(line) {
  4209. processLine(cm, line.text, state);
  4210. var save = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo;
  4211. line.stateAfter = save ? copyState(doc.mode, state) : null;
  4212. ++pos;
  4213. });
  4214. if (precise) doc.frontier = pos;
  4215. return state;
  4216. }
  4217. // POSITION MEASUREMENT
  4218. function paddingTop(display) {return display.lineSpace.offsetTop;}
  4219. function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight;}
  4220. function paddingH(display) {
  4221. if (display.cachedPaddingH) return display.cachedPaddingH;
  4222. var e = removeChildrenAndAdd(display.measure, elt("pre", "x"));
  4223. var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle;
  4224. var data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)};
  4225. if (!isNaN(data.left) && !isNaN(data.right)) display.cachedPaddingH = data;
  4226. return data;
  4227. }
  4228. function scrollGap(cm) { return scrollerGap - cm.display.nativeBarWidth; }
  4229. function displayWidth(cm) {
  4230. return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth;
  4231. }
  4232. function displayHeight(cm) {
  4233. return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight;
  4234. }
  4235. // Ensure the lineView.wrapping.heights array is populated. This is
  4236. // an array of bottom offsets for the lines that make up a drawn
  4237. // line. When lineWrapping is on, there might be more than one
  4238. // height.
  4239. function ensureLineHeights(cm, lineView, rect) {
  4240. var wrapping = cm.options.lineWrapping;
  4241. var curWidth = wrapping && displayWidth(cm);
  4242. if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) {
  4243. var heights = lineView.measure.heights = [];
  4244. if (wrapping) {
  4245. lineView.measure.width = curWidth;
  4246. var rects = lineView.text.firstChild.getClientRects();
  4247. for (var i = 0; i < rects.length - 1; i++) {
  4248. var cur = rects[i], next = rects[i + 1];
  4249. if (Math.abs(cur.bottom - next.bottom) > 2)
  4250. heights.push((cur.bottom + next.top) / 2 - rect.top);
  4251. }
  4252. }
  4253. heights.push(rect.bottom - rect.top);
  4254. }
  4255. }
  4256. // Find a line map (mapping character offsets to text nodes) and a
  4257. // measurement cache for the given line number. (A line view might
  4258. // contain multiple lines when collapsed ranges are present.)
  4259. function mapFromLineView(lineView, line, lineN) {
  4260. if (lineView.line == line)
  4261. return {map: lineView.measure.map, cache: lineView.measure.cache};
  4262. for (var i = 0; i < lineView.rest.length; i++)
  4263. if (lineView.rest[i] == line)
  4264. return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i]};
  4265. for (var i = 0; i < lineView.rest.length; i++)
  4266. if (lineNo(lineView.rest[i]) > lineN)
  4267. return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i], before: true};
  4268. }
  4269. // Render a line into the hidden node display.externalMeasured. Used
  4270. // when measurement is needed for a line that's not in the viewport.
  4271. function updateExternalMeasurement(cm, line) {
  4272. line = visualLine(line);
  4273. var lineN = lineNo(line);
  4274. var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN);
  4275. view.lineN = lineN;
  4276. var built = view.built = buildLineContent(cm, view);
  4277. view.text = built.pre;
  4278. removeChildrenAndAdd(cm.display.lineMeasure, built.pre);
  4279. return view;
  4280. }
  4281. // Get a {top, bottom, left, right} box (in line-local coordinates)
  4282. // for a given character.
  4283. function measureChar(cm, line, ch, bias) {
  4284. return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias);
  4285. }
  4286. // Find a line view that corresponds to the given line number.
  4287. function findViewForLine(cm, lineN) {
  4288. if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo)
  4289. return cm.display.view[findViewIndex(cm, lineN)];
  4290. var ext = cm.display.externalMeasured;
  4291. if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size)
  4292. return ext;
  4293. }
  4294. // Measurement can be split in two steps, the set-up work that
  4295. // applies to the whole line, and the measurement of the actual
  4296. // character. Functions like coordsChar, that need to do a lot of
  4297. // measurements in a row, can thus ensure that the set-up work is
  4298. // only done once.
  4299. function prepareMeasureForLine(cm, line) {
  4300. var lineN = lineNo(line);
  4301. var view = findViewForLine(cm, lineN);
  4302. if (view && !view.text) {
  4303. view = null;
  4304. } else if (view && view.changes) {
  4305. updateLineForChanges(cm, view, lineN, getDimensions(cm));
  4306. cm.curOp.forceUpdate = true;
  4307. }
  4308. if (!view)
  4309. view = updateExternalMeasurement(cm, line);
  4310. var info = mapFromLineView(view, line, lineN);
  4311. return {
  4312. line: line, view: view, rect: null,
  4313. map: info.map, cache: info.cache, before: info.before,
  4314. hasHeights: false
  4315. };
  4316. }
  4317. // Given a prepared measurement object, measures the position of an
  4318. // actual character (or fetches it from the cache).
  4319. function measureCharPrepared(cm, prepared, ch, bias, varHeight) {
  4320. if (prepared.before) ch = -1;
  4321. var key = ch + (bias || ""), found;
  4322. if (prepared.cache.hasOwnProperty(key)) {
  4323. found = prepared.cache[key];
  4324. } else {
  4325. if (!prepared.rect)
  4326. prepared.rect = prepared.view.text.getBoundingClientRect();
  4327. if (!prepared.hasHeights) {
  4328. ensureLineHeights(cm, prepared.view, prepared.rect);
  4329. prepared.hasHeights = true;
  4330. }
  4331. found = measureCharInner(cm, prepared, ch, bias);
  4332. if (!found.bogus) prepared.cache[key] = found;
  4333. }
  4334. return {left: found.left, right: found.right,
  4335. top: varHeight ? found.rtop : found.top,
  4336. bottom: varHeight ? found.rbottom : found.bottom};
  4337. }
  4338. var nullRect = {left: 0, right: 0, top: 0, bottom: 0};
  4339. function nodeAndOffsetInLineMap(map, ch, bias) {
  4340. var node, start, end, collapse;
  4341. // First, search the line map for the text node corresponding to,
  4342. // or closest to, the target character.
  4343. for (var i = 0; i < map.length; i += 3) {
  4344. var mStart = map[i], mEnd = map[i + 1];
  4345. if (ch < mStart) {
  4346. start = 0; end = 1;
  4347. collapse = "left";
  4348. } else if (ch < mEnd) {
  4349. start = ch - mStart;
  4350. end = start + 1;
  4351. } else if (i == map.length - 3 || ch == mEnd && map[i + 3] > ch) {
  4352. end = mEnd - mStart;
  4353. start = end - 1;
  4354. if (ch >= mEnd) collapse = "right";
  4355. }
  4356. if (start != null) {
  4357. node = map[i + 2];
  4358. if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right"))
  4359. collapse = bias;
  4360. if (bias == "left" && start == 0)
  4361. while (i && map[i - 2] == map[i - 3] && map[i - 1].insertLeft) {
  4362. node = map[(i -= 3) + 2];
  4363. collapse = "left";
  4364. }
  4365. if (bias == "right" && start == mEnd - mStart)
  4366. while (i < map.length - 3 && map[i + 3] == map[i + 4] && !map[i + 5].insertLeft) {
  4367. node = map[(i += 3) + 2];
  4368. collapse = "right";
  4369. }
  4370. break;
  4371. }
  4372. }
  4373. return {node: node, start: start, end: end, collapse: collapse, coverStart: mStart, coverEnd: mEnd};
  4374. }
  4375. function measureCharInner(cm, prepared, ch, bias) {
  4376. var place = nodeAndOffsetInLineMap(prepared.map, ch, bias);
  4377. var node = place.node, start = place.start, end = place.end, collapse = place.collapse;
  4378. var rect;
  4379. if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates.
  4380. for (var i = 0; i < 4; i++) { // Retry a maximum of 4 times when nonsense rectangles are returned
  4381. while (start && isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) --start;
  4382. while (place.coverStart + end < place.coverEnd && isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) ++end;
  4383. if (ie && ie_version < 9 && start == 0 && end == place.coverEnd - place.coverStart) {
  4384. rect = node.parentNode.getBoundingClientRect();
  4385. } else if (ie && cm.options.lineWrapping) {
  4386. var rects = range(node, start, end).getClientRects();
  4387. if (rects.length)
  4388. rect = rects[bias == "right" ? rects.length - 1 : 0];
  4389. else
  4390. rect = nullRect;
  4391. } else {
  4392. rect = range(node, start, end).getBoundingClientRect() || nullRect;
  4393. }
  4394. if (rect.left || rect.right || start == 0) break;
  4395. end = start;
  4396. start = start - 1;
  4397. collapse = "right";
  4398. }
  4399. if (ie && ie_version < 11) rect = maybeUpdateRectForZooming(cm.display.measure, rect);
  4400. } else { // If it is a widget, simply get the box for the whole widget.
  4401. if (start > 0) collapse = bias = "right";
  4402. var rects;
  4403. if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1)
  4404. rect = rects[bias == "right" ? rects.length - 1 : 0];
  4405. else
  4406. rect = node.getBoundingClientRect();
  4407. }
  4408. if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) {
  4409. var rSpan = node.parentNode.getClientRects()[0];
  4410. if (rSpan)
  4411. rect = {left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom};
  4412. else
  4413. rect = nullRect;
  4414. }
  4415. var rtop = rect.top - prepared.rect.top, rbot = rect.bottom - prepared.rect.top;
  4416. var mid = (rtop + rbot) / 2;
  4417. var heights = prepared.view.measure.heights;
  4418. for (var i = 0; i < heights.length - 1; i++)
  4419. if (mid < heights[i]) break;
  4420. var top = i ? heights[i - 1] : 0, bot = heights[i];
  4421. var result = {left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left,
  4422. right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left,
  4423. top: top, bottom: bot};
  4424. if (!rect.left && !rect.right) result.bogus = true;
  4425. if (!cm.options.singleCursorHeightPerLine) { result.rtop = rtop; result.rbottom = rbot; }
  4426. return result;
  4427. }
  4428. // Work around problem with bounding client rects on ranges being
  4429. // returned incorrectly when zoomed on IE10 and below.
  4430. function maybeUpdateRectForZooming(measure, rect) {
  4431. if (!window.screen || screen.logicalXDPI == null ||
  4432. screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure))
  4433. return rect;
  4434. var scaleX = screen.logicalXDPI / screen.deviceXDPI;
  4435. var scaleY = screen.logicalYDPI / screen.deviceYDPI;
  4436. return {left: rect.left * scaleX, right: rect.right * scaleX,
  4437. top: rect.top * scaleY, bottom: rect.bottom * scaleY};
  4438. }
  4439. function clearLineMeasurementCacheFor(lineView) {
  4440. if (lineView.measure) {
  4441. lineView.measure.cache = {};
  4442. lineView.measure.heights = null;
  4443. if (lineView.rest) for (var i = 0; i < lineView.rest.length; i++)
  4444. lineView.measure.caches[i] = {};
  4445. }
  4446. }
  4447. function clearLineMeasurementCache(cm) {
  4448. cm.display.externalMeasure = null;
  4449. removeChildren(cm.display.lineMeasure);
  4450. for (var i = 0; i < cm.display.view.length; i++)
  4451. clearLineMeasurementCacheFor(cm.display.view[i]);
  4452. }
  4453. function clearCaches(cm) {
  4454. clearLineMeasurementCache(cm);
  4455. cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null;
  4456. if (!cm.options.lineWrapping) cm.display.maxLineChanged = true;
  4457. cm.display.lineNumChars = null;
  4458. }
  4459. function pageScrollX() { return window.pageXOffset || (document.documentElement || document.body).scrollLeft; }
  4460. function pageScrollY() { return window.pageYOffset || (document.documentElement || document.body).scrollTop; }
  4461. // Converts a {top, bottom, left, right} box from line-local
  4462. // coordinates into another coordinate system. Context may be one of
  4463. // "line", "div" (display.lineDiv), "local"/null (editor), "window",
  4464. // or "page".
  4465. function intoCoordSystem(cm, lineObj, rect, context) {
  4466. if (lineObj.widgets) for (var i = 0; i < lineObj.widgets.length; ++i) if (lineObj.widgets[i].above) {
  4467. var size = widgetHeight(lineObj.widgets[i]);
  4468. rect.top += size; rect.bottom += size;
  4469. }
  4470. if (context == "line") return rect;
  4471. if (!context) context = "local";
  4472. var yOff = heightAtLine(lineObj);
  4473. if (context == "local") yOff += paddingTop(cm.display);
  4474. else yOff -= cm.display.viewOffset;
  4475. if (context == "page" || context == "window") {
  4476. var lOff = cm.display.lineSpace.getBoundingClientRect();
  4477. yOff += lOff.top + (context == "window" ? 0 : pageScrollY());
  4478. var xOff = lOff.left + (context == "window" ? 0 : pageScrollX());
  4479. rect.left += xOff; rect.right += xOff;
  4480. }
  4481. rect.top += yOff; rect.bottom += yOff;
  4482. return rect;
  4483. }
  4484. // Coverts a box from "div" coords to another coordinate system.
  4485. // Context may be "window", "page", "div", or "local"/null.
  4486. function fromCoordSystem(cm, coords, context) {
  4487. if (context == "div") return coords;
  4488. var left = coords.left, top = coords.top;
  4489. // First move into "page" coordinate system
  4490. if (context == "page") {
  4491. left -= pageScrollX();
  4492. top -= pageScrollY();
  4493. } else if (context == "local" || !context) {
  4494. var localBox = cm.display.sizer.getBoundingClientRect();
  4495. left += localBox.left;
  4496. top += localBox.top;
  4497. }
  4498. var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect();
  4499. return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top};
  4500. }
  4501. function charCoords(cm, pos, context, lineObj, bias) {
  4502. if (!lineObj) lineObj = getLine(cm.doc, pos.line);
  4503. return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context);
  4504. }
  4505. // Returns a box for a given cursor position, which may have an
  4506. // 'other' property containing the position of the secondary cursor
  4507. // on a bidi boundary.
  4508. function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) {
  4509. lineObj = lineObj || getLine(cm.doc, pos.line);
  4510. if (!preparedMeasure) preparedMeasure = prepareMeasureForLine(cm, lineObj);
  4511. function get(ch, right) {
  4512. var m = measureCharPrepared(cm, preparedMeasure, ch, right ? "right" : "left", varHeight);
  4513. if (right) m.left = m.right; else m.right = m.left;
  4514. return intoCoordSystem(cm, lineObj, m, context);
  4515. }
  4516. function getBidi(ch, partPos) {
  4517. var part = order[partPos], right = part.level % 2;
  4518. if (ch == bidiLeft(part) && partPos && part.level < order[partPos - 1].level) {
  4519. part = order[--partPos];
  4520. ch = bidiRight(part) - (part.level % 2 ? 0 : 1);
  4521. right = true;
  4522. } else if (ch == bidiRight(part) && partPos < order.length - 1 && part.level < order[partPos + 1].level) {
  4523. part = order[++partPos];
  4524. ch = bidiLeft(part) - part.level % 2;
  4525. right = false;
  4526. }
  4527. if (right && ch == part.to && ch > part.from) return get(ch - 1);
  4528. return get(ch, right);
  4529. }
  4530. var order = getOrder(lineObj), ch = pos.ch;
  4531. if (!order) return get(ch);
  4532. var partPos = getBidiPartAt(order, ch);
  4533. var val = getBidi(ch, partPos);
  4534. if (bidiOther != null) val.other = getBidi(ch, bidiOther);
  4535. return val;
  4536. }
  4537. // Used to cheaply estimate the coordinates for a position. Used for
  4538. // intermediate scroll updates.
  4539. function estimateCoords(cm, pos) {
  4540. var left = 0, pos = clipPos(cm.doc, pos);
  4541. if (!cm.options.lineWrapping) left = charWidth(cm.display) * pos.ch;
  4542. var lineObj = getLine(cm.doc, pos.line);
  4543. var top = heightAtLine(lineObj) + paddingTop(cm.display);
  4544. return {left: left, right: left, top: top, bottom: top + lineObj.height};
  4545. }
  4546. // Positions returned by coordsChar contain some extra information.
  4547. // xRel is the relative x position of the input coordinates compared
  4548. // to the found position (so xRel > 0 means the coordinates are to
  4549. // the right of the character position, for example). When outside
  4550. // is true, that means the coordinates lie outside the line's
  4551. // vertical range.
  4552. function PosWithInfo(line, ch, outside, xRel) {
  4553. var pos = Pos(line, ch);
  4554. pos.xRel = xRel;
  4555. if (outside) pos.outside = true;
  4556. return pos;
  4557. }
  4558. // Compute the character position closest to the given coordinates.
  4559. // Input must be lineSpace-local ("div" coordinate system).
  4560. function coordsChar(cm, x, y) {
  4561. var doc = cm.doc;
  4562. y += cm.display.viewOffset;
  4563. if (y < 0) return PosWithInfo(doc.first, 0, true, -1);
  4564. var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1;
  4565. if (lineN > last)
  4566. return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, true, 1);
  4567. if (x < 0) x = 0;
  4568. var lineObj = getLine(doc, lineN);
  4569. for (;;) {
  4570. var found = coordsCharInner(cm, lineObj, lineN, x, y);
  4571. var merged = collapsedSpanAtEnd(lineObj);
  4572. var mergedPos = merged && merged.find(0, true);
  4573. if (merged && (found.ch > mergedPos.from.ch || found.ch == mergedPos.from.ch && found.xRel > 0))
  4574. lineN = lineNo(lineObj = mergedPos.to.line);
  4575. else
  4576. return found;
  4577. }
  4578. }
  4579. function coordsCharInner(cm, lineObj, lineNo, x, y) {
  4580. var innerOff = y - heightAtLine(lineObj);
  4581. var wrongLine = false, adjust = 2 * cm.display.wrapper.clientWidth;
  4582. var preparedMeasure = prepareMeasureForLine(cm, lineObj);
  4583. function getX(ch) {
  4584. var sp = cursorCoords(cm, Pos(lineNo, ch), "line", lineObj, preparedMeasure);
  4585. wrongLine = true;
  4586. if (innerOff > sp.bottom) return sp.left - adjust;
  4587. else if (innerOff < sp.top) return sp.left + adjust;
  4588. else wrongLine = false;
  4589. return sp.left;
  4590. }
  4591. var bidi = getOrder(lineObj), dist = lineObj.text.length;
  4592. var from = lineLeft(lineObj), to = lineRight(lineObj);
  4593. var fromX = getX(from), fromOutside = wrongLine, toX = getX(to), toOutside = wrongLine;
  4594. if (x > toX) return PosWithInfo(lineNo, to, toOutside, 1);
  4595. // Do a binary search between these bounds.
  4596. for (;;) {
  4597. if (bidi ? to == from || to == moveVisually(lineObj, from, 1) : to - from <= 1) {
  4598. var ch = x < fromX || x - fromX <= toX - x ? from : to;
  4599. var xDiff = x - (ch == from ? fromX : toX);
  4600. while (isExtendingChar(lineObj.text.charAt(ch))) ++ch;
  4601. var pos = PosWithInfo(lineNo, ch, ch == from ? fromOutside : toOutside,
  4602. xDiff < -1 ? -1 : xDiff > 1 ? 1 : 0);
  4603. return pos;
  4604. }
  4605. var step = Math.ceil(dist / 2), middle = from + step;
  4606. if (bidi) {
  4607. middle = from;
  4608. for (var i = 0; i < step; ++i) middle = moveVisually(lineObj, middle, 1);
  4609. }
  4610. var middleX = getX(middle);
  4611. if (middleX > x) {to = middle; toX = middleX; if (toOutside = wrongLine) toX += 1000; dist = step;}
  4612. else {from = middle; fromX = middleX; fromOutside = wrongLine; dist -= step;}
  4613. }
  4614. }
  4615. var measureText;
  4616. // Compute the default text height.
  4617. function textHeight(display) {
  4618. if (display.cachedTextHeight != null) return display.cachedTextHeight;
  4619. if (measureText == null) {
  4620. measureText = elt("pre");
  4621. // Measure a bunch of lines, for browsers that compute
  4622. // fractional heights.
  4623. for (var i = 0; i < 49; ++i) {
  4624. measureText.appendChild(document.createTextNode("x"));
  4625. measureText.appendChild(elt("br"));
  4626. }
  4627. measureText.appendChild(document.createTextNode("x"));
  4628. }
  4629. removeChildrenAndAdd(display.measure, measureText);
  4630. var height = measureText.offsetHeight / 50;
  4631. if (height > 3) display.cachedTextHeight = height;
  4632. removeChildren(display.measure);
  4633. return height || 1;
  4634. }
  4635. // Compute the default character width.
  4636. function charWidth(display) {
  4637. if (display.cachedCharWidth != null) return display.cachedCharWidth;
  4638. var anchor = elt("span", "xxxxxxxxxx");
  4639. var pre = elt("pre", [anchor]);
  4640. removeChildrenAndAdd(display.measure, pre);
  4641. var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10;
  4642. if (width > 2) display.cachedCharWidth = width;
  4643. return width || 10;
  4644. }
  4645. // OPERATIONS
  4646. // Operations are used to wrap a series of changes to the editor
  4647. // state in such a way that each change won't have to update the
  4648. // cursor and display (which would be awkward, slow, and
  4649. // error-prone). Instead, display updates are batched and then all
  4650. // combined and executed at once.
  4651. var operationGroup = null;
  4652. var nextOpId = 0;
  4653. // Start a new operation.
  4654. function startOperation(cm) {
  4655. cm.curOp = {
  4656. cm: cm,
  4657. viewChanged: false, // Flag that indicates that lines might need to be redrawn
  4658. startHeight: cm.doc.height, // Used to detect need to update scrollbar
  4659. forceUpdate: false, // Used to force a redraw
  4660. updateInput: null, // Whether to reset the input textarea
  4661. typing: false, // Whether this reset should be careful to leave existing text (for compositing)
  4662. changeObjs: null, // Accumulated changes, for firing change events
  4663. cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on
  4664. cursorActivityCalled: 0, // Tracks which cursorActivity handlers have been called already
  4665. selectionChanged: false, // Whether the selection needs to be redrawn
  4666. updateMaxLine: false, // Set when the widest line needs to be determined anew
  4667. scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet
  4668. scrollToPos: null, // Used to scroll to a specific position
  4669. focus: false,
  4670. id: ++nextOpId // Unique ID
  4671. };
  4672. if (operationGroup) {
  4673. operationGroup.ops.push(cm.curOp);
  4674. } else {
  4675. cm.curOp.ownsGroup = operationGroup = {
  4676. ops: [cm.curOp],
  4677. delayedCallbacks: []
  4678. };
  4679. }
  4680. }
  4681. function fireCallbacksForOps(group) {
  4682. // Calls delayed callbacks and cursorActivity handlers until no
  4683. // new ones appear
  4684. var callbacks = group.delayedCallbacks, i = 0;
  4685. do {
  4686. for (; i < callbacks.length; i++)
  4687. callbacks[i].call(null);
  4688. for (var j = 0; j < group.ops.length; j++) {
  4689. var op = group.ops[j];
  4690. if (op.cursorActivityHandlers)
  4691. while (op.cursorActivityCalled < op.cursorActivityHandlers.length)
  4692. op.cursorActivityHandlers[op.cursorActivityCalled++].call(null, op.cm);
  4693. }
  4694. } while (i < callbacks.length);
  4695. }
  4696. // Finish an operation, updating the display and signalling delayed events
  4697. function endOperation(cm) {
  4698. var op = cm.curOp, group = op.ownsGroup;
  4699. if (!group) return;
  4700. try { fireCallbacksForOps(group); }
  4701. finally {
  4702. operationGroup = null;
  4703. for (var i = 0; i < group.ops.length; i++)
  4704. group.ops[i].cm.curOp = null;
  4705. endOperations(group);
  4706. }
  4707. }
  4708. // The DOM updates done when an operation finishes are batched so
  4709. // that the minimum number of relayouts are required.
  4710. function endOperations(group) {
  4711. var ops = group.ops;
  4712. for (var i = 0; i < ops.length; i++) // Read DOM
  4713. endOperation_R1(ops[i]);
  4714. for (var i = 0; i < ops.length; i++) // Write DOM (maybe)
  4715. endOperation_W1(ops[i]);
  4716. for (var i = 0; i < ops.length; i++) // Read DOM
  4717. endOperation_R2(ops[i]);
  4718. for (var i = 0; i < ops.length; i++) // Write DOM (maybe)
  4719. endOperation_W2(ops[i]);
  4720. for (var i = 0; i < ops.length; i++) // Read DOM
  4721. endOperation_finish(ops[i]);
  4722. }
  4723. function endOperation_R1(op) {
  4724. var cm = op.cm, display = cm.display;
  4725. maybeClipScrollbars(cm);
  4726. if (op.updateMaxLine) findMaxLine(cm);
  4727. op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null ||
  4728. op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom ||
  4729. op.scrollToPos.to.line >= display.viewTo) ||
  4730. display.maxLineChanged && cm.options.lineWrapping;
  4731. op.update = op.mustUpdate &&
  4732. new DisplayUpdate(cm, op.mustUpdate && {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate);
  4733. }
  4734. function endOperation_W1(op) {
  4735. op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update);
  4736. }
  4737. function endOperation_R2(op) {
  4738. var cm = op.cm, display = cm.display;
  4739. if (op.updatedDisplay) updateHeightsInViewport(cm);
  4740. op.barMeasure = measureForScrollbars(cm);
  4741. // If the max line changed since it was last measured, measure it,
  4742. // and ensure the document's width matches it.
  4743. // updateDisplay_W2 will use these properties to do the actual resizing
  4744. if (display.maxLineChanged && !cm.options.lineWrapping) {
  4745. op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3;
  4746. cm.display.sizerWidth = op.adjustWidthTo;
  4747. op.barMeasure.scrollWidth =
  4748. Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth);
  4749. op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm));
  4750. }
  4751. if (op.updatedDisplay || op.selectionChanged)
  4752. op.preparedSelection = display.input.prepareSelection(op.focus);
  4753. }
  4754. function endOperation_W2(op) {
  4755. var cm = op.cm;
  4756. if (op.adjustWidthTo != null) {
  4757. cm.display.sizer.style.minWidth = op.adjustWidthTo + "px";
  4758. if (op.maxScrollLeft < cm.doc.scrollLeft)
  4759. setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true);
  4760. cm.display.maxLineChanged = false;
  4761. }
  4762. var takeFocus = op.focus && op.focus == activeElt() && (!document.hasFocus || document.hasFocus())
  4763. if (op.preparedSelection)
  4764. cm.display.input.showSelection(op.preparedSelection, takeFocus);
  4765. if (op.updatedDisplay || op.startHeight != cm.doc.height)
  4766. updateScrollbars(cm, op.barMeasure);
  4767. if (op.updatedDisplay)
  4768. setDocumentHeight(cm, op.barMeasure);
  4769. if (op.selectionChanged) restartBlink(cm);
  4770. if (cm.state.focused && op.updateInput)
  4771. cm.display.input.reset(op.typing);
  4772. if (takeFocus) ensureFocus(op.cm);
  4773. }
  4774. function endOperation_finish(op) {
  4775. var cm = op.cm, display = cm.display, doc = cm.doc;
  4776. if (op.updatedDisplay) postUpdateDisplay(cm, op.update);
  4777. // Abort mouse wheel delta measurement, when scrolling explicitly
  4778. if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos))
  4779. display.wheelStartX = display.wheelStartY = null;
  4780. // Propagate the scroll position to the actual DOM scroller
  4781. if (op.scrollTop != null && (display.scroller.scrollTop != op.scrollTop || op.forceScroll)) {
  4782. doc.scrollTop = Math.max(0, Math.min(display.scroller.scrollHeight - display.scroller.clientHeight, op.scrollTop));
  4783. display.scrollbars.setScrollTop(doc.scrollTop);
  4784. display.scroller.scrollTop = doc.scrollTop;
  4785. }
  4786. if (op.scrollLeft != null && (display.scroller.scrollLeft != op.scrollLeft || op.forceScroll)) {
  4787. doc.scrollLeft = Math.max(0, Math.min(display.scroller.scrollWidth - display.scroller.clientWidth, op.scrollLeft));
  4788. display.scrollbars.setScrollLeft(doc.scrollLeft);
  4789. display.scroller.scrollLeft = doc.scrollLeft;
  4790. alignHorizontally(cm);
  4791. }
  4792. // If we need to scroll a specific position into view, do so.
  4793. if (op.scrollToPos) {
  4794. var coords = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from),
  4795. clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin);
  4796. if (op.scrollToPos.isCursor && cm.state.focused) maybeScrollWindow(cm, coords);
  4797. }
  4798. // Fire events for markers that are hidden/unidden by editing or
  4799. // undoing
  4800. var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers;
  4801. if (hidden) for (var i = 0; i < hidden.length; ++i)
  4802. if (!hidden[i].lines.length) signal(hidden[i], "hide");
  4803. if (unhidden) for (var i = 0; i < unhidden.length; ++i)
  4804. if (unhidden[i].lines.length) signal(unhidden[i], "unhide");
  4805. if (display.wrapper.offsetHeight)
  4806. doc.scrollTop = cm.display.scroller.scrollTop;
  4807. // Fire change events, and delayed event handlers
  4808. if (op.changeObjs)
  4809. signal(cm, "changes", cm, op.changeObjs);
  4810. if (op.update)
  4811. op.update.finish();
  4812. }
  4813. // Run the given function in an operation
  4814. function runInOp(cm, f) {
  4815. if (cm.curOp) return f();
  4816. startOperation(cm);
  4817. try { return f(); }
  4818. finally { endOperation(cm); }
  4819. }
  4820. // Wraps a function in an operation. Returns the wrapped function.
  4821. function operation(cm, f) {
  4822. return function() {
  4823. if (cm.curOp) return f.apply(cm, arguments);
  4824. startOperation(cm);
  4825. try { return f.apply(cm, arguments); }
  4826. finally { endOperation(cm); }
  4827. };
  4828. }
  4829. // Used to add methods to editor and doc instances, wrapping them in
  4830. // operations.
  4831. function methodOp(f) {
  4832. return function() {
  4833. if (this.curOp) return f.apply(this, arguments);
  4834. startOperation(this);
  4835. try { return f.apply(this, arguments); }
  4836. finally { endOperation(this); }
  4837. };
  4838. }
  4839. function docMethodOp(f) {
  4840. return function() {
  4841. var cm = this.cm;
  4842. if (!cm || cm.curOp) return f.apply(this, arguments);
  4843. startOperation(cm);
  4844. try { return f.apply(this, arguments); }
  4845. finally { endOperation(cm); }
  4846. };
  4847. }
  4848. // VIEW TRACKING
  4849. // These objects are used to represent the visible (currently drawn)
  4850. // part of the document. A LineView may correspond to multiple
  4851. // logical lines, if those are connected by collapsed ranges.
  4852. function LineView(doc, line, lineN) {
  4853. // The starting line
  4854. this.line = line;
  4855. // Continuing lines, if any
  4856. this.rest = visualLineContinued(line);
  4857. // Number of logical lines in this visual line
  4858. this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1;
  4859. this.node = this.text = null;
  4860. this.hidden = lineIsHidden(doc, line);
  4861. }
  4862. // Create a range of LineView objects for the given lines.
  4863. function buildViewArray(cm, from, to) {
  4864. var array = [], nextPos;
  4865. for (var pos = from; pos < to; pos = nextPos) {
  4866. var view = new LineView(cm.doc, getLine(cm.doc, pos), pos);
  4867. nextPos = pos + view.size;
  4868. array.push(view);
  4869. }
  4870. return array;
  4871. }
  4872. // Updates the display.view data structure for a given change to the
  4873. // document. From and to are in pre-change coordinates. Lendiff is
  4874. // the amount of lines added or subtracted by the change. This is
  4875. // used for changes that span multiple lines, or change the way
  4876. // lines are divided into visual lines. regLineChange (below)
  4877. // registers single-line changes.
  4878. function regChange(cm, from, to, lendiff) {
  4879. if (from == null) from = cm.doc.first;
  4880. if (to == null) to = cm.doc.first + cm.doc.size;
  4881. if (!lendiff) lendiff = 0;
  4882. var display = cm.display;
  4883. if (lendiff && to < display.viewTo &&
  4884. (display.updateLineNumbers == null || display.updateLineNumbers > from))
  4885. display.updateLineNumbers = from;
  4886. cm.curOp.viewChanged = true;
  4887. if (from >= display.viewTo) { // Change after
  4888. if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo)
  4889. resetView(cm);
  4890. } else if (to <= display.viewFrom) { // Change before
  4891. if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) {
  4892. resetView(cm);
  4893. } else {
  4894. display.viewFrom += lendiff;
  4895. display.viewTo += lendiff;
  4896. }
  4897. } else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap
  4898. resetView(cm);
  4899. } else if (from <= display.viewFrom) { // Top overlap
  4900. var cut = viewCuttingPoint(cm, to, to + lendiff, 1);
  4901. if (cut) {
  4902. display.view = display.view.slice(cut.index);
  4903. display.viewFrom = cut.lineN;
  4904. display.viewTo += lendiff;
  4905. } else {
  4906. resetView(cm);
  4907. }
  4908. } else if (to >= display.viewTo) { // Bottom overlap
  4909. var cut = viewCuttingPoint(cm, from, from, -1);
  4910. if (cut) {
  4911. display.view = display.view.slice(0, cut.index);
  4912. display.viewTo = cut.lineN;
  4913. } else {
  4914. resetView(cm);
  4915. }
  4916. } else { // Gap in the middle
  4917. var cutTop = viewCuttingPoint(cm, from, from, -1);
  4918. var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1);
  4919. if (cutTop && cutBot) {
  4920. display.view = display.view.slice(0, cutTop.index)
  4921. .concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN))
  4922. .concat(display.view.slice(cutBot.index));
  4923. display.viewTo += lendiff;
  4924. } else {
  4925. resetView(cm);
  4926. }
  4927. }
  4928. var ext = display.externalMeasured;
  4929. if (ext) {
  4930. if (to < ext.lineN)
  4931. ext.lineN += lendiff;
  4932. else if (from < ext.lineN + ext.size)
  4933. display.externalMeasured = null;
  4934. }
  4935. }
  4936. // Register a change to a single line. Type must be one of "text",
  4937. // "gutter", "class", "widget"
  4938. function regLineChange(cm, line, type) {
  4939. cm.curOp.viewChanged = true;
  4940. var display = cm.display, ext = cm.display.externalMeasured;
  4941. if (ext && line >= ext.lineN && line < ext.lineN + ext.size)
  4942. display.externalMeasured = null;
  4943. if (line < display.viewFrom || line >= display.viewTo) return;
  4944. var lineView = display.view[findViewIndex(cm, line)];
  4945. if (lineView.node == null) return;
  4946. var arr = lineView.changes || (lineView.changes = []);
  4947. if (indexOf(arr, type) == -1) arr.push(type);
  4948. }
  4949. // Clear the view.
  4950. function resetView(cm) {
  4951. cm.display.viewFrom = cm.display.viewTo = cm.doc.first;
  4952. cm.display.view = [];
  4953. cm.display.viewOffset = 0;
  4954. }
  4955. // Find the view element corresponding to a given line. Return null
  4956. // when the line isn't visible.
  4957. function findViewIndex(cm, n) {
  4958. if (n >= cm.display.viewTo) return null;
  4959. n -= cm.display.viewFrom;
  4960. if (n < 0) return null;
  4961. var view = cm.display.view;
  4962. for (var i = 0; i < view.length; i++) {
  4963. n -= view[i].size;
  4964. if (n < 0) return i;
  4965. }
  4966. }
  4967. function viewCuttingPoint(cm, oldN, newN, dir) {
  4968. var index = findViewIndex(cm, oldN), diff, view = cm.display.view;
  4969. if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size)
  4970. return {index: index, lineN: newN};
  4971. for (var i = 0, n = cm.display.viewFrom; i < index; i++)
  4972. n += view[i].size;
  4973. if (n != oldN) {
  4974. if (dir > 0) {
  4975. if (index == view.length - 1) return null;
  4976. diff = (n + view[index].size) - oldN;
  4977. index++;
  4978. } else {
  4979. diff = n - oldN;
  4980. }
  4981. oldN += diff; newN += diff;
  4982. }
  4983. while (visualLineNo(cm.doc, newN) != newN) {
  4984. if (index == (dir < 0 ? 0 : view.length - 1)) return null;
  4985. newN += dir * view[index - (dir < 0 ? 1 : 0)].size;
  4986. index += dir;
  4987. }
  4988. return {index: index, lineN: newN};
  4989. }
  4990. // Force the view to cover a given range, adding empty view element
  4991. // or clipping off existing ones as needed.
  4992. function adjustView(cm, from, to) {
  4993. var display = cm.display, view = display.view;
  4994. if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) {
  4995. display.view = buildViewArray(cm, from, to);
  4996. display.viewFrom = from;
  4997. } else {
  4998. if (display.viewFrom > from)
  4999. display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view);
  5000. else if (display.viewFrom < from)
  5001. display.view = display.view.slice(findViewIndex(cm, from));
  5002. display.viewFrom = from;
  5003. if (display.viewTo < to)
  5004. display.view = display.view.concat(buildViewArray(cm, display.viewTo, to));
  5005. else if (display.viewTo > to)
  5006. display.view = display.view.slice(0, findViewIndex(cm, to));
  5007. }
  5008. display.viewTo = to;
  5009. }
  5010. // Count the number of lines in the view whose DOM representation is
  5011. // out of date (or nonexistent).
  5012. function countDirtyView(cm) {
  5013. var view = cm.display.view, dirty = 0;
  5014. for (var i = 0; i < view.length; i++) {
  5015. var lineView = view[i];
  5016. if (!lineView.hidden && (!lineView.node || lineView.changes)) ++dirty;
  5017. }
  5018. return dirty;
  5019. }
  5020. // EVENT HANDLERS
  5021. // Attach the necessary event handlers when initializing the editor
  5022. function registerEventHandlers(cm) {
  5023. var d = cm.display;
  5024. on(d.scroller, "mousedown", operation(cm, onMouseDown));
  5025. // Older IE's will not fire a second mousedown for a double click
  5026. if (ie && ie_version < 11)
  5027. on(d.scroller, "dblclick", operation(cm, function(e) {
  5028. if (signalDOMEvent(cm, e)) return;
  5029. var pos = posFromMouse(cm, e);
  5030. if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) return;
  5031. e_preventDefault(e);
  5032. var word = cm.findWordAt(pos);
  5033. extendSelection(cm.doc, word.anchor, word.head);
  5034. }));
  5035. else
  5036. on(d.scroller, "dblclick", function(e) { signalDOMEvent(cm, e) || e_preventDefault(e); });
  5037. // Some browsers fire contextmenu *after* opening the menu, at
  5038. // which point we can't mess with it anymore. Context menu is
  5039. // handled in onMouseDown for these browsers.
  5040. if (!captureRightClick) on(d.scroller, "contextmenu", function(e) {onContextMenu(cm, e);});
  5041. // Used to suppress mouse event handling when a touch happens
  5042. var touchFinished, prevTouch = {end: 0};
  5043. function finishTouch() {
  5044. if (d.activeTouch) {
  5045. touchFinished = setTimeout(function() {d.activeTouch = null;}, 1000);
  5046. prevTouch = d.activeTouch;
  5047. prevTouch.end = +new Date;
  5048. }
  5049. };
  5050. function isMouseLikeTouchEvent(e) {
  5051. if (e.touches.length != 1) return false;
  5052. var touch = e.touches[0];
  5053. return touch.radiusX <= 1 && touch.radiusY <= 1;
  5054. }
  5055. function farAway(touch, other) {
  5056. if (other.left == null) return true;
  5057. var dx = other.left - touch.left, dy = other.top - touch.top;
  5058. return dx * dx + dy * dy > 20 * 20;
  5059. }
  5060. on(d.scroller, "touchstart", function(e) {
  5061. if (!signalDOMEvent(cm, e) && !isMouseLikeTouchEvent(e)) {
  5062. clearTimeout(touchFinished);
  5063. var now = +new Date;
  5064. d.activeTouch = {start: now, moved: false,
  5065. prev: now - prevTouch.end <= 300 ? prevTouch : null};
  5066. if (e.touches.length == 1) {
  5067. d.activeTouch.left = e.touches[0].pageX;
  5068. d.activeTouch.top = e.touches[0].pageY;
  5069. }
  5070. }
  5071. });
  5072. on(d.scroller, "touchmove", function() {
  5073. if (d.activeTouch) d.activeTouch.moved = true;
  5074. });
  5075. on(d.scroller, "touchend", function(e) {
  5076. var touch = d.activeTouch;
  5077. if (touch && !eventInWidget(d, e) && touch.left != null &&
  5078. !touch.moved && new Date - touch.start < 300) {
  5079. var pos = cm.coordsChar(d.activeTouch, "page"), range;
  5080. if (!touch.prev || farAway(touch, touch.prev)) // Single tap
  5081. range = new Range(pos, pos);
  5082. else if (!touch.prev.prev || farAway(touch, touch.prev.prev)) // Double tap
  5083. range = cm.findWordAt(pos);
  5084. else // Triple tap
  5085. range = new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0)));
  5086. cm.setSelection(range.anchor, range.head);
  5087. cm.focus();
  5088. e_preventDefault(e);
  5089. }
  5090. finishTouch();
  5091. });
  5092. on(d.scroller, "touchcancel", finishTouch);
  5093. // Sync scrolling between fake scrollbars and real scrollable
  5094. // area, ensure viewport is updated when scrolling.
  5095. on(d.scroller, "scroll", function() {
  5096. if (d.scroller.clientHeight) {
  5097. setScrollTop(cm, d.scroller.scrollTop);
  5098. setScrollLeft(cm, d.scroller.scrollLeft, true);
  5099. signal(cm, "scroll", cm);
  5100. }
  5101. });
  5102. // Listen to wheel events in order to try and update the viewport on time.
  5103. on(d.scroller, "mousewheel", function(e){onScrollWheel(cm, e);});
  5104. on(d.scroller, "DOMMouseScroll", function(e){onScrollWheel(cm, e);});
  5105. // Prevent wrapper from ever scrolling
  5106. on(d.wrapper, "scroll", function() { d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; });
  5107. d.dragFunctions = {
  5108. enter: function(e) {if (!signalDOMEvent(cm, e)) e_stop(e);},
  5109. over: function(e) {if (!signalDOMEvent(cm, e)) { onDragOver(cm, e); e_stop(e); }},
  5110. start: function(e){onDragStart(cm, e);},
  5111. drop: operation(cm, onDrop),
  5112. leave: function(e) {if (!signalDOMEvent(cm, e)) { clearDragCursor(cm); }}
  5113. };
  5114. var inp = d.input.getField();
  5115. on(inp, "keyup", function(e) { onKeyUp.call(cm, e); });
  5116. on(inp, "keydown", operation(cm, onKeyDown));
  5117. on(inp, "keypress", operation(cm, onKeyPress));
  5118. on(inp, "focus", bind(onFocus, cm));
  5119. on(inp, "blur", bind(onBlur, cm));
  5120. }
  5121. function dragDropChanged(cm, value, old) {
  5122. var wasOn = old && old != CodeMirror.Init;
  5123. if (!value != !wasOn) {
  5124. var funcs = cm.display.dragFunctions;
  5125. var toggle = value ? on : off;
  5126. toggle(cm.display.scroller, "dragstart", funcs.start);
  5127. toggle(cm.display.scroller, "dragenter", funcs.enter);
  5128. toggle(cm.display.scroller, "dragover", funcs.over);
  5129. toggle(cm.display.scroller, "dragleave", funcs.leave);
  5130. toggle(cm.display.scroller, "drop", funcs.drop);
  5131. }
  5132. }
  5133. // Called when the window resizes
  5134. function onResize(cm) {
  5135. var d = cm.display;
  5136. if (d.lastWrapHeight == d.wrapper.clientHeight && d.lastWrapWidth == d.wrapper.clientWidth)
  5137. return;
  5138. // Might be a text scaling operation, clear size caches.
  5139. d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
  5140. d.scrollbarsClipped = false;
  5141. cm.setSize();
  5142. }
  5143. // MOUSE EVENTS
  5144. // Return true when the given mouse event happened in a widget
  5145. function eventInWidget(display, e) {
  5146. for (var n = e_target(e); n != display.wrapper; n = n.parentNode) {
  5147. if (!n || (n.nodeType == 1 && n.getAttribute("cm-ignore-events") == "true") ||
  5148. (n.parentNode == display.sizer && n != display.mover))
  5149. return true;
  5150. }
  5151. }
  5152. // Given a mouse event, find the corresponding position. If liberal
  5153. // is false, it checks whether a gutter or scrollbar was clicked,
  5154. // and returns null if it was. forRect is used by rectangular
  5155. // selections, and tries to estimate a character position even for
  5156. // coordinates beyond the right of the text.
  5157. function posFromMouse(cm, e, liberal, forRect) {
  5158. var display = cm.display;
  5159. if (!liberal && e_target(e).getAttribute("cm-not-content") == "true") return null;
  5160. var x, y, space = display.lineSpace.getBoundingClientRect();
  5161. // Fails unpredictably on IE[67] when mouse is dragged around quickly.
  5162. try { x = e.clientX - space.left; y = e.clientY - space.top; }
  5163. catch (e) { return null; }
  5164. var coords = coordsChar(cm, x, y), line;
  5165. if (forRect && coords.xRel == 1 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) {
  5166. var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length;
  5167. coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff));
  5168. }
  5169. return coords;
  5170. }
  5171. // A mouse down can be a single click, double click, triple click,
  5172. // start of selection drag, start of text drag, new cursor
  5173. // (ctrl-click), rectangle drag (alt-drag), or xwin
  5174. // middle-click-paste. Or it might be a click on something we should
  5175. // not interfere with, such as a scrollbar or widget.
  5176. function onMouseDown(e) {
  5177. var cm = this, display = cm.display;
  5178. if (signalDOMEvent(cm, e) || display.activeTouch && display.input.supportsTouch()) return;
  5179. display.shift = e.shiftKey;
  5180. if (eventInWidget(display, e)) {
  5181. if (!webkit) {
  5182. // Briefly turn off draggability, to allow widgets to do
  5183. // normal dragging things.
  5184. display.scroller.draggable = false;
  5185. setTimeout(function(){display.scroller.draggable = true;}, 100);
  5186. }
  5187. return;
  5188. }
  5189. if (clickInGutter(cm, e)) return;
  5190. var start = posFromMouse(cm, e);
  5191. window.focus();
  5192. switch (e_button(e)) {
  5193. case 1:
  5194. // #3261: make sure, that we're not starting a second selection
  5195. if (cm.state.selectingText)
  5196. cm.state.selectingText(e);
  5197. else if (start)
  5198. leftButtonDown(cm, e, start);
  5199. else if (e_target(e) == display.scroller)
  5200. e_preventDefault(e);
  5201. break;
  5202. case 2:
  5203. if (webkit) cm.state.lastMiddleDown = +new Date;
  5204. if (start) extendSelection(cm.doc, start);
  5205. setTimeout(function() {display.input.focus();}, 20);
  5206. e_preventDefault(e);
  5207. break;
  5208. case 3:
  5209. if (captureRightClick) onContextMenu(cm, e);
  5210. else delayBlurEvent(cm);
  5211. break;
  5212. }
  5213. }
  5214. var lastClick, lastDoubleClick;
  5215. function leftButtonDown(cm, e, start) {
  5216. if (ie) setTimeout(bind(ensureFocus, cm), 0);
  5217. else cm.curOp.focus = activeElt();
  5218. var now = +new Date, type;
  5219. if (lastDoubleClick && lastDoubleClick.time > now - 400 && cmp(lastDoubleClick.pos, start) == 0) {
  5220. type = "triple";
  5221. } else if (lastClick && lastClick.time > now - 400 && cmp(lastClick.pos, start) == 0) {
  5222. type = "double";
  5223. lastDoubleClick = {time: now, pos: start};
  5224. } else {
  5225. type = "single";
  5226. lastClick = {time: now, pos: start};
  5227. }
  5228. var sel = cm.doc.sel, modifier = mac ? e.metaKey : e.ctrlKey, contained;
  5229. if (cm.options.dragDrop && dragAndDrop && !cm.isReadOnly() &&
  5230. type == "single" && (contained = sel.contains(start)) > -1 &&
  5231. (cmp((contained = sel.ranges[contained]).from(), start) < 0 || start.xRel > 0) &&
  5232. (cmp(contained.to(), start) > 0 || start.xRel < 0))
  5233. leftButtonStartDrag(cm, e, start, modifier);
  5234. else
  5235. leftButtonSelect(cm, e, start, type, modifier);
  5236. }
  5237. // Start a text drag. When it ends, see if any dragging actually
  5238. // happen, and treat as a click if it didn't.
  5239. function leftButtonStartDrag(cm, e, start, modifier) {
  5240. var display = cm.display, startTime = +new Date;
  5241. var dragEnd = operation(cm, function(e2) {
  5242. if (webkit) display.scroller.draggable = false;
  5243. cm.state.draggingText = false;
  5244. off(document, "mouseup", dragEnd);
  5245. off(display.scroller, "drop", dragEnd);
  5246. if (Math.abs(e.clientX - e2.clientX) + Math.abs(e.clientY - e2.clientY) < 10) {
  5247. e_preventDefault(e2);
  5248. if (!modifier && +new Date - 200 < startTime)
  5249. extendSelection(cm.doc, start);
  5250. // Work around unexplainable focus problem in IE9 (#2127) and Chrome (#3081)
  5251. if (webkit || ie && ie_version == 9)
  5252. setTimeout(function() {document.body.focus(); display.input.focus();}, 20);
  5253. else
  5254. display.input.focus();
  5255. }
  5256. });
  5257. // Let the drag handler handle this.
  5258. if (webkit) display.scroller.draggable = true;
  5259. cm.state.draggingText = dragEnd;
  5260. // IE's approach to draggable
  5261. if (display.scroller.dragDrop) display.scroller.dragDrop();
  5262. on(document, "mouseup", dragEnd);
  5263. on(display.scroller, "drop", dragEnd);
  5264. }
  5265. // Normal selection, as opposed to text dragging.
  5266. function leftButtonSelect(cm, e, start, type, addNew) {
  5267. var display = cm.display, doc = cm.doc;
  5268. e_preventDefault(e);
  5269. var ourRange, ourIndex, startSel = doc.sel, ranges = startSel.ranges;
  5270. if (addNew && !e.shiftKey) {
  5271. ourIndex = doc.sel.contains(start);
  5272. if (ourIndex > -1)
  5273. ourRange = ranges[ourIndex];
  5274. else
  5275. ourRange = new Range(start, start);
  5276. } else {
  5277. ourRange = doc.sel.primary();
  5278. ourIndex = doc.sel.primIndex;
  5279. }
  5280. if (chromeOS ? e.shiftKey && e.metaKey : e.altKey) {
  5281. type = "rect";
  5282. if (!addNew) ourRange = new Range(start, start);
  5283. start = posFromMouse(cm, e, true, true);
  5284. ourIndex = -1;
  5285. } else if (type == "double") {
  5286. var word = cm.findWordAt(start);
  5287. if (cm.display.shift || doc.extend)
  5288. ourRange = extendRange(doc, ourRange, word.anchor, word.head);
  5289. else
  5290. ourRange = word;
  5291. } else if (type == "triple") {
  5292. var line = new Range(Pos(start.line, 0), clipPos(doc, Pos(start.line + 1, 0)));
  5293. if (cm.display.shift || doc.extend)
  5294. ourRange = extendRange(doc, ourRange, line.anchor, line.head);
  5295. else
  5296. ourRange = line;
  5297. } else {
  5298. ourRange = extendRange(doc, ourRange, start);
  5299. }
  5300. if (!addNew) {
  5301. ourIndex = 0;
  5302. setSelection(doc, new Selection([ourRange], 0), sel_mouse);
  5303. startSel = doc.sel;
  5304. } else if (ourIndex == -1) {
  5305. ourIndex = ranges.length;
  5306. setSelection(doc, normalizeSelection(ranges.concat([ourRange]), ourIndex),
  5307. {scroll: false, origin: "*mouse"});
  5308. } else if (ranges.length > 1 && ranges[ourIndex].empty() && type == "single" && !e.shiftKey) {
  5309. setSelection(doc, normalizeSelection(ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0),
  5310. {scroll: false, origin: "*mouse"});
  5311. startSel = doc.sel;
  5312. } else {
  5313. replaceOneSelection(doc, ourIndex, ourRange, sel_mouse);
  5314. }
  5315. var lastPos = start;
  5316. function extendTo(pos) {
  5317. if (cmp(lastPos, pos) == 0) return;
  5318. lastPos = pos;
  5319. if (type == "rect") {
  5320. var ranges = [], tabSize = cm.options.tabSize;
  5321. var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize);
  5322. var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize);
  5323. var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol);
  5324. for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line));
  5325. line <= end; line++) {
  5326. var text = getLine(doc, line).text, leftPos = findColumn(text, left, tabSize);
  5327. if (left == right)
  5328. ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos)));
  5329. else if (text.length > leftPos)
  5330. ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize))));
  5331. }
  5332. if (!ranges.length) ranges.push(new Range(start, start));
  5333. setSelection(doc, normalizeSelection(startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex),
  5334. {origin: "*mouse", scroll: false});
  5335. cm.scrollIntoView(pos);
  5336. } else {
  5337. var oldRange = ourRange;
  5338. var anchor = oldRange.anchor, head = pos;
  5339. if (type != "single") {
  5340. if (type == "double")
  5341. var range = cm.findWordAt(pos);
  5342. else
  5343. var range = new Range(Pos(pos.line, 0), clipPos(doc, Pos(pos.line + 1, 0)));
  5344. if (cmp(range.anchor, anchor) > 0) {
  5345. head = range.head;
  5346. anchor = minPos(oldRange.from(), range.anchor);
  5347. } else {
  5348. head = range.anchor;
  5349. anchor = maxPos(oldRange.to(), range.head);
  5350. }
  5351. }
  5352. var ranges = startSel.ranges.slice(0);
  5353. ranges[ourIndex] = new Range(clipPos(doc, anchor), head);
  5354. setSelection(doc, normalizeSelection(ranges, ourIndex), sel_mouse);
  5355. }
  5356. }
  5357. var editorSize = display.wrapper.getBoundingClientRect();
  5358. // Used to ensure timeout re-tries don't fire when another extend
  5359. // happened in the meantime (clearTimeout isn't reliable -- at
  5360. // least on Chrome, the timeouts still happen even when cleared,
  5361. // if the clear happens after their scheduled firing time).
  5362. var counter = 0;
  5363. function extend(e) {
  5364. var curCount = ++counter;
  5365. var cur = posFromMouse(cm, e, true, type == "rect");
  5366. if (!cur) return;
  5367. if (cmp(cur, lastPos) != 0) {
  5368. cm.curOp.focus = activeElt();
  5369. extendTo(cur);
  5370. var visible = visibleLines(display, doc);
  5371. if (cur.line >= visible.to || cur.line < visible.from)
  5372. setTimeout(operation(cm, function(){if (counter == curCount) extend(e);}), 150);
  5373. } else {
  5374. var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0;
  5375. if (outside) setTimeout(operation(cm, function() {
  5376. if (counter != curCount) return;
  5377. display.scroller.scrollTop += outside;
  5378. extend(e);
  5379. }), 50);
  5380. }
  5381. }
  5382. function done(e) {
  5383. cm.state.selectingText = false;
  5384. counter = Infinity;
  5385. e_preventDefault(e);
  5386. display.input.focus();
  5387. off(document, "mousemove", move);
  5388. off(document, "mouseup", up);
  5389. doc.history.lastSelOrigin = null;
  5390. }
  5391. var move = operation(cm, function(e) {
  5392. if (!e_button(e)) done(e);
  5393. else extend(e);
  5394. });
  5395. var up = operation(cm, done);
  5396. cm.state.selectingText = up;
  5397. on(document, "mousemove", move);
  5398. on(document, "mouseup", up);
  5399. }
  5400. // Determines whether an event happened in the gutter, and fires the
  5401. // handlers for the corresponding event.
  5402. function gutterEvent(cm, e, type, prevent) {
  5403. try { var mX = e.clientX, mY = e.clientY; }
  5404. catch(e) { return false; }
  5405. if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) return false;
  5406. if (prevent) e_preventDefault(e);
  5407. var display = cm.display;
  5408. var lineBox = display.lineDiv.getBoundingClientRect();
  5409. if (mY > lineBox.bottom || !hasHandler(cm, type)) return e_defaultPrevented(e);
  5410. mY -= lineBox.top - display.viewOffset;
  5411. for (var i = 0; i < cm.options.gutters.length; ++i) {
  5412. var g = display.gutters.childNodes[i];
  5413. if (g && g.getBoundingClientRect().right >= mX) {
  5414. var line = lineAtHeight(cm.doc, mY);
  5415. var gutter = cm.options.gutters[i];
  5416. signal(cm, type, cm, line, gutter, e);
  5417. return e_defaultPrevented(e);
  5418. }
  5419. }
  5420. }
  5421. function clickInGutter(cm, e) {
  5422. return gutterEvent(cm, e, "gutterClick", true);
  5423. }
  5424. // Kludge to work around strange IE behavior where it'll sometimes
  5425. // re-fire a series of drag-related events right after the drop (#1551)
  5426. var lastDrop = 0;
  5427. function onDrop(e) {
  5428. var cm = this;
  5429. clearDragCursor(cm);
  5430. if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e))
  5431. return;
  5432. e_preventDefault(e);
  5433. if (ie) lastDrop = +new Date;
  5434. var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files;
  5435. if (!pos || cm.isReadOnly()) return;
  5436. // Might be a file drop, in which case we simply extract the text
  5437. // and insert it.
  5438. if (files && files.length && window.FileReader && window.File) {
  5439. var n = files.length, text = Array(n), read = 0;
  5440. var loadFile = function(file, i) {
  5441. if (cm.options.allowDropFileTypes &&
  5442. indexOf(cm.options.allowDropFileTypes, file.type) == -1)
  5443. return;
  5444. var reader = new FileReader;
  5445. reader.onload = operation(cm, function() {
  5446. var content = reader.result;
  5447. if (/[\x00-\x08\x0e-\x1f]{2}/.test(content)) content = "";
  5448. text[i] = content;
  5449. if (++read == n) {
  5450. pos = clipPos(cm.doc, pos);
  5451. var change = {from: pos, to: pos,
  5452. text: cm.doc.splitLines(text.join(cm.doc.lineSeparator())),
  5453. origin: "paste"};
  5454. makeChange(cm.doc, change);
  5455. setSelectionReplaceHistory(cm.doc, simpleSelection(pos, changeEnd(change)));
  5456. }
  5457. });
  5458. reader.readAsText(file);
  5459. };
  5460. for (var i = 0; i < n; ++i) loadFile(files[i], i);
  5461. } else { // Normal drop
  5462. // Don't do a replace if the drop happened inside of the selected text.
  5463. if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) {
  5464. cm.state.draggingText(e);
  5465. // Ensure the editor is re-focused
  5466. setTimeout(function() {cm.display.input.focus();}, 20);
  5467. return;
  5468. }
  5469. try {
  5470. var text = e.dataTransfer.getData("Text");
  5471. if (text) {
  5472. if (cm.state.draggingText && !(mac ? e.altKey : e.ctrlKey))
  5473. var selected = cm.listSelections();
  5474. setSelectionNoUndo(cm.doc, simpleSelection(pos, pos));
  5475. if (selected) for (var i = 0; i < selected.length; ++i)
  5476. replaceRange(cm.doc, "", selected[i].anchor, selected[i].head, "drag");
  5477. cm.replaceSelection(text, "around", "paste");
  5478. cm.display.input.focus();
  5479. }
  5480. }
  5481. catch(e){}
  5482. }
  5483. }
  5484. function onDragStart(cm, e) {
  5485. if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return; }
  5486. if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) return;
  5487. e.dataTransfer.setData("Text", cm.getSelection());
  5488. e.dataTransfer.effectAllowed = "copyMove"
  5489. // Use dummy image instead of default browsers image.
  5490. // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there.
  5491. if (e.dataTransfer.setDragImage && !safari) {
  5492. var img = elt("img", null, null, "position: fixed; left: 0; top: 0;");
  5493. img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";
  5494. if (presto) {
  5495. img.width = img.height = 1;
  5496. cm.display.wrapper.appendChild(img);
  5497. // Force a relayout, or Opera won't use our image for some obscure reason
  5498. img._top = img.offsetTop;
  5499. }
  5500. e.dataTransfer.setDragImage(img, 0, 0);
  5501. if (presto) img.parentNode.removeChild(img);
  5502. }
  5503. }
  5504. function onDragOver(cm, e) {
  5505. var pos = posFromMouse(cm, e);
  5506. if (!pos) return;
  5507. var frag = document.createDocumentFragment();
  5508. drawSelectionCursor(cm, pos, frag);
  5509. if (!cm.display.dragCursor) {
  5510. cm.display.dragCursor = elt("div", null, "CodeMirror-cursors CodeMirror-dragcursors");
  5511. cm.display.lineSpace.insertBefore(cm.display.dragCursor, cm.display.cursorDiv);
  5512. }
  5513. removeChildrenAndAdd(cm.display.dragCursor, frag);
  5514. }
  5515. function clearDragCursor(cm) {
  5516. if (cm.display.dragCursor) {
  5517. cm.display.lineSpace.removeChild(cm.display.dragCursor);
  5518. cm.display.dragCursor = null;
  5519. }
  5520. }
  5521. // SCROLL EVENTS
  5522. // Sync the scrollable area and scrollbars, ensure the viewport
  5523. // covers the visible area.
  5524. function setScrollTop(cm, val) {
  5525. if (Math.abs(cm.doc.scrollTop - val) < 2) return;
  5526. cm.doc.scrollTop = val;
  5527. if (!gecko) updateDisplaySimple(cm, {top: val});
  5528. if (cm.display.scroller.scrollTop != val) cm.display.scroller.scrollTop = val;
  5529. cm.display.scrollbars.setScrollTop(val);
  5530. if (gecko) updateDisplaySimple(cm);
  5531. startWorker(cm, 100);
  5532. }
  5533. // Sync scroller and scrollbar, ensure the gutter elements are
  5534. // aligned.
  5535. function setScrollLeft(cm, val, isScroller) {
  5536. if (isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) return;
  5537. val = Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth);
  5538. cm.doc.scrollLeft = val;
  5539. alignHorizontally(cm);
  5540. if (cm.display.scroller.scrollLeft != val) cm.display.scroller.scrollLeft = val;
  5541. cm.display.scrollbars.setScrollLeft(val);
  5542. }
  5543. // Since the delta values reported on mouse wheel events are
  5544. // unstandardized between browsers and even browser versions, and
  5545. // generally horribly unpredictable, this code starts by measuring
  5546. // the scroll effect that the first few mouse wheel events have,
  5547. // and, from that, detects the way it can convert deltas to pixel
  5548. // offsets afterwards.
  5549. //
  5550. // The reason we want to know the amount a wheel event will scroll
  5551. // is that it gives us a chance to update the display before the
  5552. // actual scrolling happens, reducing flickering.
  5553. var wheelSamples = 0, wheelPixelsPerUnit = null;
  5554. // Fill in a browser-detected starting value on browsers where we
  5555. // know one. These don't have to be accurate -- the result of them
  5556. // being wrong would just be a slight flicker on the first wheel
  5557. // scroll (if it is large enough).
  5558. if (ie) wheelPixelsPerUnit = -.53;
  5559. else if (gecko) wheelPixelsPerUnit = 15;
  5560. else if (chrome) wheelPixelsPerUnit = -.7;
  5561. else if (safari) wheelPixelsPerUnit = -1/3;
  5562. var wheelEventDelta = function(e) {
  5563. var dx = e.wheelDeltaX, dy = e.wheelDeltaY;
  5564. if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) dx = e.detail;
  5565. if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) dy = e.detail;
  5566. else if (dy == null) dy = e.wheelDelta;
  5567. return {x: dx, y: dy};
  5568. };
  5569. CodeMirror.wheelEventPixels = function(e) {
  5570. var delta = wheelEventDelta(e);
  5571. delta.x *= wheelPixelsPerUnit;
  5572. delta.y *= wheelPixelsPerUnit;
  5573. return delta;
  5574. };
  5575. function onScrollWheel(cm, e) {
  5576. var delta = wheelEventDelta(e), dx = delta.x, dy = delta.y;
  5577. var display = cm.display, scroll = display.scroller;
  5578. // Quit if there's nothing to scroll here
  5579. var canScrollX = scroll.scrollWidth > scroll.clientWidth;
  5580. var canScrollY = scroll.scrollHeight > scroll.clientHeight;
  5581. if (!(dx && canScrollX || dy && canScrollY)) return;
  5582. // Webkit browsers on OS X abort momentum scrolls when the target
  5583. // of the scroll event is removed from the scrollable element.
  5584. // This hack (see related code in patchDisplay) makes sure the
  5585. // element is kept around.
  5586. if (dy && mac && webkit) {
  5587. outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) {
  5588. for (var i = 0; i < view.length; i++) {
  5589. if (view[i].node == cur) {
  5590. cm.display.currentWheelTarget = cur;
  5591. break outer;
  5592. }
  5593. }
  5594. }
  5595. }
  5596. // On some browsers, horizontal scrolling will cause redraws to
  5597. // happen before the gutter has been realigned, causing it to
  5598. // wriggle around in a most unseemly way. When we have an
  5599. // estimated pixels/delta value, we just handle horizontal
  5600. // scrolling entirely here. It'll be slightly off from native, but
  5601. // better than glitching out.
  5602. if (dx && !gecko && !presto && wheelPixelsPerUnit != null) {
  5603. if (dy && canScrollY)
  5604. setScrollTop(cm, Math.max(0, Math.min(scroll.scrollTop + dy * wheelPixelsPerUnit, scroll.scrollHeight - scroll.clientHeight)));
  5605. setScrollLeft(cm, Math.max(0, Math.min(scroll.scrollLeft + dx * wheelPixelsPerUnit, scroll.scrollWidth - scroll.clientWidth)));
  5606. // Only prevent default scrolling if vertical scrolling is
  5607. // actually possible. Otherwise, it causes vertical scroll
  5608. // jitter on OSX trackpads when deltaX is small and deltaY
  5609. // is large (issue #3579)
  5610. if (!dy || (dy && canScrollY))
  5611. e_preventDefault(e);
  5612. display.wheelStartX = null; // Abort measurement, if in progress
  5613. return;
  5614. }
  5615. // 'Project' the visible viewport to cover the area that is being
  5616. // scrolled into view (if we know enough to estimate it).
  5617. if (dy && wheelPixelsPerUnit != null) {
  5618. var pixels = dy * wheelPixelsPerUnit;
  5619. var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight;
  5620. if (pixels < 0) top = Math.max(0, top + pixels - 50);
  5621. else bot = Math.min(cm.doc.height, bot + pixels + 50);
  5622. updateDisplaySimple(cm, {top: top, bottom: bot});
  5623. }
  5624. if (wheelSamples < 20) {
  5625. if (display.wheelStartX == null) {
  5626. display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop;
  5627. display.wheelDX = dx; display.wheelDY = dy;
  5628. setTimeout(function() {
  5629. if (display.wheelStartX == null) return;
  5630. var movedX = scroll.scrollLeft - display.wheelStartX;
  5631. var movedY = scroll.scrollTop - display.wheelStartY;
  5632. var sample = (movedY && display.wheelDY && movedY / display.wheelDY) ||
  5633. (movedX && display.wheelDX && movedX / display.wheelDX);
  5634. display.wheelStartX = display.wheelStartY = null;
  5635. if (!sample) return;
  5636. wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1);
  5637. ++wheelSamples;
  5638. }, 200);
  5639. } else {
  5640. display.wheelDX += dx; display.wheelDY += dy;
  5641. }
  5642. }
  5643. }
  5644. // KEY EVENTS
  5645. // Run a handler that was bound to a key.
  5646. function doHandleBinding(cm, bound, dropShift) {
  5647. if (typeof bound == "string") {
  5648. bound = commands[bound];
  5649. if (!bound) return false;
  5650. }
  5651. // Ensure previous input has been read, so that the handler sees a
  5652. // consistent view of the document
  5653. cm.display.input.ensurePolled();
  5654. var prevShift = cm.display.shift, done = false;
  5655. try {
  5656. if (cm.isReadOnly()) cm.state.suppressEdits = true;
  5657. if (dropShift) cm.display.shift = false;
  5658. done = bound(cm) != Pass;
  5659. } finally {
  5660. cm.display.shift = prevShift;
  5661. cm.state.suppressEdits = false;
  5662. }
  5663. return done;
  5664. }
  5665. function lookupKeyForEditor(cm, name, handle) {
  5666. for (var i = 0; i < cm.state.keyMaps.length; i++) {
  5667. var result = lookupKey(name, cm.state.keyMaps[i], handle, cm);
  5668. if (result) return result;
  5669. }
  5670. return (cm.options.extraKeys && lookupKey(name, cm.options.extraKeys, handle, cm))
  5671. || lookupKey(name, cm.options.keyMap, handle, cm);
  5672. }
  5673. var stopSeq = new Delayed;
  5674. function dispatchKey(cm, name, e, handle) {
  5675. var seq = cm.state.keySeq;
  5676. if (seq) {
  5677. if (isModifierKey(name)) return "handled";
  5678. stopSeq.set(50, function() {
  5679. if (cm.state.keySeq == seq) {
  5680. cm.state.keySeq = null;
  5681. cm.display.input.reset();
  5682. }
  5683. });
  5684. name = seq + " " + name;
  5685. }
  5686. var result = lookupKeyForEditor(cm, name, handle);
  5687. if (result == "multi")
  5688. cm.state.keySeq = name;
  5689. if (result == "handled")
  5690. signalLater(cm, "keyHandled", cm, name, e);
  5691. if (result == "handled" || result == "multi") {
  5692. e_preventDefault(e);
  5693. restartBlink(cm);
  5694. }
  5695. if (seq && !result && /\'$/.test(name)) {
  5696. e_preventDefault(e);
  5697. return true;
  5698. }
  5699. return !!result;
  5700. }
  5701. // Handle a key from the keydown event.
  5702. function handleKeyBinding(cm, e) {
  5703. var name = keyName(e, true);
  5704. if (!name) return false;
  5705. if (e.shiftKey && !cm.state.keySeq) {
  5706. // First try to resolve full name (including 'Shift-'). Failing
  5707. // that, see if there is a cursor-motion command (starting with
  5708. // 'go') bound to the keyname without 'Shift-'.
  5709. return dispatchKey(cm, "Shift-" + name, e, function(b) {return doHandleBinding(cm, b, true);})
  5710. || dispatchKey(cm, name, e, function(b) {
  5711. if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion)
  5712. return doHandleBinding(cm, b);
  5713. });
  5714. } else {
  5715. return dispatchKey(cm, name, e, function(b) { return doHandleBinding(cm, b); });
  5716. }
  5717. }
  5718. // Handle a key from the keypress event
  5719. function handleCharBinding(cm, e, ch) {
  5720. return dispatchKey(cm, "'" + ch + "'", e,
  5721. function(b) { return doHandleBinding(cm, b, true); });
  5722. }
  5723. var lastStoppedKey = null;
  5724. function onKeyDown(e) {
  5725. var cm = this;
  5726. cm.curOp.focus = activeElt();
  5727. if (signalDOMEvent(cm, e)) return;
  5728. // IE does strange things with escape.
  5729. if (ie && ie_version < 11 && e.keyCode == 27) e.returnValue = false;
  5730. var code = e.keyCode;
  5731. cm.display.shift = code == 16 || e.shiftKey;
  5732. var handled = handleKeyBinding(cm, e);
  5733. if (presto) {
  5734. lastStoppedKey = handled ? code : null;
  5735. // Opera has no cut event... we try to at least catch the key combo
  5736. if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey))
  5737. cm.replaceSelection("", null, "cut");
  5738. }
  5739. // Turn mouse into crosshair when Alt is held on Mac.
  5740. if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className))
  5741. showCrossHair(cm);
  5742. }
  5743. function showCrossHair(cm) {
  5744. var lineDiv = cm.display.lineDiv;
  5745. addClass(lineDiv, "CodeMirror-crosshair");
  5746. function up(e) {
  5747. if (e.keyCode == 18 || !e.altKey) {
  5748. rmClass(lineDiv, "CodeMirror-crosshair");
  5749. off(document, "keyup", up);
  5750. off(document, "mouseover", up);
  5751. }
  5752. }
  5753. on(document, "keyup", up);
  5754. on(document, "mouseover", up);
  5755. }
  5756. function onKeyUp(e) {
  5757. if (e.keyCode == 16) this.doc.sel.shift = false;
  5758. signalDOMEvent(this, e);
  5759. }
  5760. function onKeyPress(e) {
  5761. var cm = this;
  5762. if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) return;
  5763. var keyCode = e.keyCode, charCode = e.charCode;
  5764. if (presto && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return;}
  5765. if ((presto && (!e.which || e.which < 10)) && handleKeyBinding(cm, e)) return;
  5766. var ch = String.fromCharCode(charCode == null ? keyCode : charCode);
  5767. if (handleCharBinding(cm, e, ch)) return;
  5768. cm.display.input.onKeyPress(e);
  5769. }
  5770. // FOCUS/BLUR EVENTS
  5771. function delayBlurEvent(cm) {
  5772. cm.state.delayingBlurEvent = true;
  5773. setTimeout(function() {
  5774. if (cm.state.delayingBlurEvent) {
  5775. cm.state.delayingBlurEvent = false;
  5776. onBlur(cm);
  5777. }
  5778. }, 100);
  5779. }
  5780. function onFocus(cm) {
  5781. if (cm.state.delayingBlurEvent) cm.state.delayingBlurEvent = false;
  5782. if (cm.options.readOnly == "nocursor") return;
  5783. if (!cm.state.focused) {
  5784. signal(cm, "focus", cm);
  5785. cm.state.focused = true;
  5786. addClass(cm.display.wrapper, "CodeMirror-focused");
  5787. // This test prevents this from firing when a context
  5788. // menu is closed (since the input reset would kill the
  5789. // select-all detection hack)
  5790. if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) {
  5791. cm.display.input.reset();
  5792. if (webkit) setTimeout(function() { cm.display.input.reset(true); }, 20); // Issue #1730
  5793. }
  5794. cm.display.input.receivedFocus();
  5795. }
  5796. restartBlink(cm);
  5797. }
  5798. function onBlur(cm) {
  5799. if (cm.state.delayingBlurEvent) return;
  5800. if (cm.state.focused) {
  5801. signal(cm, "blur", cm);
  5802. cm.state.focused = false;
  5803. rmClass(cm.display.wrapper, "CodeMirror-focused");
  5804. }
  5805. clearInterval(cm.display.blinker);
  5806. setTimeout(function() {if (!cm.state.focused) cm.display.shift = false;}, 150);
  5807. }
  5808. // CONTEXT MENU HANDLING
  5809. // To make the context menu work, we need to briefly unhide the
  5810. // textarea (making it as unobtrusive as possible) to let the
  5811. // right-click take effect on it.
  5812. function onContextMenu(cm, e) {
  5813. if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) return;
  5814. if (signalDOMEvent(cm, e, "contextmenu")) return;
  5815. cm.display.input.onContextMenu(e);
  5816. }
  5817. function contextMenuInGutter(cm, e) {
  5818. if (!hasHandler(cm, "gutterContextMenu")) return false;
  5819. return gutterEvent(cm, e, "gutterContextMenu", false);
  5820. }
  5821. // UPDATING
  5822. // Compute the position of the end of a change (its 'to' property
  5823. // refers to the pre-change end).
  5824. var changeEnd = CodeMirror.changeEnd = function(change) {
  5825. if (!change.text) return change.to;
  5826. return Pos(change.from.line + change.text.length - 1,
  5827. lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0));
  5828. };
  5829. // Adjust a position to refer to the post-change position of the
  5830. // same text, or the end of the change if the change covers it.
  5831. function adjustForChange(pos, change) {
  5832. if (cmp(pos, change.from) < 0) return pos;
  5833. if (cmp(pos, change.to) <= 0) return changeEnd(change);
  5834. var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch;
  5835. if (pos.line == change.to.line) ch += changeEnd(change).ch - change.to.ch;
  5836. return Pos(line, ch);
  5837. }
  5838. function computeSelAfterChange(doc, change) {
  5839. var out = [];
  5840. for (var i = 0; i < doc.sel.ranges.length; i++) {
  5841. var range = doc.sel.ranges[i];
  5842. out.push(new Range(adjustForChange(range.anchor, change),
  5843. adjustForChange(range.head, change)));
  5844. }
  5845. return normalizeSelection(out, doc.sel.primIndex);
  5846. }
  5847. function offsetPos(pos, old, nw) {
  5848. if (pos.line == old.line)
  5849. return Pos(nw.line, pos.ch - old.ch + nw.ch);
  5850. else
  5851. return Pos(nw.line + (pos.line - old.line), pos.ch);
  5852. }
  5853. // Used by replaceSelections to allow moving the selection to the
  5854. // start or around the replaced test. Hint may be "start" or "around".
  5855. function computeReplacedSel(doc, changes, hint) {
  5856. var out = [];
  5857. var oldPrev = Pos(doc.first, 0), newPrev = oldPrev;
  5858. for (var i = 0; i < changes.length; i++) {
  5859. var change = changes[i];
  5860. var from = offsetPos(change.from, oldPrev, newPrev);
  5861. var to = offsetPos(changeEnd(change), oldPrev, newPrev);
  5862. oldPrev = change.to;
  5863. newPrev = to;
  5864. if (hint == "around") {
  5865. var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) < 0;
  5866. out[i] = new Range(inv ? to : from, inv ? from : to);
  5867. } else {
  5868. out[i] = new Range(from, from);
  5869. }
  5870. }
  5871. return new Selection(out, doc.sel.primIndex);
  5872. }
  5873. // Allow "beforeChange" event handlers to influence a change
  5874. function filterChange(doc, change, update) {
  5875. var obj = {
  5876. canceled: false,
  5877. from: change.from,
  5878. to: change.to,
  5879. text: change.text,
  5880. origin: change.origin,
  5881. cancel: function() { this.canceled = true; }
  5882. };
  5883. if (update) obj.update = function(from, to, text, origin) {
  5884. if (from) this.from = clipPos(doc, from);
  5885. if (to) this.to = clipPos(doc, to);
  5886. if (text) this.text = text;
  5887. if (origin !== undefined) this.origin = origin;
  5888. };
  5889. signal(doc, "beforeChange", doc, obj);
  5890. if (doc.cm) signal(doc.cm, "beforeChange", doc.cm, obj);
  5891. if (obj.canceled) return null;
  5892. return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin};
  5893. }
  5894. // Apply a change to a document, and add it to the document's
  5895. // history, and propagating it to all linked documents.
  5896. function makeChange(doc, change, ignoreReadOnly) {
  5897. if (doc.cm) {
  5898. if (!doc.cm.curOp) return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly);
  5899. if (doc.cm.state.suppressEdits) return;
  5900. }
  5901. if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) {
  5902. change = filterChange(doc, change, true);
  5903. if (!change) return;
  5904. }
  5905. // Possibly split or suppress the update based on the presence
  5906. // of read-only spans in its range.
  5907. var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to);
  5908. if (split) {
  5909. for (var i = split.length - 1; i >= 0; --i)
  5910. makeChangeInner(doc, {from: split[i].from, to: split[i].to, text: i ? [""] : change.text});
  5911. } else {
  5912. makeChangeInner(doc, change);
  5913. }
  5914. }
  5915. function makeChangeInner(doc, change) {
  5916. if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) return;
  5917. var selAfter = computeSelAfterChange(doc, change);
  5918. addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN);
  5919. makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change));
  5920. var rebased = [];
  5921. linkedDocs(doc, function(doc, sharedHist) {
  5922. if (!sharedHist && indexOf(rebased, doc.history) == -1) {
  5923. rebaseHist(doc.history, change);
  5924. rebased.push(doc.history);
  5925. }
  5926. makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change));
  5927. });
  5928. }
  5929. // Revert a change stored in a document's history.
  5930. function makeChangeFromHistory(doc, type, allowSelectionOnly) {
  5931. if (doc.cm && doc.cm.state.suppressEdits) return;
  5932. var hist = doc.history, event, selAfter = doc.sel;
  5933. var source = type == "undo" ? hist.done : hist.undone, dest = type == "undo" ? hist.undone : hist.done;
  5934. // Verify that there is a useable event (so that ctrl-z won't
  5935. // needlessly clear selection events)
  5936. for (var i = 0; i < source.length; i++) {
  5937. event = source[i];
  5938. if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges)
  5939. break;
  5940. }
  5941. if (i == source.length) return;
  5942. hist.lastOrigin = hist.lastSelOrigin = null;
  5943. for (;;) {
  5944. event = source.pop();
  5945. if (event.ranges) {
  5946. pushSelectionToHistory(event, dest);
  5947. if (allowSelectionOnly && !event.equals(doc.sel)) {
  5948. setSelection(doc, event, {clearRedo: false});
  5949. return;
  5950. }
  5951. selAfter = event;
  5952. }
  5953. else break;
  5954. }
  5955. // Build up a reverse change object to add to the opposite history
  5956. // stack (redo when undoing, and vice versa).
  5957. var antiChanges = [];
  5958. pushSelectionToHistory(selAfter, dest);
  5959. dest.push({changes: antiChanges, generation: hist.generation});
  5960. hist.generation = event.generation || ++hist.maxGeneration;
  5961. var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange");
  5962. for (var i = event.changes.length - 1; i >= 0; --i) {
  5963. var change = event.changes[i];
  5964. change.origin = type;
  5965. if (filter && !filterChange(doc, change, false)) {
  5966. source.length = 0;
  5967. return;
  5968. }
  5969. antiChanges.push(historyChangeFromChange(doc, change));
  5970. var after = i ? computeSelAfterChange(doc, change) : lst(source);
  5971. makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change));
  5972. if (!i && doc.cm) doc.cm.scrollIntoView({from: change.from, to: changeEnd(change)});
  5973. var rebased = [];
  5974. // Propagate to the linked documents
  5975. linkedDocs(doc, function(doc, sharedHist) {
  5976. if (!sharedHist && indexOf(rebased, doc.history) == -1) {
  5977. rebaseHist(doc.history, change);
  5978. rebased.push(doc.history);
  5979. }
  5980. makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change));
  5981. });
  5982. }
  5983. }
  5984. // Sub-views need their line numbers shifted when text is added
  5985. // above or below them in the parent document.
  5986. function shiftDoc(doc, distance) {
  5987. if (distance == 0) return;
  5988. doc.first += distance;
  5989. doc.sel = new Selection(map(doc.sel.ranges, function(range) {
  5990. return new Range(Pos(range.anchor.line + distance, range.anchor.ch),
  5991. Pos(range.head.line + distance, range.head.ch));
  5992. }), doc.sel.primIndex);
  5993. if (doc.cm) {
  5994. regChange(doc.cm, doc.first, doc.first - distance, distance);
  5995. for (var d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++)
  5996. regLineChange(doc.cm, l, "gutter");
  5997. }
  5998. }
  5999. // More lower-level change function, handling only a single document
  6000. // (not linked ones).
  6001. function makeChangeSingleDoc(doc, change, selAfter, spans) {
  6002. if (doc.cm && !doc.cm.curOp)
  6003. return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans);
  6004. if (change.to.line < doc.first) {
  6005. shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line));
  6006. return;
  6007. }
  6008. if (change.from.line > doc.lastLine()) return;
  6009. // Clip the change to the size of this doc
  6010. if (change.from.line < doc.first) {
  6011. var shift = change.text.length - 1 - (doc.first - change.from.line);
  6012. shiftDoc(doc, shift);
  6013. change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch),
  6014. text: [lst(change.text)], origin: change.origin};
  6015. }
  6016. var last = doc.lastLine();
  6017. if (change.to.line > last) {
  6018. change = {from: change.from, to: Pos(last, getLine(doc, last).text.length),
  6019. text: [change.text[0]], origin: change.origin};
  6020. }
  6021. change.removed = getBetween(doc, change.from, change.to);
  6022. if (!selAfter) selAfter = computeSelAfterChange(doc, change);
  6023. if (doc.cm) makeChangeSingleDocInEditor(doc.cm, change, spans);
  6024. else updateDoc(doc, change, spans);
  6025. setSelectionNoUndo(doc, selAfter, sel_dontScroll);
  6026. }
  6027. // Handle the interaction of a change to a document with the editor
  6028. // that this document is part of.
  6029. function makeChangeSingleDocInEditor(cm, change, spans) {
  6030. var doc = cm.doc, display = cm.display, from = change.from, to = change.to;
  6031. var recomputeMaxLength = false, checkWidthStart = from.line;
  6032. if (!cm.options.lineWrapping) {
  6033. checkWidthStart = lineNo(visualLine(getLine(doc, from.line)));
  6034. doc.iter(checkWidthStart, to.line + 1, function(line) {
  6035. if (line == display.maxLine) {
  6036. recomputeMaxLength = true;
  6037. return true;
  6038. }
  6039. });
  6040. }
  6041. if (doc.sel.contains(change.from, change.to) > -1)
  6042. signalCursorActivity(cm);
  6043. updateDoc(doc, change, spans, estimateHeight(cm));
  6044. if (!cm.options.lineWrapping) {
  6045. doc.iter(checkWidthStart, from.line + change.text.length, function(line) {
  6046. var len = lineLength(line);
  6047. if (len > display.maxLineLength) {
  6048. display.maxLine = line;
  6049. display.maxLineLength = len;
  6050. display.maxLineChanged = true;
  6051. recomputeMaxLength = false;
  6052. }
  6053. });
  6054. if (recomputeMaxLength) cm.curOp.updateMaxLine = true;
  6055. }
  6056. // Adjust frontier, schedule worker
  6057. doc.frontier = Math.min(doc.frontier, from.line);
  6058. startWorker(cm, 400);
  6059. var lendiff = change.text.length - (to.line - from.line) - 1;
  6060. // Remember that these lines changed, for updating the display
  6061. if (change.full)
  6062. regChange(cm);
  6063. else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change))
  6064. regLineChange(cm, from.line, "text");
  6065. else
  6066. regChange(cm, from.line, to.line + 1, lendiff);
  6067. var changesHandler = hasHandler(cm, "changes"), changeHandler = hasHandler(cm, "change");
  6068. if (changeHandler || changesHandler) {
  6069. var obj = {
  6070. from: from, to: to,
  6071. text: change.text,
  6072. removed: change.removed,
  6073. origin: change.origin
  6074. };
  6075. if (changeHandler) signalLater(cm, "change", cm, obj);
  6076. if (changesHandler) (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj);
  6077. }
  6078. cm.display.selForContextMenu = null;
  6079. }
  6080. function replaceRange(doc, code, from, to, origin) {
  6081. if (!to) to = from;
  6082. if (cmp(to, from) < 0) { var tmp = to; to = from; from = tmp; }
  6083. if (typeof code == "string") code = doc.splitLines(code);
  6084. makeChange(doc, {from: from, to: to, text: code, origin: origin});
  6085. }
  6086. // SCROLLING THINGS INTO VIEW
  6087. // If an editor sits on the top or bottom of the window, partially
  6088. // scrolled out of view, this ensures that the cursor is visible.
  6089. function maybeScrollWindow(cm, coords) {
  6090. if (signalDOMEvent(cm, "scrollCursorIntoView")) return;
  6091. var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null;
  6092. if (coords.top + box.top < 0) doScroll = true;
  6093. else if (coords.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) doScroll = false;
  6094. if (doScroll != null && !phantom) {
  6095. var scrollNode = elt("div", "\u200b", null, "position: absolute; top: " +
  6096. (coords.top - display.viewOffset - paddingTop(cm.display)) + "px; height: " +
  6097. (coords.bottom - coords.top + scrollGap(cm) + display.barHeight) + "px; left: " +
  6098. coords.left + "px; width: 2px;");
  6099. cm.display.lineSpace.appendChild(scrollNode);
  6100. scrollNode.scrollIntoView(doScroll);
  6101. cm.display.lineSpace.removeChild(scrollNode);
  6102. }
  6103. }
  6104. // Scroll a given position into view (immediately), verifying that
  6105. // it actually became visible (as line heights are accurately
  6106. // measured, the position of something may 'drift' during drawing).
  6107. function scrollPosIntoView(cm, pos, end, margin) {
  6108. if (margin == null) margin = 0;
  6109. for (var limit = 0; limit < 5; limit++) {
  6110. var changed = false, coords = cursorCoords(cm, pos);
  6111. var endCoords = !end || end == pos ? coords : cursorCoords(cm, end);
  6112. var scrollPos = calculateScrollPos(cm, Math.min(coords.left, endCoords.left),
  6113. Math.min(coords.top, endCoords.top) - margin,
  6114. Math.max(coords.left, endCoords.left),
  6115. Math.max(coords.bottom, endCoords.bottom) + margin);
  6116. var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft;
  6117. if (scrollPos.scrollTop != null) {
  6118. setScrollTop(cm, scrollPos.scrollTop);
  6119. if (Math.abs(cm.doc.scrollTop - startTop) > 1) changed = true;
  6120. }
  6121. if (scrollPos.scrollLeft != null) {
  6122. setScrollLeft(cm, scrollPos.scrollLeft);
  6123. if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) changed = true;
  6124. }
  6125. if (!changed) break;
  6126. }
  6127. return coords;
  6128. }
  6129. // Scroll a given set of coordinates into view (immediately).
  6130. function scrollIntoView(cm, x1, y1, x2, y2) {
  6131. var scrollPos = calculateScrollPos(cm, x1, y1, x2, y2);
  6132. if (scrollPos.scrollTop != null) setScrollTop(cm, scrollPos.scrollTop);
  6133. if (scrollPos.scrollLeft != null) setScrollLeft(cm, scrollPos.scrollLeft);
  6134. }
  6135. // Calculate a new scroll position needed to scroll the given
  6136. // rectangle into view. Returns an object with scrollTop and
  6137. // scrollLeft properties. When these are undefined, the
  6138. // vertical/horizontal position does not need to be adjusted.
  6139. function calculateScrollPos(cm, x1, y1, x2, y2) {
  6140. var display = cm.display, snapMargin = textHeight(cm.display);
  6141. if (y1 < 0) y1 = 0;
  6142. var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop;
  6143. var screen = displayHeight(cm), result = {};
  6144. if (y2 - y1 > screen) y2 = y1 + screen;
  6145. var docBottom = cm.doc.height + paddingVert(display);
  6146. var atTop = y1 < snapMargin, atBottom = y2 > docBottom - snapMargin;
  6147. if (y1 < screentop) {
  6148. result.scrollTop = atTop ? 0 : y1;
  6149. } else if (y2 > screentop + screen) {
  6150. var newTop = Math.min(y1, (atBottom ? docBottom : y2) - screen);
  6151. if (newTop != screentop) result.scrollTop = newTop;
  6152. }
  6153. var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft;
  6154. var screenw = displayWidth(cm) - (cm.options.fixedGutter ? display.gutters.offsetWidth : 0);
  6155. var tooWide = x2 - x1 > screenw;
  6156. if (tooWide) x2 = x1 + screenw;
  6157. if (x1 < 10)
  6158. result.scrollLeft = 0;
  6159. else if (x1 < screenleft)
  6160. result.scrollLeft = Math.max(0, x1 - (tooWide ? 0 : 10));
  6161. else if (x2 > screenw + screenleft - 3)
  6162. result.scrollLeft = x2 + (tooWide ? 0 : 10) - screenw;
  6163. return result;
  6164. }
  6165. // Store a relative adjustment to the scroll position in the current
  6166. // operation (to be applied when the operation finishes).
  6167. function addToScrollPos(cm, left, top) {
  6168. if (left != null || top != null) resolveScrollToPos(cm);
  6169. if (left != null)
  6170. cm.curOp.scrollLeft = (cm.curOp.scrollLeft == null ? cm.doc.scrollLeft : cm.curOp.scrollLeft) + left;
  6171. if (top != null)
  6172. cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top;
  6173. }
  6174. // Make sure that at the end of the operation the current cursor is
  6175. // shown.
  6176. function ensureCursorVisible(cm) {
  6177. resolveScrollToPos(cm);
  6178. var cur = cm.getCursor(), from = cur, to = cur;
  6179. if (!cm.options.lineWrapping) {
  6180. from = cur.ch ? Pos(cur.line, cur.ch - 1) : cur;
  6181. to = Pos(cur.line, cur.ch + 1);
  6182. }
  6183. cm.curOp.scrollToPos = {from: from, to: to, margin: cm.options.cursorScrollMargin, isCursor: true};
  6184. }
  6185. // When an operation has its scrollToPos property set, and another
  6186. // scroll action is applied before the end of the operation, this
  6187. // 'simulates' scrolling that position into view in a cheap way, so
  6188. // that the effect of intermediate scroll commands is not ignored.
  6189. function resolveScrollToPos(cm) {
  6190. var range = cm.curOp.scrollToPos;
  6191. if (range) {
  6192. cm.curOp.scrollToPos = null;
  6193. var from = estimateCoords(cm, range.from), to = estimateCoords(cm, range.to);
  6194. var sPos = calculateScrollPos(cm, Math.min(from.left, to.left),
  6195. Math.min(from.top, to.top) - range.margin,
  6196. Math.max(from.right, to.right),
  6197. Math.max(from.bottom, to.bottom) + range.margin);
  6198. cm.scrollTo(sPos.scrollLeft, sPos.scrollTop);
  6199. }
  6200. }
  6201. // API UTILITIES
  6202. // Indent the given line. The how parameter can be "smart",
  6203. // "add"/null, "subtract", or "prev". When aggressive is false
  6204. // (typically set to true for forced single-line indents), empty
  6205. // lines are not indented, and places where the mode returns Pass
  6206. // are left alone.
  6207. function indentLine(cm, n, how, aggressive) {
  6208. var doc = cm.doc, state;
  6209. if (how == null) how = "add";
  6210. if (how == "smart") {
  6211. // Fall back to "prev" when the mode doesn't have an indentation
  6212. // method.
  6213. if (!doc.mode.indent) how = "prev";
  6214. else state = getStateBefore(cm, n);
  6215. }
  6216. var tabSize = cm.options.tabSize;
  6217. var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize);
  6218. if (line.stateAfter) line.stateAfter = null;
  6219. var curSpaceString = line.text.match(/^\s*/)[0], indentation;
  6220. if (!aggressive && !/\S/.test(line.text)) {
  6221. indentation = 0;
  6222. how = "not";
  6223. } else if (how == "smart") {
  6224. indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text);
  6225. if (indentation == Pass || indentation > 150) {
  6226. if (!aggressive) return;
  6227. how = "prev";
  6228. }
  6229. }
  6230. if (how == "prev") {
  6231. if (n > doc.first) indentation = countColumn(getLine(doc, n-1).text, null, tabSize);
  6232. else indentation = 0;
  6233. } else if (how == "add") {
  6234. indentation = curSpace + cm.options.indentUnit;
  6235. } else if (how == "subtract") {
  6236. indentation = curSpace - cm.options.indentUnit;
  6237. } else if (typeof how == "number") {
  6238. indentation = curSpace + how;
  6239. }
  6240. indentation = Math.max(0, indentation);
  6241. var indentString = "", pos = 0;
  6242. if (cm.options.indentWithTabs)
  6243. for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";}
  6244. if (pos < indentation) indentString += spaceStr(indentation - pos);
  6245. if (indentString != curSpaceString) {
  6246. replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input");
  6247. line.stateAfter = null;
  6248. return true;
  6249. } else {
  6250. // Ensure that, if the cursor was in the whitespace at the start
  6251. // of the line, it is moved to the end of that space.
  6252. for (var i = 0; i < doc.sel.ranges.length; i++) {
  6253. var range = doc.sel.ranges[i];
  6254. if (range.head.line == n && range.head.ch < curSpaceString.length) {
  6255. var pos = Pos(n, curSpaceString.length);
  6256. replaceOneSelection(doc, i, new Range(pos, pos));
  6257. break;
  6258. }
  6259. }
  6260. }
  6261. }
  6262. // Utility for applying a change to a line by handle or number,
  6263. // returning the number and optionally registering the line as
  6264. // changed.
  6265. function changeLine(doc, handle, changeType, op) {
  6266. var no = handle, line = handle;
  6267. if (typeof handle == "number") line = getLine(doc, clipLine(doc, handle));
  6268. else no = lineNo(handle);
  6269. if (no == null) return null;
  6270. if (op(line, no) && doc.cm) regLineChange(doc.cm, no, changeType);
  6271. return line;
  6272. }
  6273. // Helper for deleting text near the selection(s), used to implement
  6274. // backspace, delete, and similar functionality.
  6275. function deleteNearSelection(cm, compute) {
  6276. var ranges = cm.doc.sel.ranges, kill = [];
  6277. // Build up a set of ranges to kill first, merging overlapping
  6278. // ranges.
  6279. for (var i = 0; i < ranges.length; i++) {
  6280. var toKill = compute(ranges[i]);
  6281. while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) {
  6282. var replaced = kill.pop();
  6283. if (cmp(replaced.from, toKill.from) < 0) {
  6284. toKill.from = replaced.from;
  6285. break;
  6286. }
  6287. }
  6288. kill.push(toKill);
  6289. }
  6290. // Next, remove those actual ranges.
  6291. runInOp(cm, function() {
  6292. for (var i = kill.length - 1; i >= 0; i--)
  6293. replaceRange(cm.doc, "", kill[i].from, kill[i].to, "+delete");
  6294. ensureCursorVisible(cm);
  6295. });
  6296. }
  6297. // Used for horizontal relative motion. Dir is -1 or 1 (left or
  6298. // right), unit can be "char", "column" (like char, but doesn't
  6299. // cross line boundaries), "word" (across next word), or "group" (to
  6300. // the start of next group of word or non-word-non-whitespace
  6301. // chars). The visually param controls whether, in right-to-left
  6302. // text, direction 1 means to move towards the next index in the
  6303. // string, or towards the character to the right of the current
  6304. // position. The resulting position will have a hitSide=true
  6305. // property if it reached the end of the document.
  6306. function findPosH(doc, pos, dir, unit, visually) {
  6307. var line = pos.line, ch = pos.ch, origDir = dir;
  6308. var lineObj = getLine(doc, line);
  6309. function findNextLine() {
  6310. var l = line + dir;
  6311. if (l < doc.first || l >= doc.first + doc.size) return false
  6312. line = l;
  6313. return lineObj = getLine(doc, l);
  6314. }
  6315. function moveOnce(boundToLine) {
  6316. var next = (visually ? moveVisually : moveLogically)(lineObj, ch, dir, true);
  6317. if (next == null) {
  6318. if (!boundToLine && findNextLine()) {
  6319. if (visually) ch = (dir < 0 ? lineRight : lineLeft)(lineObj);
  6320. else ch = dir < 0 ? lineObj.text.length : 0;
  6321. } else return false
  6322. } else ch = next;
  6323. return true;
  6324. }
  6325. if (unit == "char") {
  6326. moveOnce()
  6327. } else if (unit == "column") {
  6328. moveOnce(true)
  6329. } else if (unit == "word" || unit == "group") {
  6330. var sawType = null, group = unit == "group";
  6331. var helper = doc.cm && doc.cm.getHelper(pos, "wordChars");
  6332. for (var first = true;; first = false) {
  6333. if (dir < 0 && !moveOnce(!first)) break;
  6334. var cur = lineObj.text.charAt(ch) || "\n";
  6335. var type = isWordChar(cur, helper) ? "w"
  6336. : group && cur == "\n" ? "n"
  6337. : !group || /\s/.test(cur) ? null
  6338. : "p";
  6339. if (group && !first && !type) type = "s";
  6340. if (sawType && sawType != type) {
  6341. if (dir < 0) {dir = 1; moveOnce();}
  6342. break;
  6343. }
  6344. if (type) sawType = type;
  6345. if (dir > 0 && !moveOnce(!first)) break;
  6346. }
  6347. }
  6348. var result = skipAtomic(doc, Pos(line, ch), pos, origDir, true);
  6349. if (!cmp(pos, result)) result.hitSide = true;
  6350. return result;
  6351. }
  6352. // For relative vertical movement. Dir may be -1 or 1. Unit can be
  6353. // "page" or "line". The resulting position will have a hitSide=true
  6354. // property if it reached the end of the document.
  6355. function findPosV(cm, pos, dir, unit) {
  6356. var doc = cm.doc, x = pos.left, y;
  6357. if (unit == "page") {
  6358. var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight);
  6359. y = pos.top + dir * (pageSize - (dir < 0 ? 1.5 : .5) * textHeight(cm.display));
  6360. } else if (unit == "line") {
  6361. y = dir > 0 ? pos.bottom + 3 : pos.top - 3;
  6362. }
  6363. for (;;) {
  6364. var target = coordsChar(cm, x, y);
  6365. if (!target.outside) break;
  6366. if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break; }
  6367. y += dir * 5;
  6368. }
  6369. return target;
  6370. }
  6371. // EDITOR METHODS
  6372. // The publicly visible API. Note that methodOp(f) means
  6373. // 'wrap f in an operation, performed on its `this` parameter'.
  6374. // This is not the complete set of editor methods. Most of the
  6375. // methods defined on the Doc type are also injected into
  6376. // CodeMirror.prototype, for backwards compatibility and
  6377. // convenience.
  6378. CodeMirror.prototype = {
  6379. constructor: CodeMirror,
  6380. focus: function(){window.focus(); this.display.input.focus();},
  6381. setOption: function(option, value) {
  6382. var options = this.options, old = options[option];
  6383. if (options[option] == value && option != "mode") return;
  6384. options[option] = value;
  6385. if (optionHandlers.hasOwnProperty(option))
  6386. operation(this, optionHandlers[option])(this, value, old);
  6387. },
  6388. getOption: function(option) {return this.options[option];},
  6389. getDoc: function() {return this.doc;},
  6390. addKeyMap: function(map, bottom) {
  6391. this.state.keyMaps[bottom ? "push" : "unshift"](getKeyMap(map));
  6392. },
  6393. removeKeyMap: function(map) {
  6394. var maps = this.state.keyMaps;
  6395. for (var i = 0; i < maps.length; ++i)
  6396. if (maps[i] == map || maps[i].name == map) {
  6397. maps.splice(i, 1);
  6398. return true;
  6399. }
  6400. },
  6401. addOverlay: methodOp(function(spec, options) {
  6402. var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec);
  6403. if (mode.startState) throw new Error("Overlays may not be stateful.");
  6404. this.state.overlays.push({mode: mode, modeSpec: spec, opaque: options && options.opaque});
  6405. this.state.modeGen++;
  6406. regChange(this);
  6407. }),
  6408. removeOverlay: methodOp(function(spec) {
  6409. var overlays = this.state.overlays;
  6410. for (var i = 0; i < overlays.length; ++i) {
  6411. var cur = overlays[i].modeSpec;
  6412. if (cur == spec || typeof spec == "string" && cur.name == spec) {
  6413. overlays.splice(i, 1);
  6414. this.state.modeGen++;
  6415. regChange(this);
  6416. return;
  6417. }
  6418. }
  6419. }),
  6420. indentLine: methodOp(function(n, dir, aggressive) {
  6421. if (typeof dir != "string" && typeof dir != "number") {
  6422. if (dir == null) dir = this.options.smartIndent ? "smart" : "prev";
  6423. else dir = dir ? "add" : "subtract";
  6424. }
  6425. if (isLine(this.doc, n)) indentLine(this, n, dir, aggressive);
  6426. }),
  6427. indentSelection: methodOp(function(how) {
  6428. var ranges = this.doc.sel.ranges, end = -1;
  6429. for (var i = 0; i < ranges.length; i++) {
  6430. var range = ranges[i];
  6431. if (!range.empty()) {
  6432. var from = range.from(), to = range.to();
  6433. var start = Math.max(end, from.line);
  6434. end = Math.min(this.lastLine(), to.line - (to.ch ? 0 : 1)) + 1;
  6435. for (var j = start; j < end; ++j)
  6436. indentLine(this, j, how);
  6437. var newRanges = this.doc.sel.ranges;
  6438. if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i].from().ch > 0)
  6439. replaceOneSelection(this.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll);
  6440. } else if (range.head.line > end) {
  6441. indentLine(this, range.head.line, how, true);
  6442. end = range.head.line;
  6443. if (i == this.doc.sel.primIndex) ensureCursorVisible(this);
  6444. }
  6445. }
  6446. }),
  6447. // Fetch the parser token for a given character. Useful for hacks
  6448. // that want to inspect the mode state (say, for completion).
  6449. getTokenAt: function(pos, precise) {
  6450. return takeToken(this, pos, precise);
  6451. },
  6452. getLineTokens: function(line, precise) {
  6453. return takeToken(this, Pos(line), precise, true);
  6454. },
  6455. getTokenTypeAt: function(pos) {
  6456. pos = clipPos(this.doc, pos);
  6457. var styles = getLineStyles(this, getLine(this.doc, pos.line));
  6458. var before = 0, after = (styles.length - 1) / 2, ch = pos.ch;
  6459. var type;
  6460. if (ch == 0) type = styles[2];
  6461. else for (;;) {
  6462. var mid = (before + after) >> 1;
  6463. if ((mid ? styles[mid * 2 - 1] : 0) >= ch) after = mid;
  6464. else if (styles[mid * 2 + 1] < ch) before = mid + 1;
  6465. else { type = styles[mid * 2 + 2]; break; }
  6466. }
  6467. var cut = type ? type.indexOf("cm-overlay ") : -1;
  6468. return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1);
  6469. },
  6470. getModeAt: function(pos) {
  6471. var mode = this.doc.mode;
  6472. if (!mode.innerMode) return mode;
  6473. return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode;
  6474. },
  6475. getHelper: function(pos, type) {
  6476. return this.getHelpers(pos, type)[0];
  6477. },
  6478. getHelpers: function(pos, type) {
  6479. var found = [];
  6480. if (!helpers.hasOwnProperty(type)) return found;
  6481. var help = helpers[type], mode = this.getModeAt(pos);
  6482. if (typeof mode[type] == "string") {
  6483. if (help[mode[type]]) found.push(help[mode[type]]);
  6484. } else if (mode[type]) {
  6485. for (var i = 0; i < mode[type].length; i++) {
  6486. var val = help[mode[type][i]];
  6487. if (val) found.push(val);
  6488. }
  6489. } else if (mode.helperType && help[mode.helperType]) {
  6490. found.push(help[mode.helperType]);
  6491. } else if (help[mode.name]) {
  6492. found.push(help[mode.name]);
  6493. }
  6494. for (var i = 0; i < help._global.length; i++) {
  6495. var cur = help._global[i];
  6496. if (cur.pred(mode, this) && indexOf(found, cur.val) == -1)
  6497. found.push(cur.val);
  6498. }
  6499. return found;
  6500. },
  6501. getStateAfter: function(line, precise) {
  6502. var doc = this.doc;
  6503. line = clipLine(doc, line == null ? doc.first + doc.size - 1: line);
  6504. return getStateBefore(this, line + 1, precise);
  6505. },
  6506. cursorCoords: function(start, mode) {
  6507. var pos, range = this.doc.sel.primary();
  6508. if (start == null) pos = range.head;
  6509. else if (typeof start == "object") pos = clipPos(this.doc, start);
  6510. else pos = start ? range.from() : range.to();
  6511. return cursorCoords(this, pos, mode || "page");
  6512. },
  6513. charCoords: function(pos, mode) {
  6514. return charCoords(this, clipPos(this.doc, pos), mode || "page");
  6515. },
  6516. coordsChar: function(coords, mode) {
  6517. coords = fromCoordSystem(this, coords, mode || "page");
  6518. return coordsChar(this, coords.left, coords.top);
  6519. },
  6520. lineAtHeight: function(height, mode) {
  6521. height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top;
  6522. return lineAtHeight(this.doc, height + this.display.viewOffset);
  6523. },
  6524. heightAtLine: function(line, mode) {
  6525. var end = false, lineObj;
  6526. if (typeof line == "number") {
  6527. var last = this.doc.first + this.doc.size - 1;
  6528. if (line < this.doc.first) line = this.doc.first;
  6529. else if (line > last) { line = last; end = true; }
  6530. lineObj = getLine(this.doc, line);
  6531. } else {
  6532. lineObj = line;
  6533. }
  6534. return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || "page").top +
  6535. (end ? this.doc.height - heightAtLine(lineObj) : 0);
  6536. },
  6537. defaultTextHeight: function() { return textHeight(this.display); },
  6538. defaultCharWidth: function() { return charWidth(this.display); },
  6539. setGutterMarker: methodOp(function(line, gutterID, value) {
  6540. return changeLine(this.doc, line, "gutter", function(line) {
  6541. var markers = line.gutterMarkers || (line.gutterMarkers = {});
  6542. markers[gutterID] = value;
  6543. if (!value && isEmpty(markers)) line.gutterMarkers = null;
  6544. return true;
  6545. });
  6546. }),
  6547. clearGutter: methodOp(function(gutterID) {
  6548. var cm = this, doc = cm.doc, i = doc.first;
  6549. doc.iter(function(line) {
  6550. if (line.gutterMarkers && line.gutterMarkers[gutterID]) {
  6551. line.gutterMarkers[gutterID] = null;
  6552. regLineChange(cm, i, "gutter");
  6553. if (isEmpty(line.gutterMarkers)) line.gutterMarkers = null;
  6554. }
  6555. ++i;
  6556. });
  6557. }),
  6558. lineInfo: function(line) {
  6559. if (typeof line == "number") {
  6560. if (!isLine(this.doc, line)) return null;
  6561. var n = line;
  6562. line = getLine(this.doc, line);
  6563. if (!line) return null;
  6564. } else {
  6565. var n = lineNo(line);
  6566. if (n == null) return null;
  6567. }
  6568. return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers,
  6569. textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass,
  6570. widgets: line.widgets};
  6571. },
  6572. getViewport: function() { return {from: this.display.viewFrom, to: this.display.viewTo};},
  6573. addWidget: function(pos, node, scroll, vert, horiz) {
  6574. var display = this.display;
  6575. pos = cursorCoords(this, clipPos(this.doc, pos));
  6576. var top = pos.bottom, left = pos.left;
  6577. node.style.position = "absolute";
  6578. node.setAttribute("cm-ignore-events", "true");
  6579. this.display.input.setUneditable(node);
  6580. display.sizer.appendChild(node);
  6581. if (vert == "over") {
  6582. top = pos.top;
  6583. } else if (vert == "above" || vert == "near") {
  6584. var vspace = Math.max(display.wrapper.clientHeight, this.doc.height),
  6585. hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth);
  6586. // Default to positioning above (if specified and possible); otherwise default to positioning below
  6587. if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight)
  6588. top = pos.top - node.offsetHeight;
  6589. else if (pos.bottom + node.offsetHeight <= vspace)
  6590. top = pos.bottom;
  6591. if (left + node.offsetWidth > hspace)
  6592. left = hspace - node.offsetWidth;
  6593. }
  6594. node.style.top = top + "px";
  6595. node.style.left = node.style.right = "";
  6596. if (horiz == "right") {
  6597. left = display.sizer.clientWidth - node.offsetWidth;
  6598. node.style.right = "0px";
  6599. } else {
  6600. if (horiz == "left") left = 0;
  6601. else if (horiz == "middle") left = (display.sizer.clientWidth - node.offsetWidth) / 2;
  6602. node.style.left = left + "px";
  6603. }
  6604. if (scroll)
  6605. scrollIntoView(this, left, top, left + node.offsetWidth, top + node.offsetHeight);
  6606. },
  6607. triggerOnKeyDown: methodOp(onKeyDown),
  6608. triggerOnKeyPress: methodOp(onKeyPress),
  6609. triggerOnKeyUp: onKeyUp,
  6610. execCommand: function(cmd) {
  6611. if (commands.hasOwnProperty(cmd))
  6612. return commands[cmd].call(null, this);
  6613. },
  6614. triggerElectric: methodOp(function(text) { triggerElectric(this, text); }),
  6615. findPosH: function(from, amount, unit, visually) {
  6616. var dir = 1;
  6617. if (amount < 0) { dir = -1; amount = -amount; }
  6618. for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) {
  6619. cur = findPosH(this.doc, cur, dir, unit, visually);
  6620. if (cur.hitSide) break;
  6621. }
  6622. return cur;
  6623. },
  6624. moveH: methodOp(function(dir, unit) {
  6625. var cm = this;
  6626. cm.extendSelectionsBy(function(range) {
  6627. if (cm.display.shift || cm.doc.extend || range.empty())
  6628. return findPosH(cm.doc, range.head, dir, unit, cm.options.rtlMoveVisually);
  6629. else
  6630. return dir < 0 ? range.from() : range.to();
  6631. }, sel_move);
  6632. }),
  6633. deleteH: methodOp(function(dir, unit) {
  6634. var sel = this.doc.sel, doc = this.doc;
  6635. if (sel.somethingSelected())
  6636. doc.replaceSelection("", null, "+delete");
  6637. else
  6638. deleteNearSelection(this, function(range) {
  6639. var other = findPosH(doc, range.head, dir, unit, false);
  6640. return dir < 0 ? {from: other, to: range.head} : {from: range.head, to: other};
  6641. });
  6642. }),
  6643. findPosV: function(from, amount, unit, goalColumn) {
  6644. var dir = 1, x = goalColumn;
  6645. if (amount < 0) { dir = -1; amount = -amount; }
  6646. for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) {
  6647. var coords = cursorCoords(this, cur, "div");
  6648. if (x == null) x = coords.left;
  6649. else coords.left = x;
  6650. cur = findPosV(this, coords, dir, unit);
  6651. if (cur.hitSide) break;
  6652. }
  6653. return cur;
  6654. },
  6655. moveV: methodOp(function(dir, unit) {
  6656. var cm = this, doc = this.doc, goals = [];
  6657. var collapse = !cm.display.shift && !doc.extend && doc.sel.somethingSelected();
  6658. doc.extendSelectionsBy(function(range) {
  6659. if (collapse)
  6660. return dir < 0 ? range.from() : range.to();
  6661. var headPos = cursorCoords(cm, range.head, "div");
  6662. if (range.goalColumn != null) headPos.left = range.goalColumn;
  6663. goals.push(headPos.left);
  6664. var pos = findPosV(cm, headPos, dir, unit);
  6665. if (unit == "page" && range == doc.sel.primary())
  6666. addToScrollPos(cm, null, charCoords(cm, pos, "div").top - headPos.top);
  6667. return pos;
  6668. }, sel_move);
  6669. if (goals.length) for (var i = 0; i < doc.sel.ranges.length; i++)
  6670. doc.sel.ranges[i].goalColumn = goals[i];
  6671. }),
  6672. // Find the word at the given position (as returned by coordsChar).
  6673. findWordAt: function(pos) {
  6674. var doc = this.doc, line = getLine(doc, pos.line).text;
  6675. var start = pos.ch, end = pos.ch;
  6676. if (line) {
  6677. var helper = this.getHelper(pos, "wordChars");
  6678. if ((pos.xRel < 0 || end == line.length) && start) --start; else ++end;
  6679. var startChar = line.charAt(start);
  6680. var check = isWordChar(startChar, helper)
  6681. ? function(ch) { return isWordChar(ch, helper); }
  6682. : /\s/.test(startChar) ? function(ch) {return /\s/.test(ch);}
  6683. : function(ch) {return !/\s/.test(ch) && !isWordChar(ch);};
  6684. while (start > 0 && check(line.charAt(start - 1))) --start;
  6685. while (end < line.length && check(line.charAt(end))) ++end;
  6686. }
  6687. return new Range(Pos(pos.line, start), Pos(pos.line, end));
  6688. },
  6689. toggleOverwrite: function(value) {
  6690. if (value != null && value == this.state.overwrite) return;
  6691. if (this.state.overwrite = !this.state.overwrite)
  6692. addClass(this.display.cursorDiv, "CodeMirror-overwrite");
  6693. else
  6694. rmClass(this.display.cursorDiv, "CodeMirror-overwrite");
  6695. signal(this, "overwriteToggle", this, this.state.overwrite);
  6696. },
  6697. hasFocus: function() { return this.display.input.getField() == activeElt(); },
  6698. isReadOnly: function() { return !!(this.options.readOnly || this.doc.cantEdit); },
  6699. scrollTo: methodOp(function(x, y) {
  6700. if (x != null || y != null) resolveScrollToPos(this);
  6701. if (x != null) this.curOp.scrollLeft = x;
  6702. if (y != null) this.curOp.scrollTop = y;
  6703. }),
  6704. getScrollInfo: function() {
  6705. var scroller = this.display.scroller;
  6706. return {left: scroller.scrollLeft, top: scroller.scrollTop,
  6707. height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight,
  6708. width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth,
  6709. clientHeight: displayHeight(this), clientWidth: displayWidth(this)};
  6710. },
  6711. scrollIntoView: methodOp(function(range, margin) {
  6712. if (range == null) {
  6713. range = {from: this.doc.sel.primary().head, to: null};
  6714. if (margin == null) margin = this.options.cursorScrollMargin;
  6715. } else if (typeof range == "number") {
  6716. range = {from: Pos(range, 0), to: null};
  6717. } else if (range.from == null) {
  6718. range = {from: range, to: null};
  6719. }
  6720. if (!range.to) range.to = range.from;
  6721. range.margin = margin || 0;
  6722. if (range.from.line != null) {
  6723. resolveScrollToPos(this);
  6724. this.curOp.scrollToPos = range;
  6725. } else {
  6726. var sPos = calculateScrollPos(this, Math.min(range.from.left, range.to.left),
  6727. Math.min(range.from.top, range.to.top) - range.margin,
  6728. Math.max(range.from.right, range.to.right),
  6729. Math.max(range.from.bottom, range.to.bottom) + range.margin);
  6730. this.scrollTo(sPos.scrollLeft, sPos.scrollTop);
  6731. }
  6732. }),
  6733. setSize: methodOp(function(width, height) {
  6734. var cm = this;
  6735. function interpret(val) {
  6736. return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val;
  6737. }
  6738. if (width != null) cm.display.wrapper.style.width = interpret(width);
  6739. if (height != null) cm.display.wrapper.style.height = interpret(height);
  6740. if (cm.options.lineWrapping) clearLineMeasurementCache(this);
  6741. var lineNo = cm.display.viewFrom;
  6742. cm.doc.iter(lineNo, cm.display.viewTo, function(line) {
  6743. if (line.widgets) for (var i = 0; i < line.widgets.length; i++)
  6744. if (line.widgets[i].noHScroll) { regLineChange(cm, lineNo, "widget"); break; }
  6745. ++lineNo;
  6746. });
  6747. cm.curOp.forceUpdate = true;
  6748. signal(cm, "refresh", this);
  6749. }),
  6750. operation: function(f){return runInOp(this, f);},
  6751. refresh: methodOp(function() {
  6752. var oldHeight = this.display.cachedTextHeight;
  6753. regChange(this);
  6754. this.curOp.forceUpdate = true;
  6755. clearCaches(this);
  6756. this.scrollTo(this.doc.scrollLeft, this.doc.scrollTop);
  6757. updateGutterSpace(this);
  6758. if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5)
  6759. estimateLineHeights(this);
  6760. signal(this, "refresh", this);
  6761. }),
  6762. swapDoc: methodOp(function(doc) {
  6763. var old = this.doc;
  6764. old.cm = null;
  6765. attachDoc(this, doc);
  6766. clearCaches(this);
  6767. this.display.input.reset();
  6768. this.scrollTo(doc.scrollLeft, doc.scrollTop);
  6769. this.curOp.forceScroll = true;
  6770. signalLater(this, "swapDoc", this, old);
  6771. return old;
  6772. }),
  6773. getInputField: function(){return this.display.input.getField();},
  6774. getWrapperElement: function(){return this.display.wrapper;},
  6775. getScrollerElement: function(){return this.display.scroller;},
  6776. getGutterElement: function(){return this.display.gutters;}
  6777. };
  6778. eventMixin(CodeMirror);
  6779. // OPTION DEFAULTS
  6780. // The default configuration options.
  6781. var defaults = CodeMirror.defaults = {};
  6782. // Functions to run when options are changed.
  6783. var optionHandlers = CodeMirror.optionHandlers = {};
  6784. function option(name, deflt, handle, notOnInit) {
  6785. CodeMirror.defaults[name] = deflt;
  6786. if (handle) optionHandlers[name] =
  6787. notOnInit ? function(cm, val, old) {if (old != Init) handle(cm, val, old);} : handle;
  6788. }
  6789. // Passed to option handlers when there is no old value.
  6790. var Init = CodeMirror.Init = {toString: function(){return "CodeMirror.Init";}};
  6791. // These two are, on init, called from the constructor because they
  6792. // have to be initialized before the editor can start at all.
  6793. option("value", "", function(cm, val) {
  6794. cm.setValue(val);
  6795. }, true);
  6796. option("mode", null, function(cm, val) {
  6797. cm.doc.modeOption = val;
  6798. loadMode(cm);
  6799. }, true);
  6800. option("indentUnit", 2, loadMode, true);
  6801. option("indentWithTabs", false);
  6802. option("smartIndent", true);
  6803. option("tabSize", 4, function(cm) {
  6804. resetModeState(cm);
  6805. clearCaches(cm);
  6806. regChange(cm);
  6807. }, true);
  6808. option("lineSeparator", null, function(cm, val) {
  6809. cm.doc.lineSep = val;
  6810. if (!val) return;
  6811. var newBreaks = [], lineNo = cm.doc.first;
  6812. cm.doc.iter(function(line) {
  6813. for (var pos = 0;;) {
  6814. var found = line.text.indexOf(val, pos);
  6815. if (found == -1) break;
  6816. pos = found + val.length;
  6817. newBreaks.push(Pos(lineNo, found));
  6818. }
  6819. lineNo++;
  6820. });
  6821. for (var i = newBreaks.length - 1; i >= 0; i--)
  6822. replaceRange(cm.doc, val, newBreaks[i], Pos(newBreaks[i].line, newBreaks[i].ch + val.length))
  6823. });
  6824. option("specialChars", /[\u0000-\u001f\u007f\u00ad\u200b-\u200f\u2028\u2029\ufeff]/g, function(cm, val, old) {
  6825. cm.state.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g");
  6826. if (old != CodeMirror.Init) cm.refresh();
  6827. });
  6828. option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function(cm) {cm.refresh();}, true);
  6829. option("electricChars", true);
  6830. option("inputStyle", mobile ? "contenteditable" : "textarea", function() {
  6831. throw new Error("inputStyle can not (yet) be changed in a running editor"); // FIXME
  6832. }, true);
  6833. option("rtlMoveVisually", !windows);
  6834. option("wholeLineUpdateBefore", true);
  6835. option("theme", "default", function(cm) {
  6836. themeChanged(cm);
  6837. guttersChanged(cm);
  6838. }, true);
  6839. option("keyMap", "default", function(cm, val, old) {
  6840. var next = getKeyMap(val);
  6841. var prev = old != CodeMirror.Init && getKeyMap(old);
  6842. if (prev && prev.detach) prev.detach(cm, next);
  6843. if (next.attach) next.attach(cm, prev || null);
  6844. });
  6845. option("extraKeys", null);
  6846. option("lineWrapping", false, wrappingChanged, true);
  6847. option("gutters", [], function(cm) {
  6848. setGuttersForLineNumbers(cm.options);
  6849. guttersChanged(cm);
  6850. }, true);
  6851. option("fixedGutter", true, function(cm, val) {
  6852. cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0";
  6853. cm.refresh();
  6854. }, true);
  6855. option("coverGutterNextToScrollbar", false, function(cm) {updateScrollbars(cm);}, true);
  6856. option("scrollbarStyle", "native", function(cm) {
  6857. initScrollbars(cm);
  6858. updateScrollbars(cm);
  6859. cm.display.scrollbars.setScrollTop(cm.doc.scrollTop);
  6860. cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft);
  6861. }, true);
  6862. option("lineNumbers", false, function(cm) {
  6863. setGuttersForLineNumbers(cm.options);
  6864. guttersChanged(cm);
  6865. }, true);
  6866. option("firstLineNumber", 1, guttersChanged, true);
  6867. option("lineNumberFormatter", function(integer) {return integer;}, guttersChanged, true);
  6868. option("showCursorWhenSelecting", false, updateSelection, true);
  6869. option("resetSelectionOnContextMenu", true);
  6870. option("lineWiseCopyCut", true);
  6871. option("readOnly", false, function(cm, val) {
  6872. if (val == "nocursor") {
  6873. onBlur(cm);
  6874. cm.display.input.blur();
  6875. cm.display.disabled = true;
  6876. } else {
  6877. cm.display.disabled = false;
  6878. }
  6879. cm.display.input.readOnlyChanged(val)
  6880. });
  6881. option("disableInput", false, function(cm, val) {if (!val) cm.display.input.reset();}, true);
  6882. option("dragDrop", true, dragDropChanged);
  6883. option("allowDropFileTypes", null);
  6884. option("cursorBlinkRate", 530);
  6885. option("cursorScrollMargin", 0);
  6886. option("cursorHeight", 1, updateSelection, true);
  6887. option("singleCursorHeightPerLine", true, updateSelection, true);
  6888. option("workTime", 100);
  6889. option("workDelay", 100);
  6890. option("flattenSpans", true, resetModeState, true);
  6891. option("addModeClass", false, resetModeState, true);
  6892. option("pollInterval", 100);
  6893. option("undoDepth", 200, function(cm, val){cm.doc.history.undoDepth = val;});
  6894. option("historyEventDelay", 1250);
  6895. option("viewportMargin", 10, function(cm){cm.refresh();}, true);
  6896. option("maxHighlightLength", 10000, resetModeState, true);
  6897. option("moveInputWithCursor", true, function(cm, val) {
  6898. if (!val) cm.display.input.resetPosition();
  6899. });
  6900. option("tabindex", null, function(cm, val) {
  6901. cm.display.input.getField().tabIndex = val || "";
  6902. });
  6903. option("autofocus", null);
  6904. // MODE DEFINITION AND QUERYING
  6905. // Known modes, by name and by MIME
  6906. var modes = CodeMirror.modes = {}, mimeModes = CodeMirror.mimeModes = {};
  6907. // Extra arguments are stored as the mode's dependencies, which is
  6908. // used by (legacy) mechanisms like loadmode.js to automatically
  6909. // load a mode. (Preferred mechanism is the require/define calls.)
  6910. CodeMirror.defineMode = function(name, mode) {
  6911. if (!CodeMirror.defaults.mode && name != "null") CodeMirror.defaults.mode = name;
  6912. if (arguments.length > 2)
  6913. mode.dependencies = Array.prototype.slice.call(arguments, 2);
  6914. modes[name] = mode;
  6915. };
  6916. CodeMirror.defineMIME = function(mime, spec) {
  6917. mimeModes[mime] = spec;
  6918. };
  6919. // Given a MIME type, a {name, ...options} config object, or a name
  6920. // string, return a mode config object.
  6921. CodeMirror.resolveMode = function(spec) {
  6922. if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) {
  6923. spec = mimeModes[spec];
  6924. } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) {
  6925. var found = mimeModes[spec.name];
  6926. if (typeof found == "string") found = {name: found};
  6927. spec = createObj(found, spec);
  6928. spec.name = found.name;
  6929. } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) {
  6930. return CodeMirror.resolveMode("application/xml");
  6931. }
  6932. if (typeof spec == "string") return {name: spec};
  6933. else return spec || {name: "null"};
  6934. };
  6935. // Given a mode spec (anything that resolveMode accepts), find and
  6936. // initialize an actual mode object.
  6937. CodeMirror.getMode = function(options, spec) {
  6938. var spec = CodeMirror.resolveMode(spec);
  6939. var mfactory = modes[spec.name];
  6940. if (!mfactory) return CodeMirror.getMode(options, "text/plain");
  6941. var modeObj = mfactory(options, spec);
  6942. if (modeExtensions.hasOwnProperty(spec.name)) {
  6943. var exts = modeExtensions[spec.name];
  6944. for (var prop in exts) {
  6945. if (!exts.hasOwnProperty(prop)) continue;
  6946. if (modeObj.hasOwnProperty(prop)) modeObj["_" + prop] = modeObj[prop];
  6947. modeObj[prop] = exts[prop];
  6948. }
  6949. }
  6950. modeObj.name = spec.name;
  6951. if (spec.helperType) modeObj.helperType = spec.helperType;
  6952. if (spec.modeProps) for (var prop in spec.modeProps)
  6953. modeObj[prop] = spec.modeProps[prop];
  6954. return modeObj;
  6955. };
  6956. // Minimal default mode.
  6957. CodeMirror.defineMode("null", function() {
  6958. return {token: function(stream) {stream.skipToEnd();}};
  6959. });
  6960. CodeMirror.defineMIME("text/plain", "null");
  6961. // This can be used to attach properties to mode objects from
  6962. // outside the actual mode definition.
  6963. var modeExtensions = CodeMirror.modeExtensions = {};
  6964. CodeMirror.extendMode = function(mode, properties) {
  6965. var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {});
  6966. copyObj(properties, exts);
  6967. };
  6968. // EXTENSIONS
  6969. CodeMirror.defineExtension = function(name, func) {
  6970. CodeMirror.prototype[name] = func;
  6971. };
  6972. CodeMirror.defineDocExtension = function(name, func) {
  6973. Doc.prototype[name] = func;
  6974. };
  6975. CodeMirror.defineOption = option;
  6976. var initHooks = [];
  6977. CodeMirror.defineInitHook = function(f) {initHooks.push(f);};
  6978. var helpers = CodeMirror.helpers = {};
  6979. CodeMirror.registerHelper = function(type, name, value) {
  6980. if (!helpers.hasOwnProperty(type)) helpers[type] = CodeMirror[type] = {_global: []};
  6981. helpers[type][name] = value;
  6982. };
  6983. CodeMirror.registerGlobalHelper = function(type, name, predicate, value) {
  6984. CodeMirror.registerHelper(type, name, value);
  6985. helpers[type]._global.push({pred: predicate, val: value});
  6986. };
  6987. // MODE STATE HANDLING
  6988. // Utility functions for working with state. Exported because nested
  6989. // modes need to do this for their inner modes.
  6990. var copyState = CodeMirror.copyState = function(mode, state) {
  6991. if (state === true) return state;
  6992. if (mode.copyState) return mode.copyState(state);
  6993. var nstate = {};
  6994. for (var n in state) {
  6995. var val = state[n];
  6996. if (val instanceof Array) val = val.concat([]);
  6997. nstate[n] = val;
  6998. }
  6999. return nstate;
  7000. };
  7001. var startState = CodeMirror.startState = function(mode, a1, a2) {
  7002. return mode.startState ? mode.startState(a1, a2) : true;
  7003. };
  7004. // Given a mode and a state (for that mode), find the inner mode and
  7005. // state at the position that the state refers to.
  7006. CodeMirror.innerMode = function(mode, state) {
  7007. while (mode.innerMode) {
  7008. var info = mode.innerMode(state);
  7009. if (!info || info.mode == mode) break;
  7010. state = info.state;
  7011. mode = info.mode;
  7012. }
  7013. return info || {mode: mode, state: state};
  7014. };
  7015. // STANDARD COMMANDS
  7016. // Commands are parameter-less actions that can be performed on an
  7017. // editor, mostly used for keybindings.
  7018. var commands = CodeMirror.commands = {
  7019. selectAll: function(cm) {cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll);},
  7020. singleSelection: function(cm) {
  7021. cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll);
  7022. },
  7023. killLine: function(cm) {
  7024. deleteNearSelection(cm, function(range) {
  7025. if (range.empty()) {
  7026. var len = getLine(cm.doc, range.head.line).text.length;
  7027. if (range.head.ch == len && range.head.line < cm.lastLine())
  7028. return {from: range.head, to: Pos(range.head.line + 1, 0)};
  7029. else
  7030. return {from: range.head, to: Pos(range.head.line, len)};
  7031. } else {
  7032. return {from: range.from(), to: range.to()};
  7033. }
  7034. });
  7035. },
  7036. deleteLine: function(cm) {
  7037. deleteNearSelection(cm, function(range) {
  7038. return {from: Pos(range.from().line, 0),
  7039. to: clipPos(cm.doc, Pos(range.to().line + 1, 0))};
  7040. });
  7041. },
  7042. delLineLeft: function(cm) {
  7043. deleteNearSelection(cm, function(range) {
  7044. return {from: Pos(range.from().line, 0), to: range.from()};
  7045. });
  7046. },
  7047. delWrappedLineLeft: function(cm) {
  7048. deleteNearSelection(cm, function(range) {
  7049. var top = cm.charCoords(range.head, "div").top + 5;
  7050. var leftPos = cm.coordsChar({left: 0, top: top}, "div");
  7051. return {from: leftPos, to: range.from()};
  7052. });
  7053. },
  7054. delWrappedLineRight: function(cm) {
  7055. deleteNearSelection(cm, function(range) {
  7056. var top = cm.charCoords(range.head, "div").top + 5;
  7057. var rightPos = cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div");
  7058. return {from: range.from(), to: rightPos };
  7059. });
  7060. },
  7061. undo: function(cm) {cm.undo();},
  7062. redo: function(cm) {cm.redo();},
  7063. undoSelection: function(cm) {cm.undoSelection();},
  7064. redoSelection: function(cm) {cm.redoSelection();},
  7065. goDocStart: function(cm) {cm.extendSelection(Pos(cm.firstLine(), 0));},
  7066. goDocEnd: function(cm) {cm.extendSelection(Pos(cm.lastLine()));},
  7067. goLineStart: function(cm) {
  7068. cm.extendSelectionsBy(function(range) { return lineStart(cm, range.head.line); },
  7069. {origin: "+move", bias: 1});
  7070. },
  7071. goLineStartSmart: function(cm) {
  7072. cm.extendSelectionsBy(function(range) {
  7073. return lineStartSmart(cm, range.head);
  7074. }, {origin: "+move", bias: 1});
  7075. },
  7076. goLineEnd: function(cm) {
  7077. cm.extendSelectionsBy(function(range) { return lineEnd(cm, range.head.line); },
  7078. {origin: "+move", bias: -1});
  7079. },
  7080. goLineRight: function(cm) {
  7081. cm.extendSelectionsBy(function(range) {
  7082. var top = cm.charCoords(range.head, "div").top + 5;
  7083. return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div");
  7084. }, sel_move);
  7085. },
  7086. goLineLeft: function(cm) {
  7087. cm.extendSelectionsBy(function(range) {
  7088. var top = cm.charCoords(range.head, "div").top + 5;
  7089. return cm.coordsChar({left: 0, top: top}, "div");
  7090. }, sel_move);
  7091. },
  7092. goLineLeftSmart: function(cm) {
  7093. cm.extendSelectionsBy(function(range) {
  7094. var top = cm.charCoords(range.head, "div").top + 5;
  7095. var pos = cm.coordsChar({left: 0, top: top}, "div");
  7096. if (pos.ch < cm.getLine(pos.line).search(/\S/)) return lineStartSmart(cm, range.head);
  7097. return pos;
  7098. }, sel_move);
  7099. },
  7100. goLineUp: function(cm) {cm.moveV(-1, "line");},
  7101. goLineDown: function(cm) {cm.moveV(1, "line");},
  7102. goPageUp: function(cm) {cm.moveV(-1, "page");},
  7103. goPageDown: function(cm) {cm.moveV(1, "page");},
  7104. goCharLeft: function(cm) {cm.moveH(-1, "char");},
  7105. goCharRight: function(cm) {cm.moveH(1, "char");},
  7106. goColumnLeft: function(cm) {cm.moveH(-1, "column");},
  7107. goColumnRight: function(cm) {cm.moveH(1, "column");},
  7108. goWordLeft: function(cm) {cm.moveH(-1, "word");},
  7109. goGroupRight: function(cm) {cm.moveH(1, "group");},
  7110. goGroupLeft: function(cm) {cm.moveH(-1, "group");},
  7111. goWordRight: function(cm) {cm.moveH(1, "word");},
  7112. delCharBefore: function(cm) {cm.deleteH(-1, "char");},
  7113. delCharAfter: function(cm) {cm.deleteH(1, "char");},
  7114. delWordBefore: function(cm) {cm.deleteH(-1, "word");},
  7115. delWordAfter: function(cm) {cm.deleteH(1, "word");},
  7116. delGroupBefore: function(cm) {cm.deleteH(-1, "group");},
  7117. delGroupAfter: function(cm) {cm.deleteH(1, "group");},
  7118. indentAuto: function(cm) {cm.indentSelection("smart");},
  7119. indentMore: function(cm) {cm.indentSelection("add");},
  7120. indentLess: function(cm) {cm.indentSelection("subtract");},
  7121. insertTab: function(cm) {cm.replaceSelection("\t");},
  7122. insertSoftTab: function(cm) {
  7123. var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize;
  7124. for (var i = 0; i < ranges.length; i++) {
  7125. var pos = ranges[i].from();
  7126. var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize);
  7127. spaces.push(spaceStr(tabSize - col % tabSize));
  7128. }
  7129. cm.replaceSelections(spaces);
  7130. },
  7131. defaultTab: function(cm) {
  7132. if (cm.somethingSelected()) cm.indentSelection("add");
  7133. else cm.execCommand("insertTab");
  7134. },
  7135. transposeChars: function(cm) {
  7136. runInOp(cm, function() {
  7137. var ranges = cm.listSelections(), newSel = [];
  7138. for (var i = 0; i < ranges.length; i++) {
  7139. var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text;
  7140. if (line) {
  7141. if (cur.ch == line.length) cur = new Pos(cur.line, cur.ch - 1);
  7142. if (cur.ch > 0) {
  7143. cur = new Pos(cur.line, cur.ch + 1);
  7144. cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2),
  7145. Pos(cur.line, cur.ch - 2), cur, "+transpose");
  7146. } else if (cur.line > cm.doc.first) {
  7147. var prev = getLine(cm.doc, cur.line - 1).text;
  7148. if (prev)
  7149. cm.replaceRange(line.charAt(0) + cm.doc.lineSeparator() +
  7150. prev.charAt(prev.length - 1),
  7151. Pos(cur.line - 1, prev.length - 1), Pos(cur.line, 1), "+transpose");
  7152. }
  7153. }
  7154. newSel.push(new Range(cur, cur));
  7155. }
  7156. cm.setSelections(newSel);
  7157. });
  7158. },
  7159. newlineAndIndent: function(cm) {
  7160. runInOp(cm, function() {
  7161. var len = cm.listSelections().length;
  7162. for (var i = 0; i < len; i++) {
  7163. var range = cm.listSelections()[i];
  7164. cm.replaceRange(cm.doc.lineSeparator(), range.anchor, range.head, "+input");
  7165. cm.indentLine(range.from().line + 1, null, true);
  7166. }
  7167. ensureCursorVisible(cm);
  7168. });
  7169. },
  7170. openLine: function(cm) {cm.replaceSelection("\n", "start")},
  7171. toggleOverwrite: function(cm) {cm.toggleOverwrite();}
  7172. };
  7173. // STANDARD KEYMAPS
  7174. var keyMap = CodeMirror.keyMap = {};
  7175. keyMap.basic = {
  7176. "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown",
  7177. "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown",
  7178. "Delete": "delCharAfter", "Backspace": "delCharBefore", "Shift-Backspace": "delCharBefore",
  7179. "Tab": "defaultTab", "Shift-Tab": "indentAuto",
  7180. "Enter": "newlineAndIndent", "Insert": "toggleOverwrite",
  7181. "Esc": "singleSelection"
  7182. };
  7183. // Note that the save and find-related commands aren't defined by
  7184. // default. User code or addons can define them. Unknown commands
  7185. // are simply ignored.
  7186. keyMap.pcDefault = {
  7187. "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo",
  7188. "Ctrl-Home": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Up": "goLineUp", "Ctrl-Down": "goLineDown",
  7189. "Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd",
  7190. "Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find",
  7191. "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll",
  7192. "Ctrl-[": "indentLess", "Ctrl-]": "indentMore",
  7193. "Ctrl-U": "undoSelection", "Shift-Ctrl-U": "redoSelection", "Alt-U": "redoSelection",
  7194. fallthrough: "basic"
  7195. };
  7196. // Very basic readline/emacs-style bindings, which are standard on Mac.
  7197. keyMap.emacsy = {
  7198. "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown",
  7199. "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd",
  7200. "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp", "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore",
  7201. "Alt-D": "delWordAfter", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars",
  7202. "Ctrl-O": "openLine"
  7203. };
  7204. keyMap.macDefault = {
  7205. "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo",
  7206. "Cmd-Home": "goDocStart", "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft",
  7207. "Alt-Right": "goGroupRight", "Cmd-Left": "goLineLeft", "Cmd-Right": "goLineRight", "Alt-Backspace": "delGroupBefore",
  7208. "Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find",
  7209. "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll",
  7210. "Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delWrappedLineLeft", "Cmd-Delete": "delWrappedLineRight",
  7211. "Cmd-U": "undoSelection", "Shift-Cmd-U": "redoSelection", "Ctrl-Up": "goDocStart", "Ctrl-Down": "goDocEnd",
  7212. fallthrough: ["basic", "emacsy"]
  7213. };
  7214. keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault;
  7215. // KEYMAP DISPATCH
  7216. function normalizeKeyName(name) {
  7217. var parts = name.split(/-(?!$)/), name = parts[parts.length - 1];
  7218. var alt, ctrl, shift, cmd;
  7219. for (var i = 0; i < parts.length - 1; i++) {
  7220. var mod = parts[i];
  7221. if (/^(cmd|meta|m)$/i.test(mod)) cmd = true;
  7222. else if (/^a(lt)?$/i.test(mod)) alt = true;
  7223. else if (/^(c|ctrl|control)$/i.test(mod)) ctrl = true;
  7224. else if (/^s(hift)$/i.test(mod)) shift = true;
  7225. else throw new Error("Unrecognized modifier name: " + mod);
  7226. }
  7227. if (alt) name = "Alt-" + name;
  7228. if (ctrl) name = "Ctrl-" + name;
  7229. if (cmd) name = "Cmd-" + name;
  7230. if (shift) name = "Shift-" + name;
  7231. return name;
  7232. }
  7233. // This is a kludge to keep keymaps mostly working as raw objects
  7234. // (backwards compatibility) while at the same time support features
  7235. // like normalization and multi-stroke key bindings. It compiles a
  7236. // new normalized keymap, and then updates the old object to reflect
  7237. // this.
  7238. CodeMirror.normalizeKeyMap = function(keymap) {
  7239. var copy = {};
  7240. for (var keyname in keymap) if (keymap.hasOwnProperty(keyname)) {
  7241. var value = keymap[keyname];
  7242. if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) continue;
  7243. if (value == "...") { delete keymap[keyname]; continue; }
  7244. var keys = map(keyname.split(" "), normalizeKeyName);
  7245. for (var i = 0; i < keys.length; i++) {
  7246. var val, name;
  7247. if (i == keys.length - 1) {
  7248. name = keys.join(" ");
  7249. val = value;
  7250. } else {
  7251. name = keys.slice(0, i + 1).join(" ");
  7252. val = "...";
  7253. }
  7254. var prev = copy[name];
  7255. if (!prev) copy[name] = val;
  7256. else if (prev != val) throw new Error("Inconsistent bindings for " + name);
  7257. }
  7258. delete keymap[keyname];
  7259. }
  7260. for (var prop in copy) keymap[prop] = copy[prop];
  7261. return keymap;
  7262. };
  7263. var lookupKey = CodeMirror.lookupKey = function(key, map, handle, context) {
  7264. map = getKeyMap(map);
  7265. var found = map.call ? map.call(key, context) : map[key];
  7266. if (found === false) return "nothing";
  7267. if (found === "...") return "multi";
  7268. if (found != null && handle(found)) return "handled";
  7269. if (map.fallthrough) {
  7270. if (Object.prototype.toString.call(map.fallthrough) != "[object Array]")
  7271. return lookupKey(key, map.fallthrough, handle, context);
  7272. for (var i = 0; i < map.fallthrough.length; i++) {
  7273. var result = lookupKey(key, map.fallthrough[i], handle, context);
  7274. if (result) return result;
  7275. }
  7276. }
  7277. };
  7278. // Modifier key presses don't count as 'real' key presses for the
  7279. // purpose of keymap fallthrough.
  7280. var isModifierKey = CodeMirror.isModifierKey = function(value) {
  7281. var name = typeof value == "string" ? value : keyNames[value.keyCode];
  7282. return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod";
  7283. };
  7284. // Look up the name of a key as indicated by an event object.
  7285. var keyName = CodeMirror.keyName = function(event, noShift) {
  7286. if (presto && event.keyCode == 34 && event["char"]) return false;
  7287. var base = keyNames[event.keyCode], name = base;
  7288. if (name == null || event.altGraphKey) return false;
  7289. if (event.altKey && base != "Alt") name = "Alt-" + name;
  7290. if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != "Ctrl") name = "Ctrl-" + name;
  7291. if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != "Cmd") name = "Cmd-" + name;
  7292. if (!noShift && event.shiftKey && base != "Shift") name = "Shift-" + name;
  7293. return name;
  7294. };
  7295. function getKeyMap(val) {
  7296. return typeof val == "string" ? keyMap[val] : val;
  7297. }
  7298. // FROMTEXTAREA
  7299. CodeMirror.fromTextArea = function(textarea, options) {
  7300. options = options ? copyObj(options) : {};
  7301. options.value = textarea.value;
  7302. if (!options.tabindex && textarea.tabIndex)
  7303. options.tabindex = textarea.tabIndex;
  7304. if (!options.placeholder && textarea.placeholder)
  7305. options.placeholder = textarea.placeholder;
  7306. // Set autofocus to true if this textarea is focused, or if it has
  7307. // autofocus and no other element is focused.
  7308. if (options.autofocus == null) {
  7309. var hasFocus = activeElt();
  7310. options.autofocus = hasFocus == textarea ||
  7311. textarea.getAttribute("autofocus") != null && hasFocus == document.body;
  7312. }
  7313. function save() {textarea.value = cm.getValue();}
  7314. if (textarea.form) {
  7315. on(textarea.form, "submit", save);
  7316. // Deplorable hack to make the submit method do the right thing.
  7317. if (!options.leaveSubmitMethodAlone) {
  7318. var form = textarea.form, realSubmit = form.submit;
  7319. try {
  7320. var wrappedSubmit = form.submit = function() {
  7321. save();
  7322. form.submit = realSubmit;
  7323. form.submit();
  7324. form.submit = wrappedSubmit;
  7325. };
  7326. } catch(e) {}
  7327. }
  7328. }
  7329. options.finishInit = function(cm) {
  7330. cm.save = save;
  7331. cm.getTextArea = function() { return textarea; };
  7332. cm.toTextArea = function() {
  7333. cm.toTextArea = isNaN; // Prevent this from being ran twice
  7334. save();
  7335. textarea.parentNode.removeChild(cm.getWrapperElement());
  7336. textarea.style.display = "";
  7337. if (textarea.form) {
  7338. off(textarea.form, "submit", save);
  7339. if (typeof textarea.form.submit == "function")
  7340. textarea.form.submit = realSubmit;
  7341. }
  7342. };
  7343. };
  7344. textarea.style.display = "none";
  7345. var cm = CodeMirror(function(node) {
  7346. textarea.parentNode.insertBefore(node, textarea.nextSibling);
  7347. }, options);
  7348. return cm;
  7349. };
  7350. // STRING STREAM
  7351. // Fed to the mode parsers, provides helper functions to make
  7352. // parsers more succinct.
  7353. var StringStream = CodeMirror.StringStream = function(string, tabSize) {
  7354. this.pos = this.start = 0;
  7355. this.string = string;
  7356. this.tabSize = tabSize || 8;
  7357. this.lastColumnPos = this.lastColumnValue = 0;
  7358. this.lineStart = 0;
  7359. };
  7360. StringStream.prototype = {
  7361. eol: function() {return this.pos >= this.string.length;},
  7362. sol: function() {return this.pos == this.lineStart;},
  7363. peek: function() {return this.string.charAt(this.pos) || undefined;},
  7364. next: function() {
  7365. if (this.pos < this.string.length)
  7366. return this.string.charAt(this.pos++);
  7367. },
  7368. eat: function(match) {
  7369. var ch = this.string.charAt(this.pos);
  7370. if (typeof match == "string") var ok = ch == match;
  7371. else var ok = ch && (match.test ? match.test(ch) : match(ch));
  7372. if (ok) {++this.pos; return ch;}
  7373. },
  7374. eatWhile: function(match) {
  7375. var start = this.pos;
  7376. while (this.eat(match)){}
  7377. return this.pos > start;
  7378. },
  7379. eatSpace: function() {
  7380. var start = this.pos;
  7381. while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) ++this.pos;
  7382. return this.pos > start;
  7383. },
  7384. skipToEnd: function() {this.pos = this.string.length;},
  7385. skipTo: function(ch) {
  7386. var found = this.string.indexOf(ch, this.pos);
  7387. if (found > -1) {this.pos = found; return true;}
  7388. },
  7389. backUp: function(n) {this.pos -= n;},
  7390. column: function() {
  7391. if (this.lastColumnPos < this.start) {
  7392. this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue);
  7393. this.lastColumnPos = this.start;
  7394. }
  7395. return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0);
  7396. },
  7397. indentation: function() {
  7398. return countColumn(this.string, null, this.tabSize) -
  7399. (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0);
  7400. },
  7401. match: function(pattern, consume, caseInsensitive) {
  7402. if (typeof pattern == "string") {
  7403. var cased = function(str) {return caseInsensitive ? str.toLowerCase() : str;};
  7404. var substr = this.string.substr(this.pos, pattern.length);
  7405. if (cased(substr) == cased(pattern)) {
  7406. if (consume !== false) this.pos += pattern.length;
  7407. return true;
  7408. }
  7409. } else {
  7410. var match = this.string.slice(this.pos).match(pattern);
  7411. if (match && match.index > 0) return null;
  7412. if (match && consume !== false) this.pos += match[0].length;
  7413. return match;
  7414. }
  7415. },
  7416. current: function(){return this.string.slice(this.start, this.pos);},
  7417. hideFirstChars: function(n, inner) {
  7418. this.lineStart += n;
  7419. try { return inner(); }
  7420. finally { this.lineStart -= n; }
  7421. }
  7422. };
  7423. // TEXTMARKERS
  7424. // Created with markText and setBookmark methods. A TextMarker is a
  7425. // handle that can be used to clear or find a marked position in the
  7426. // document. Line objects hold arrays (markedSpans) containing
  7427. // {from, to, marker} object pointing to such marker objects, and
  7428. // indicating that such a marker is present on that line. Multiple
  7429. // lines may point to the same marker when it spans across lines.
  7430. // The spans will have null for their from/to properties when the
  7431. // marker continues beyond the start/end of the line. Markers have
  7432. // links back to the lines they currently touch.
  7433. var nextMarkerId = 0;
  7434. var TextMarker = CodeMirror.TextMarker = function(doc, type) {
  7435. this.lines = [];
  7436. this.type = type;
  7437. this.doc = doc;
  7438. this.id = ++nextMarkerId;
  7439. };
  7440. eventMixin(TextMarker);
  7441. // Clear the marker.
  7442. TextMarker.prototype.clear = function() {
  7443. if (this.explicitlyCleared) return;
  7444. var cm = this.doc.cm, withOp = cm && !cm.curOp;
  7445. if (withOp) startOperation(cm);
  7446. if (hasHandler(this, "clear")) {
  7447. var found = this.find();
  7448. if (found) signalLater(this, "clear", found.from, found.to);
  7449. }
  7450. var min = null, max = null;
  7451. for (var i = 0; i < this.lines.length; ++i) {
  7452. var line = this.lines[i];
  7453. var span = getMarkedSpanFor(line.markedSpans, this);
  7454. if (cm && !this.collapsed) regLineChange(cm, lineNo(line), "text");
  7455. else if (cm) {
  7456. if (span.to != null) max = lineNo(line);
  7457. if (span.from != null) min = lineNo(line);
  7458. }
  7459. line.markedSpans = removeMarkedSpan(line.markedSpans, span);
  7460. if (span.from == null && this.collapsed && !lineIsHidden(this.doc, line) && cm)
  7461. updateLineHeight(line, textHeight(cm.display));
  7462. }
  7463. if (cm && this.collapsed && !cm.options.lineWrapping) for (var i = 0; i < this.lines.length; ++i) {
  7464. var visual = visualLine(this.lines[i]), len = lineLength(visual);
  7465. if (len > cm.display.maxLineLength) {
  7466. cm.display.maxLine = visual;
  7467. cm.display.maxLineLength = len;
  7468. cm.display.maxLineChanged = true;
  7469. }
  7470. }
  7471. if (min != null && cm && this.collapsed) regChange(cm, min, max + 1);
  7472. this.lines.length = 0;
  7473. this.explicitlyCleared = true;
  7474. if (this.atomic && this.doc.cantEdit) {
  7475. this.doc.cantEdit = false;
  7476. if (cm) reCheckSelection(cm.doc);
  7477. }
  7478. if (cm) signalLater(cm, "markerCleared", cm, this);
  7479. if (withOp) endOperation(cm);
  7480. if (this.parent) this.parent.clear();
  7481. };
  7482. // Find the position of the marker in the document. Returns a {from,
  7483. // to} object by default. Side can be passed to get a specific side
  7484. // -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the
  7485. // Pos objects returned contain a line object, rather than a line
  7486. // number (used to prevent looking up the same line twice).
  7487. TextMarker.prototype.find = function(side, lineObj) {
  7488. if (side == null && this.type == "bookmark") side = 1;
  7489. var from, to;
  7490. for (var i = 0; i < this.lines.length; ++i) {
  7491. var line = this.lines[i];
  7492. var span = getMarkedSpanFor(line.markedSpans, this);
  7493. if (span.from != null) {
  7494. from = Pos(lineObj ? line : lineNo(line), span.from);
  7495. if (side == -1) return from;
  7496. }
  7497. if (span.to != null) {
  7498. to = Pos(lineObj ? line : lineNo(line), span.to);
  7499. if (side == 1) return to;
  7500. }
  7501. }
  7502. return from && {from: from, to: to};
  7503. };
  7504. // Signals that the marker's widget changed, and surrounding layout
  7505. // should be recomputed.
  7506. TextMarker.prototype.changed = function() {
  7507. var pos = this.find(-1, true), widget = this, cm = this.doc.cm;
  7508. if (!pos || !cm) return;
  7509. runInOp(cm, function() {
  7510. var line = pos.line, lineN = lineNo(pos.line);
  7511. var view = findViewForLine(cm, lineN);
  7512. if (view) {
  7513. clearLineMeasurementCacheFor(view);
  7514. cm.curOp.selectionChanged = cm.curOp.forceUpdate = true;
  7515. }
  7516. cm.curOp.updateMaxLine = true;
  7517. if (!lineIsHidden(widget.doc, line) && widget.height != null) {
  7518. var oldHeight = widget.height;
  7519. widget.height = null;
  7520. var dHeight = widgetHeight(widget) - oldHeight;
  7521. if (dHeight)
  7522. updateLineHeight(line, line.height + dHeight);
  7523. }
  7524. });
  7525. };
  7526. TextMarker.prototype.attachLine = function(line) {
  7527. if (!this.lines.length && this.doc.cm) {
  7528. var op = this.doc.cm.curOp;
  7529. if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1)
  7530. (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this);
  7531. }
  7532. this.lines.push(line);
  7533. };
  7534. TextMarker.prototype.detachLine = function(line) {
  7535. this.lines.splice(indexOf(this.lines, line), 1);
  7536. if (!this.lines.length && this.doc.cm) {
  7537. var op = this.doc.cm.curOp;
  7538. (op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this);
  7539. }
  7540. };
  7541. // Collapsed markers have unique ids, in order to be able to order
  7542. // them, which is needed for uniquely determining an outer marker
  7543. // when they overlap (they may nest, but not partially overlap).
  7544. var nextMarkerId = 0;
  7545. // Create a marker, wire it up to the right lines, and
  7546. function markText(doc, from, to, options, type) {
  7547. // Shared markers (across linked documents) are handled separately
  7548. // (markTextShared will call out to this again, once per
  7549. // document).
  7550. if (options && options.shared) return markTextShared(doc, from, to, options, type);
  7551. // Ensure we are in an operation.
  7552. if (doc.cm && !doc.cm.curOp) return operation(doc.cm, markText)(doc, from, to, options, type);
  7553. var marker = new TextMarker(doc, type), diff = cmp(from, to);
  7554. if (options) copyObj(options, marker, false);
  7555. // Don't connect empty markers unless clearWhenEmpty is false
  7556. if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false)
  7557. return marker;
  7558. if (marker.replacedWith) {
  7559. // Showing up as a widget implies collapsed (widget replaces text)
  7560. marker.collapsed = true;
  7561. marker.widgetNode = elt("span", [marker.replacedWith], "CodeMirror-widget");
  7562. if (!options.handleMouseEvents) marker.widgetNode.setAttribute("cm-ignore-events", "true");
  7563. if (options.insertLeft) marker.widgetNode.insertLeft = true;
  7564. }
  7565. if (marker.collapsed) {
  7566. if (conflictingCollapsedRange(doc, from.line, from, to, marker) ||
  7567. from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker))
  7568. throw new Error("Inserting collapsed marker partially overlapping an existing one");
  7569. sawCollapsedSpans = true;
  7570. }
  7571. if (marker.addToHistory)
  7572. addChangeToHistory(doc, {from: from, to: to, origin: "markText"}, doc.sel, NaN);
  7573. var curLine = from.line, cm = doc.cm, updateMaxLine;
  7574. doc.iter(curLine, to.line + 1, function(line) {
  7575. if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine)
  7576. updateMaxLine = true;
  7577. if (marker.collapsed && curLine != from.line) updateLineHeight(line, 0);
  7578. addMarkedSpan(line, new MarkedSpan(marker,
  7579. curLine == from.line ? from.ch : null,
  7580. curLine == to.line ? to.ch : null));
  7581. ++curLine;
  7582. });
  7583. // lineIsHidden depends on the presence of the spans, so needs a second pass
  7584. if (marker.collapsed) doc.iter(from.line, to.line + 1, function(line) {
  7585. if (lineIsHidden(doc, line)) updateLineHeight(line, 0);
  7586. });
  7587. if (marker.clearOnEnter) on(marker, "beforeCursorEnter", function() { marker.clear(); });
  7588. if (marker.readOnly) {
  7589. sawReadOnlySpans = true;
  7590. if (doc.history.done.length || doc.history.undone.length)
  7591. doc.clearHistory();
  7592. }
  7593. if (marker.collapsed) {
  7594. marker.id = ++nextMarkerId;
  7595. marker.atomic = true;
  7596. }
  7597. if (cm) {
  7598. // Sync editor state
  7599. if (updateMaxLine) cm.curOp.updateMaxLine = true;
  7600. if (marker.collapsed)
  7601. regChange(cm, from.line, to.line + 1);
  7602. else if (marker.className || marker.title || marker.startStyle || marker.endStyle || marker.css)
  7603. for (var i = from.line; i <= to.line; i++) regLineChange(cm, i, "text");
  7604. if (marker.atomic) reCheckSelection(cm.doc);
  7605. signalLater(cm, "markerAdded", cm, marker);
  7606. }
  7607. return marker;
  7608. }
  7609. // SHARED TEXTMARKERS
  7610. // A shared marker spans multiple linked documents. It is
  7611. // implemented as a meta-marker-object controlling multiple normal
  7612. // markers.
  7613. var SharedTextMarker = CodeMirror.SharedTextMarker = function(markers, primary) {
  7614. this.markers = markers;
  7615. this.primary = primary;
  7616. for (var i = 0; i < markers.length; ++i)
  7617. markers[i].parent = this;
  7618. };
  7619. eventMixin(SharedTextMarker);
  7620. SharedTextMarker.prototype.clear = function() {
  7621. if (this.explicitlyCleared) return;
  7622. this.explicitlyCleared = true;
  7623. for (var i = 0; i < this.markers.length; ++i)
  7624. this.markers[i].clear();
  7625. signalLater(this, "clear");
  7626. };
  7627. SharedTextMarker.prototype.find = function(side, lineObj) {
  7628. return this.primary.find(side, lineObj);
  7629. };
  7630. function markTextShared(doc, from, to, options, type) {
  7631. options = copyObj(options);
  7632. options.shared = false;
  7633. var markers = [markText(doc, from, to, options, type)], primary = markers[0];
  7634. var widget = options.widgetNode;
  7635. linkedDocs(doc, function(doc) {
  7636. if (widget) options.widgetNode = widget.cloneNode(true);
  7637. markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type));
  7638. for (var i = 0; i < doc.linked.length; ++i)
  7639. if (doc.linked[i].isParent) return;
  7640. primary = lst(markers);
  7641. });
  7642. return new SharedTextMarker(markers, primary);
  7643. }
  7644. function findSharedMarkers(doc) {
  7645. return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())),
  7646. function(m) { return m.parent; });
  7647. }
  7648. function copySharedMarkers(doc, markers) {
  7649. for (var i = 0; i < markers.length; i++) {
  7650. var marker = markers[i], pos = marker.find();
  7651. var mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to);
  7652. if (cmp(mFrom, mTo)) {
  7653. var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type);
  7654. marker.markers.push(subMark);
  7655. subMark.parent = marker;
  7656. }
  7657. }
  7658. }
  7659. function detachSharedMarkers(markers) {
  7660. for (var i = 0; i < markers.length; i++) {
  7661. var marker = markers[i], linked = [marker.primary.doc];;
  7662. linkedDocs(marker.primary.doc, function(d) { linked.push(d); });
  7663. for (var j = 0; j < marker.markers.length; j++) {
  7664. var subMarker = marker.markers[j];
  7665. if (indexOf(linked, subMarker.doc) == -1) {
  7666. subMarker.parent = null;
  7667. marker.markers.splice(j--, 1);
  7668. }
  7669. }
  7670. }
  7671. }
  7672. // TEXTMARKER SPANS
  7673. function MarkedSpan(marker, from, to) {
  7674. this.marker = marker;
  7675. this.from = from; this.to = to;
  7676. }
  7677. // Search an array of spans for a span matching the given marker.
  7678. function getMarkedSpanFor(spans, marker) {
  7679. if (spans) for (var i = 0; i < spans.length; ++i) {
  7680. var span = spans[i];
  7681. if (span.marker == marker) return span;
  7682. }
  7683. }
  7684. // Remove a span from an array, returning undefined if no spans are
  7685. // left (we don't store arrays for lines without spans).
  7686. function removeMarkedSpan(spans, span) {
  7687. for (var r, i = 0; i < spans.length; ++i)
  7688. if (spans[i] != span) (r || (r = [])).push(spans[i]);
  7689. return r;
  7690. }
  7691. // Add a span to a line.
  7692. function addMarkedSpan(line, span) {
  7693. line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span];
  7694. span.marker.attachLine(line);
  7695. }
  7696. // Used for the algorithm that adjusts markers for a change in the
  7697. // document. These functions cut an array of spans at a given
  7698. // character position, returning an array of remaining chunks (or
  7699. // undefined if nothing remains).
  7700. function markedSpansBefore(old, startCh, isInsert) {
  7701. if (old) for (var i = 0, nw; i < old.length; ++i) {
  7702. var span = old[i], marker = span.marker;
  7703. var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh);
  7704. if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) {
  7705. var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh);
  7706. (nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to));
  7707. }
  7708. }
  7709. return nw;
  7710. }
  7711. function markedSpansAfter(old, endCh, isInsert) {
  7712. if (old) for (var i = 0, nw; i < old.length; ++i) {
  7713. var span = old[i], marker = span.marker;
  7714. var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh);
  7715. if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) {
  7716. var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh);
  7717. (nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh,
  7718. span.to == null ? null : span.to - endCh));
  7719. }
  7720. }
  7721. return nw;
  7722. }
  7723. // Given a change object, compute the new set of marker spans that
  7724. // cover the line in which the change took place. Removes spans
  7725. // entirely within the change, reconnects spans belonging to the
  7726. // same marker that appear on both sides of the change, and cuts off
  7727. // spans partially within the change. Returns an array of span
  7728. // arrays with one element for each line in (after) the change.
  7729. function stretchSpansOverChange(doc, change) {
  7730. if (change.full) return null;
  7731. var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans;
  7732. var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans;
  7733. if (!oldFirst && !oldLast) return null;
  7734. var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0;
  7735. // Get the spans that 'stick out' on both sides
  7736. var first = markedSpansBefore(oldFirst, startCh, isInsert);
  7737. var last = markedSpansAfter(oldLast, endCh, isInsert);
  7738. // Next, merge those two ends
  7739. var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0);
  7740. if (first) {
  7741. // Fix up .to properties of first
  7742. for (var i = 0; i < first.length; ++i) {
  7743. var span = first[i];
  7744. if (span.to == null) {
  7745. var found = getMarkedSpanFor(last, span.marker);
  7746. if (!found) span.to = startCh;
  7747. else if (sameLine) span.to = found.to == null ? null : found.to + offset;
  7748. }
  7749. }
  7750. }
  7751. if (last) {
  7752. // Fix up .from in last (or move them into first in case of sameLine)
  7753. for (var i = 0; i < last.length; ++i) {
  7754. var span = last[i];
  7755. if (span.to != null) span.to += offset;
  7756. if (span.from == null) {
  7757. var found = getMarkedSpanFor(first, span.marker);
  7758. if (!found) {
  7759. span.from = offset;
  7760. if (sameLine) (first || (first = [])).push(span);
  7761. }
  7762. } else {
  7763. span.from += offset;
  7764. if (sameLine) (first || (first = [])).push(span);
  7765. }
  7766. }
  7767. }
  7768. // Make sure we didn't create any zero-length spans
  7769. if (first) first = clearEmptySpans(first);
  7770. if (last && last != first) last = clearEmptySpans(last);
  7771. var newMarkers = [first];
  7772. if (!sameLine) {
  7773. // Fill gap with whole-line-spans
  7774. var gap = change.text.length - 2, gapMarkers;
  7775. if (gap > 0 && first)
  7776. for (var i = 0; i < first.length; ++i)
  7777. if (first[i].to == null)
  7778. (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i].marker, null, null));
  7779. for (var i = 0; i < gap; ++i)
  7780. newMarkers.push(gapMarkers);
  7781. newMarkers.push(last);
  7782. }
  7783. return newMarkers;
  7784. }
  7785. // Remove spans that are empty and don't have a clearWhenEmpty
  7786. // option of false.
  7787. function clearEmptySpans(spans) {
  7788. for (var i = 0; i < spans.length; ++i) {
  7789. var span = spans[i];
  7790. if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false)
  7791. spans.splice(i--, 1);
  7792. }
  7793. if (!spans.length) return null;
  7794. return spans;
  7795. }
  7796. // Used for un/re-doing changes from the history. Combines the
  7797. // result of computing the existing spans with the set of spans that
  7798. // existed in the history (so that deleting around a span and then
  7799. // undoing brings back the span).
  7800. function mergeOldSpans(doc, change) {
  7801. var old = getOldSpans(doc, change);
  7802. var stretched = stretchSpansOverChange(doc, change);
  7803. if (!old) return stretched;
  7804. if (!stretched) return old;
  7805. for (var i = 0; i < old.length; ++i) {
  7806. var oldCur = old[i], stretchCur = stretched[i];
  7807. if (oldCur && stretchCur) {
  7808. spans: for (var j = 0; j < stretchCur.length; ++j) {
  7809. var span = stretchCur[j];
  7810. for (var k = 0; k < oldCur.length; ++k)
  7811. if (oldCur[k].marker == span.marker) continue spans;
  7812. oldCur.push(span);
  7813. }
  7814. } else if (stretchCur) {
  7815. old[i] = stretchCur;
  7816. }
  7817. }
  7818. return old;
  7819. }
  7820. // Used to 'clip' out readOnly ranges when making a change.
  7821. function removeReadOnlyRanges(doc, from, to) {
  7822. var markers = null;
  7823. doc.iter(from.line, to.line + 1, function(line) {
  7824. if (line.markedSpans) for (var i = 0; i < line.markedSpans.length; ++i) {
  7825. var mark = line.markedSpans[i].marker;
  7826. if (mark.readOnly && (!markers || indexOf(markers, mark) == -1))
  7827. (markers || (markers = [])).push(mark);
  7828. }
  7829. });
  7830. if (!markers) return null;
  7831. var parts = [{from: from, to: to}];
  7832. for (var i = 0; i < markers.length; ++i) {
  7833. var mk = markers[i], m = mk.find(0);
  7834. for (var j = 0; j < parts.length; ++j) {
  7835. var p = parts[j];
  7836. if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) continue;
  7837. var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to);
  7838. if (dfrom < 0 || !mk.inclusiveLeft && !dfrom)
  7839. newParts.push({from: p.from, to: m.from});
  7840. if (dto > 0 || !mk.inclusiveRight && !dto)
  7841. newParts.push({from: m.to, to: p.to});
  7842. parts.splice.apply(parts, newParts);
  7843. j += newParts.length - 1;
  7844. }
  7845. }
  7846. return parts;
  7847. }
  7848. // Connect or disconnect spans from a line.
  7849. function detachMarkedSpans(line) {
  7850. var spans = line.markedSpans;
  7851. if (!spans) return;
  7852. for (var i = 0; i < spans.length; ++i)
  7853. spans[i].marker.detachLine(line);
  7854. line.markedSpans = null;
  7855. }
  7856. function attachMarkedSpans(line, spans) {
  7857. if (!spans) return;
  7858. for (var i = 0; i < spans.length; ++i)
  7859. spans[i].marker.attachLine(line);
  7860. line.markedSpans = spans;
  7861. }
  7862. // Helpers used when computing which overlapping collapsed span
  7863. // counts as the larger one.
  7864. function extraLeft(marker) { return marker.inclusiveLeft ? -1 : 0; }
  7865. function extraRight(marker) { return marker.inclusiveRight ? 1 : 0; }
  7866. // Returns a number indicating which of two overlapping collapsed
  7867. // spans is larger (and thus includes the other). Falls back to
  7868. // comparing ids when the spans cover exactly the same range.
  7869. function compareCollapsedMarkers(a, b) {
  7870. var lenDiff = a.lines.length - b.lines.length;
  7871. if (lenDiff != 0) return lenDiff;
  7872. var aPos = a.find(), bPos = b.find();
  7873. var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b);
  7874. if (fromCmp) return -fromCmp;
  7875. var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b);
  7876. if (toCmp) return toCmp;
  7877. return b.id - a.id;
  7878. }
  7879. // Find out whether a line ends or starts in a collapsed span. If
  7880. // so, return the marker for that span.
  7881. function collapsedSpanAtSide(line, start) {
  7882. var sps = sawCollapsedSpans && line.markedSpans, found;
  7883. if (sps) for (var sp, i = 0; i < sps.length; ++i) {
  7884. sp = sps[i];
  7885. if (sp.marker.collapsed && (start ? sp.from : sp.to) == null &&
  7886. (!found || compareCollapsedMarkers(found, sp.marker) < 0))
  7887. found = sp.marker;
  7888. }
  7889. return found;
  7890. }
  7891. function collapsedSpanAtStart(line) { return collapsedSpanAtSide(line, true); }
  7892. function collapsedSpanAtEnd(line) { return collapsedSpanAtSide(line, false); }
  7893. // Test whether there exists a collapsed span that partially
  7894. // overlaps (covers the start or end, but not both) of a new span.
  7895. // Such overlap is not allowed.
  7896. function conflictingCollapsedRange(doc, lineNo, from, to, marker) {
  7897. var line = getLine(doc, lineNo);
  7898. var sps = sawCollapsedSpans && line.markedSpans;
  7899. if (sps) for (var i = 0; i < sps.length; ++i) {
  7900. var sp = sps[i];
  7901. if (!sp.marker.collapsed) continue;
  7902. var found = sp.marker.find(0);
  7903. var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker);
  7904. var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker);
  7905. if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) continue;
  7906. if (fromCmp <= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.to, from) >= 0 : cmp(found.to, from) > 0) ||
  7907. fromCmp >= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.from, to) <= 0 : cmp(found.from, to) < 0))
  7908. return true;
  7909. }
  7910. }
  7911. // A visual line is a line as drawn on the screen. Folding, for
  7912. // example, can cause multiple logical lines to appear on the same
  7913. // visual line. This finds the start of the visual line that the
  7914. // given line is part of (usually that is the line itself).
  7915. function visualLine(line) {
  7916. var merged;
  7917. while (merged = collapsedSpanAtStart(line))
  7918. line = merged.find(-1, true).line;
  7919. return line;
  7920. }
  7921. // Returns an array of logical lines that continue the visual line
  7922. // started by the argument, or undefined if there are no such lines.
  7923. function visualLineContinued(line) {
  7924. var merged, lines;
  7925. while (merged = collapsedSpanAtEnd(line)) {
  7926. line = merged.find(1, true).line;
  7927. (lines || (lines = [])).push(line);
  7928. }
  7929. return lines;
  7930. }
  7931. // Get the line number of the start of the visual line that the
  7932. // given line number is part of.
  7933. function visualLineNo(doc, lineN) {
  7934. var line = getLine(doc, lineN), vis = visualLine(line);
  7935. if (line == vis) return lineN;
  7936. return lineNo(vis);
  7937. }
  7938. // Get the line number of the start of the next visual line after
  7939. // the given line.
  7940. function visualLineEndNo(doc, lineN) {
  7941. if (lineN > doc.lastLine()) return lineN;
  7942. var line = getLine(doc, lineN), merged;
  7943. if (!lineIsHidden(doc, line)) return lineN;
  7944. while (merged = collapsedSpanAtEnd(line))
  7945. line = merged.find(1, true).line;
  7946. return lineNo(line) + 1;
  7947. }
  7948. // Compute whether a line is hidden. Lines count as hidden when they
  7949. // are part of a visual line that starts with another line, or when
  7950. // they are entirely covered by collapsed, non-widget span.
  7951. function lineIsHidden(doc, line) {
  7952. var sps = sawCollapsedSpans && line.markedSpans;
  7953. if (sps) for (var sp, i = 0; i < sps.length; ++i) {
  7954. sp = sps[i];
  7955. if (!sp.marker.collapsed) continue;
  7956. if (sp.from == null) return true;
  7957. if (sp.marker.widgetNode) continue;
  7958. if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp))
  7959. return true;
  7960. }
  7961. }
  7962. function lineIsHiddenInner(doc, line, span) {
  7963. if (span.to == null) {
  7964. var end = span.marker.find(1, true);
  7965. return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker));
  7966. }
  7967. if (span.marker.inclusiveRight && span.to == line.text.length)
  7968. return true;
  7969. for (var sp, i = 0; i < line.markedSpans.length; ++i) {
  7970. sp = line.markedSpans[i];
  7971. if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to &&
  7972. (sp.to == null || sp.to != span.from) &&
  7973. (sp.marker.inclusiveLeft || span.marker.inclusiveRight) &&
  7974. lineIsHiddenInner(doc, line, sp)) return true;
  7975. }
  7976. }
  7977. // LINE WIDGETS
  7978. // Line widgets are block elements displayed above or below a line.
  7979. var LineWidget = CodeMirror.LineWidget = function(doc, node, options) {
  7980. if (options) for (var opt in options) if (options.hasOwnProperty(opt))
  7981. this[opt] = options[opt];
  7982. this.doc = doc;
  7983. this.node = node;
  7984. };
  7985. eventMixin(LineWidget);
  7986. function adjustScrollWhenAboveVisible(cm, line, diff) {
  7987. if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop))
  7988. addToScrollPos(cm, null, diff);
  7989. }
  7990. LineWidget.prototype.clear = function() {
  7991. var cm = this.doc.cm, ws = this.line.widgets, line = this.line, no = lineNo(line);
  7992. if (no == null || !ws) return;
  7993. for (var i = 0; i < ws.length; ++i) if (ws[i] == this) ws.splice(i--, 1);
  7994. if (!ws.length) line.widgets = null;
  7995. var height = widgetHeight(this);
  7996. updateLineHeight(line, Math.max(0, line.height - height));
  7997. if (cm) runInOp(cm, function() {
  7998. adjustScrollWhenAboveVisible(cm, line, -height);
  7999. regLineChange(cm, no, "widget");
  8000. });
  8001. };
  8002. LineWidget.prototype.changed = function() {
  8003. var oldH = this.height, cm = this.doc.cm, line = this.line;
  8004. this.height = null;
  8005. var diff = widgetHeight(this) - oldH;
  8006. if (!diff) return;
  8007. updateLineHeight(line, line.height + diff);
  8008. if (cm) runInOp(cm, function() {
  8009. cm.curOp.forceUpdate = true;
  8010. adjustScrollWhenAboveVisible(cm, line, diff);
  8011. });
  8012. };
  8013. function widgetHeight(widget) {
  8014. if (widget.height != null) return widget.height;
  8015. var cm = widget.doc.cm;
  8016. if (!cm) return 0;
  8017. if (!contains(document.body, widget.node)) {
  8018. var parentStyle = "position: relative;";
  8019. if (widget.coverGutter)
  8020. parentStyle += "margin-left: -" + cm.display.gutters.offsetWidth + "px;";
  8021. if (widget.noHScroll)
  8022. parentStyle += "width: " + cm.display.wrapper.clientWidth + "px;";
  8023. removeChildrenAndAdd(cm.display.measure, elt("div", [widget.node], null, parentStyle));
  8024. }
  8025. return widget.height = widget.node.parentNode.offsetHeight;
  8026. }
  8027. function addLineWidget(doc, handle, node, options) {
  8028. var widget = new LineWidget(doc, node, options);
  8029. var cm = doc.cm;
  8030. if (cm && widget.noHScroll) cm.display.alignWidgets = true;
  8031. changeLine(doc, handle, "widget", function(line) {
  8032. var widgets = line.widgets || (line.widgets = []);
  8033. if (widget.insertAt == null) widgets.push(widget);
  8034. else widgets.splice(Math.min(widgets.length - 1, Math.max(0, widget.insertAt)), 0, widget);
  8035. widget.line = line;
  8036. if (cm && !lineIsHidden(doc, line)) {
  8037. var aboveVisible = heightAtLine(line) < doc.scrollTop;
  8038. updateLineHeight(line, line.height + widgetHeight(widget));
  8039. if (aboveVisible) addToScrollPos(cm, null, widget.height);
  8040. cm.curOp.forceUpdate = true;
  8041. }
  8042. return true;
  8043. });
  8044. return widget;
  8045. }
  8046. // LINE DATA STRUCTURE
  8047. // Line objects. These hold state related to a line, including
  8048. // highlighting info (the styles array).
  8049. var Line = CodeMirror.Line = function(text, markedSpans, estimateHeight) {
  8050. this.text = text;
  8051. attachMarkedSpans(this, markedSpans);
  8052. this.height = estimateHeight ? estimateHeight(this) : 1;
  8053. };
  8054. eventMixin(Line);
  8055. Line.prototype.lineNo = function() { return lineNo(this); };
  8056. // Change the content (text, markers) of a line. Automatically
  8057. // invalidates cached information and tries to re-estimate the
  8058. // line's height.
  8059. function updateLine(line, text, markedSpans, estimateHeight) {
  8060. line.text = text;
  8061. if (line.stateAfter) line.stateAfter = null;
  8062. if (line.styles) line.styles = null;
  8063. if (line.order != null) line.order = null;
  8064. detachMarkedSpans(line);
  8065. attachMarkedSpans(line, markedSpans);
  8066. var estHeight = estimateHeight ? estimateHeight(line) : 1;
  8067. if (estHeight != line.height) updateLineHeight(line, estHeight);
  8068. }
  8069. // Detach a line from the document tree and its markers.
  8070. function cleanUpLine(line) {
  8071. line.parent = null;
  8072. detachMarkedSpans(line);
  8073. }
  8074. function extractLineClasses(type, output) {
  8075. if (type) for (;;) {
  8076. var lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/);
  8077. if (!lineClass) break;
  8078. type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length);
  8079. var prop = lineClass[1] ? "bgClass" : "textClass";
  8080. if (output[prop] == null)
  8081. output[prop] = lineClass[2];
  8082. else if (!(new RegExp("(?:^|\s)" + lineClass[2] + "(?:$|\s)")).test(output[prop]))
  8083. output[prop] += " " + lineClass[2];
  8084. }
  8085. return type;
  8086. }
  8087. function callBlankLine(mode, state) {
  8088. if (mode.blankLine) return mode.blankLine(state);
  8089. if (!mode.innerMode) return;
  8090. var inner = CodeMirror.innerMode(mode, state);
  8091. if (inner.mode.blankLine) return inner.mode.blankLine(inner.state);
  8092. }
  8093. function readToken(mode, stream, state, inner) {
  8094. for (var i = 0; i < 10; i++) {
  8095. if (inner) inner[0] = CodeMirror.innerMode(mode, state).mode;
  8096. var style = mode.token(stream, state);
  8097. if (stream.pos > stream.start) return style;
  8098. }
  8099. throw new Error("Mode " + mode.name + " failed to advance stream.");
  8100. }
  8101. // Utility for getTokenAt and getLineTokens
  8102. function takeToken(cm, pos, precise, asArray) {
  8103. function getObj(copy) {
  8104. return {start: stream.start, end: stream.pos,
  8105. string: stream.current(),
  8106. type: style || null,
  8107. state: copy ? copyState(doc.mode, state) : state};
  8108. }
  8109. var doc = cm.doc, mode = doc.mode, style;
  8110. pos = clipPos(doc, pos);
  8111. var line = getLine(doc, pos.line), state = getStateBefore(cm, pos.line, precise);
  8112. var stream = new StringStream(line.text, cm.options.tabSize), tokens;
  8113. if (asArray) tokens = [];
  8114. while ((asArray || stream.pos < pos.ch) && !stream.eol()) {
  8115. stream.start = stream.pos;
  8116. style = readToken(mode, stream, state);
  8117. if (asArray) tokens.push(getObj(true));
  8118. }
  8119. return asArray ? tokens : getObj();
  8120. }
  8121. // Run the given mode's parser over a line, calling f for each token.
  8122. function runMode(cm, text, mode, state, f, lineClasses, forceToEnd) {
  8123. var flattenSpans = mode.flattenSpans;
  8124. if (flattenSpans == null) flattenSpans = cm.options.flattenSpans;
  8125. var curStart = 0, curStyle = null;
  8126. var stream = new StringStream(text, cm.options.tabSize), style;
  8127. var inner = cm.options.addModeClass && [null];
  8128. if (text == "") extractLineClasses(callBlankLine(mode, state), lineClasses);
  8129. while (!stream.eol()) {
  8130. if (stream.pos > cm.options.maxHighlightLength) {
  8131. flattenSpans = false;
  8132. if (forceToEnd) processLine(cm, text, state, stream.pos);
  8133. stream.pos = text.length;
  8134. style = null;
  8135. } else {
  8136. style = extractLineClasses(readToken(mode, stream, state, inner), lineClasses);
  8137. }
  8138. if (inner) {
  8139. var mName = inner[0].name;
  8140. if (mName) style = "m-" + (style ? mName + " " + style : mName);
  8141. }
  8142. if (!flattenSpans || curStyle != style) {
  8143. while (curStart < stream.start) {
  8144. curStart = Math.min(stream.start, curStart + 50000);
  8145. f(curStart, curStyle);
  8146. }
  8147. curStyle = style;
  8148. }
  8149. stream.start = stream.pos;
  8150. }
  8151. while (curStart < stream.pos) {
  8152. // Webkit seems to refuse to render text nodes longer than 57444 characters
  8153. var pos = Math.min(stream.pos, curStart + 50000);
  8154. f(pos, curStyle);
  8155. curStart = pos;
  8156. }
  8157. }
  8158. // Compute a style array (an array starting with a mode generation
  8159. // -- for invalidation -- followed by pairs of end positions and
  8160. // style strings), which is used to highlight the tokens on the
  8161. // line.
  8162. function highlightLine(cm, line, state, forceToEnd) {
  8163. // A styles array always starts with a number identifying the
  8164. // mode/overlays that it is based on (for easy invalidation).
  8165. var st = [cm.state.modeGen], lineClasses = {};
  8166. // Compute the base array of styles
  8167. runMode(cm, line.text, cm.doc.mode, state, function(end, style) {
  8168. st.push(end, style);
  8169. }, lineClasses, forceToEnd);
  8170. // Run overlays, adjust style array.
  8171. for (var o = 0; o < cm.state.overlays.length; ++o) {
  8172. var overlay = cm.state.overlays[o], i = 1, at = 0;
  8173. runMode(cm, line.text, overlay.mode, true, function(end, style) {
  8174. var start = i;
  8175. // Ensure there's a token end at the current position, and that i points at it
  8176. while (at < end) {
  8177. var i_end = st[i];
  8178. if (i_end > end)
  8179. st.splice(i, 1, end, st[i+1], i_end);
  8180. i += 2;
  8181. at = Math.min(end, i_end);
  8182. }
  8183. if (!style) return;
  8184. if (overlay.opaque) {
  8185. st.splice(start, i - start, end, "cm-overlay " + style);
  8186. i = start + 2;
  8187. } else {
  8188. for (; start < i; start += 2) {
  8189. var cur = st[start+1];
  8190. st[start+1] = (cur ? cur + " " : "") + "cm-overlay " + style;
  8191. }
  8192. }
  8193. }, lineClasses);
  8194. }
  8195. return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null};
  8196. }
  8197. function getLineStyles(cm, line, updateFrontier) {
  8198. if (!line.styles || line.styles[0] != cm.state.modeGen) {
  8199. var state = getStateBefore(cm, lineNo(line));
  8200. var result = highlightLine(cm, line, line.text.length > cm.options.maxHighlightLength ? copyState(cm.doc.mode, state) : state);
  8201. line.stateAfter = state;
  8202. line.styles = result.styles;
  8203. if (result.classes) line.styleClasses = result.classes;
  8204. else if (line.styleClasses) line.styleClasses = null;
  8205. if (updateFrontier === cm.doc.frontier) cm.doc.frontier++;
  8206. }
  8207. return line.styles;
  8208. }
  8209. // Lightweight form of highlight -- proceed over this line and
  8210. // update state, but don't save a style array. Used for lines that
  8211. // aren't currently visible.
  8212. function processLine(cm, text, state, startAt) {
  8213. var mode = cm.doc.mode;
  8214. var stream = new StringStream(text, cm.options.tabSize);
  8215. stream.start = stream.pos = startAt || 0;
  8216. if (text == "") callBlankLine(mode, state);
  8217. while (!stream.eol()) {
  8218. readToken(mode, stream, state);
  8219. stream.start = stream.pos;
  8220. }
  8221. }
  8222. // Convert a style as returned by a mode (either null, or a string
  8223. // containing one or more styles) to a CSS style. This is cached,
  8224. // and also looks for line-wide styles.
  8225. var styleToClassCache = {}, styleToClassCacheWithMode = {};
  8226. function interpretTokenStyle(style, options) {
  8227. if (!style || /^\s*$/.test(style)) return null;
  8228. var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache;
  8229. return cache[style] ||
  8230. (cache[style] = style.replace(/\S+/g, "cm-$&"));
  8231. }
  8232. // Render the DOM representation of the text of a line. Also builds
  8233. // up a 'line map', which points at the DOM nodes that represent
  8234. // specific stretches of text, and is used by the measuring code.
  8235. // The returned object contains the DOM node, this map, and
  8236. // information about line-wide styles that were set by the mode.
  8237. function buildLineContent(cm, lineView) {
  8238. // The padding-right forces the element to have a 'border', which
  8239. // is needed on Webkit to be able to get line-level bounding
  8240. // rectangles for it (in measureChar).
  8241. var content = elt("span", null, null, webkit ? "padding-right: .1px" : null);
  8242. var builder = {pre: elt("pre", [content], "CodeMirror-line"), content: content,
  8243. col: 0, pos: 0, cm: cm,
  8244. splitSpaces: (ie || webkit) && cm.getOption("lineWrapping")};
  8245. lineView.measure = {};
  8246. // Iterate over the logical lines that make up this visual line.
  8247. for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) {
  8248. var line = i ? lineView.rest[i - 1] : lineView.line, order;
  8249. builder.pos = 0;
  8250. builder.addToken = buildToken;
  8251. // Optionally wire in some hacks into the token-rendering
  8252. // algorithm, to deal with browser quirks.
  8253. if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line)))
  8254. builder.addToken = buildTokenBadBidi(builder.addToken, order);
  8255. builder.map = [];
  8256. var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line);
  8257. insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate));
  8258. if (line.styleClasses) {
  8259. if (line.styleClasses.bgClass)
  8260. builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || "");
  8261. if (line.styleClasses.textClass)
  8262. builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || "");
  8263. }
  8264. // Ensure at least a single node is present, for measuring.
  8265. if (builder.map.length == 0)
  8266. builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure)));
  8267. // Store the map and a cache object for the current logical line
  8268. if (i == 0) {
  8269. lineView.measure.map = builder.map;
  8270. lineView.measure.cache = {};
  8271. } else {
  8272. (lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map);
  8273. (lineView.measure.caches || (lineView.measure.caches = [])).push({});
  8274. }
  8275. }
  8276. // See issue #2901
  8277. if (webkit) {
  8278. var last = builder.content.lastChild
  8279. if (/\bcm-tab\b/.test(last.className) || (last.querySelector && last.querySelector(".cm-tab")))
  8280. builder.content.className = "cm-tab-wrap-hack";
  8281. }
  8282. signal(cm, "renderLine", cm, lineView.line, builder.pre);
  8283. if (builder.pre.className)
  8284. builder.textClass = joinClasses(builder.pre.className, builder.textClass || "");
  8285. return builder;
  8286. }
  8287. function defaultSpecialCharPlaceholder(ch) {
  8288. var token = elt("span", "\u2022", "cm-invalidchar");
  8289. token.title = "\\u" + ch.charCodeAt(0).toString(16);
  8290. token.setAttribute("aria-label", token.title);
  8291. return token;
  8292. }
  8293. // Build up the DOM representation for a single token, and add it to
  8294. // the line map. Takes care to render special characters separately.
  8295. function buildToken(builder, text, style, startStyle, endStyle, title, css) {
  8296. if (!text) return;
  8297. var displayText = builder.splitSpaces ? text.replace(/ {3,}/g, splitSpaces) : text;
  8298. var special = builder.cm.state.specialChars, mustWrap = false;
  8299. if (!special.test(text)) {
  8300. builder.col += text.length;
  8301. var content = document.createTextNode(displayText);
  8302. builder.map.push(builder.pos, builder.pos + text.length, content);
  8303. if (ie && ie_version < 9) mustWrap = true;
  8304. builder.pos += text.length;
  8305. } else {
  8306. var content = document.createDocumentFragment(), pos = 0;
  8307. while (true) {
  8308. special.lastIndex = pos;
  8309. var m = special.exec(text);
  8310. var skipped = m ? m.index - pos : text.length - pos;
  8311. if (skipped) {
  8312. var txt = document.createTextNode(displayText.slice(pos, pos + skipped));
  8313. if (ie && ie_version < 9) content.appendChild(elt("span", [txt]));
  8314. else content.appendChild(txt);
  8315. builder.map.push(builder.pos, builder.pos + skipped, txt);
  8316. builder.col += skipped;
  8317. builder.pos += skipped;
  8318. }
  8319. if (!m) break;
  8320. pos += skipped + 1;
  8321. if (m[0] == "\t") {
  8322. var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize;
  8323. var txt = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab"));
  8324. txt.setAttribute("role", "presentation");
  8325. txt.setAttribute("cm-text", "\t");
  8326. builder.col += tabWidth;
  8327. } else if (m[0] == "\r" || m[0] == "\n") {
  8328. var txt = content.appendChild(elt("span", m[0] == "\r" ? "\u240d" : "\u2424", "cm-invalidchar"));
  8329. txt.setAttribute("cm-text", m[0]);
  8330. builder.col += 1;
  8331. } else {
  8332. var txt = builder.cm.options.specialCharPlaceholder(m[0]);
  8333. txt.setAttribute("cm-text", m[0]);
  8334. if (ie && ie_version < 9) content.appendChild(elt("span", [txt]));
  8335. else content.appendChild(txt);
  8336. builder.col += 1;
  8337. }
  8338. builder.map.push(builder.pos, builder.pos + 1, txt);
  8339. builder.pos++;
  8340. }
  8341. }
  8342. if (style || startStyle || endStyle || mustWrap || css) {
  8343. var fullStyle = style || "";
  8344. if (startStyle) fullStyle += startStyle;
  8345. if (endStyle) fullStyle += endStyle;
  8346. var token = elt("span", [content], fullStyle, css);
  8347. if (title) token.title = title;
  8348. return builder.content.appendChild(token);
  8349. }
  8350. builder.content.appendChild(content);
  8351. }
  8352. function splitSpaces(old) {
  8353. var out = " ";
  8354. for (var i = 0; i < old.length - 2; ++i) out += i % 2 ? " " : "\u00a0";
  8355. out += " ";
  8356. return out;
  8357. }
  8358. // Work around nonsense dimensions being reported for stretches of
  8359. // right-to-left text.
  8360. function buildTokenBadBidi(inner, order) {
  8361. return function(builder, text, style, startStyle, endStyle, title, css) {
  8362. style = style ? style + " cm-force-border" : "cm-force-border";
  8363. var start = builder.pos, end = start + text.length;
  8364. for (;;) {
  8365. // Find the part that overlaps with the start of this text
  8366. for (var i = 0; i < order.length; i++) {
  8367. var part = order[i];
  8368. if (part.to > start && part.from <= start) break;
  8369. }
  8370. if (part.to >= end) return inner(builder, text, style, startStyle, endStyle, title, css);
  8371. inner(builder, text.slice(0, part.to - start), style, startStyle, null, title, css);
  8372. startStyle = null;
  8373. text = text.slice(part.to - start);
  8374. start = part.to;
  8375. }
  8376. };
  8377. }
  8378. function buildCollapsedSpan(builder, size, marker, ignoreWidget) {
  8379. var widget = !ignoreWidget && marker.widgetNode;
  8380. if (widget) builder.map.push(builder.pos, builder.pos + size, widget);
  8381. if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) {
  8382. if (!widget)
  8383. widget = builder.content.appendChild(document.createElement("span"));
  8384. widget.setAttribute("cm-marker", marker.id);
  8385. }
  8386. if (widget) {
  8387. builder.cm.display.input.setUneditable(widget);
  8388. builder.content.appendChild(widget);
  8389. }
  8390. builder.pos += size;
  8391. }
  8392. // Outputs a number of spans to make up a line, taking highlighting
  8393. // and marked text into account.
  8394. function insertLineContent(line, builder, styles) {
  8395. var spans = line.markedSpans, allText = line.text, at = 0;
  8396. if (!spans) {
  8397. for (var i = 1; i < styles.length; i+=2)
  8398. builder.addToken(builder, allText.slice(at, at = styles[i]), interpretTokenStyle(styles[i+1], builder.cm.options));
  8399. return;
  8400. }
  8401. var len = allText.length, pos = 0, i = 1, text = "", style, css;
  8402. var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, title, collapsed;
  8403. for (;;) {
  8404. if (nextChange == pos) { // Update current marker set
  8405. spanStyle = spanEndStyle = spanStartStyle = title = css = "";
  8406. collapsed = null; nextChange = Infinity;
  8407. var foundBookmarks = [], endStyles
  8408. for (var j = 0; j < spans.length; ++j) {
  8409. var sp = spans[j], m = sp.marker;
  8410. if (m.type == "bookmark" && sp.from == pos && m.widgetNode) {
  8411. foundBookmarks.push(m);
  8412. } else if (sp.from <= pos && (sp.to == null || sp.to > pos || m.collapsed && sp.to == pos && sp.from == pos)) {
  8413. if (sp.to != null && sp.to != pos && nextChange > sp.to) {
  8414. nextChange = sp.to;
  8415. spanEndStyle = "";
  8416. }
  8417. if (m.className) spanStyle += " " + m.className;
  8418. if (m.css) css = (css ? css + ";" : "") + m.css;
  8419. if (m.startStyle && sp.from == pos) spanStartStyle += " " + m.startStyle;
  8420. if (m.endStyle && sp.to == nextChange) (endStyles || (endStyles = [])).push(m.endStyle, sp.to)
  8421. if (m.title && !title) title = m.title;
  8422. if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0))
  8423. collapsed = sp;
  8424. } else if (sp.from > pos && nextChange > sp.from) {
  8425. nextChange = sp.from;
  8426. }
  8427. }
  8428. if (endStyles) for (var j = 0; j < endStyles.length; j += 2)
  8429. if (endStyles[j + 1] == nextChange) spanEndStyle += " " + endStyles[j]
  8430. if (!collapsed || collapsed.from == pos) for (var j = 0; j < foundBookmarks.length; ++j)
  8431. buildCollapsedSpan(builder, 0, foundBookmarks[j]);
  8432. if (collapsed && (collapsed.from || 0) == pos) {
  8433. buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos,
  8434. collapsed.marker, collapsed.from == null);
  8435. if (collapsed.to == null) return;
  8436. if (collapsed.to == pos) collapsed = false;
  8437. }
  8438. }
  8439. if (pos >= len) break;
  8440. var upto = Math.min(len, nextChange);
  8441. while (true) {
  8442. if (text) {
  8443. var end = pos + text.length;
  8444. if (!collapsed) {
  8445. var tokenText = end > upto ? text.slice(0, upto - pos) : text;
  8446. builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle,
  8447. spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", title, css);
  8448. }
  8449. if (end >= upto) {text = text.slice(upto - pos); pos = upto; break;}
  8450. pos = end;
  8451. spanStartStyle = "";
  8452. }
  8453. text = allText.slice(at, at = styles[i++]);
  8454. style = interpretTokenStyle(styles[i++], builder.cm.options);
  8455. }
  8456. }
  8457. }
  8458. // DOCUMENT DATA STRUCTURE
  8459. // By default, updates that start and end at the beginning of a line
  8460. // are treated specially, in order to make the association of line
  8461. // widgets and marker elements with the text behave more intuitive.
  8462. function isWholeLineUpdate(doc, change) {
  8463. return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" &&
  8464. (!doc.cm || doc.cm.options.wholeLineUpdateBefore);
  8465. }
  8466. // Perform a change on the document data structure.
  8467. function updateDoc(doc, change, markedSpans, estimateHeight) {
  8468. function spansFor(n) {return markedSpans ? markedSpans[n] : null;}
  8469. function update(line, text, spans) {
  8470. updateLine(line, text, spans, estimateHeight);
  8471. signalLater(line, "change", line, change);
  8472. }
  8473. function linesFor(start, end) {
  8474. for (var i = start, result = []; i < end; ++i)
  8475. result.push(new Line(text[i], spansFor(i), estimateHeight));
  8476. return result;
  8477. }
  8478. var from = change.from, to = change.to, text = change.text;
  8479. var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line);
  8480. var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line;
  8481. // Adjust the line structure
  8482. if (change.full) {
  8483. doc.insert(0, linesFor(0, text.length));
  8484. doc.remove(text.length, doc.size - text.length);
  8485. } else if (isWholeLineUpdate(doc, change)) {
  8486. // This is a whole-line replace. Treated specially to make
  8487. // sure line objects move the way they are supposed to.
  8488. var added = linesFor(0, text.length - 1);
  8489. update(lastLine, lastLine.text, lastSpans);
  8490. if (nlines) doc.remove(from.line, nlines);
  8491. if (added.length) doc.insert(from.line, added);
  8492. } else if (firstLine == lastLine) {
  8493. if (text.length == 1) {
  8494. update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans);
  8495. } else {
  8496. var added = linesFor(1, text.length - 1);
  8497. added.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight));
  8498. update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
  8499. doc.insert(from.line + 1, added);
  8500. }
  8501. } else if (text.length == 1) {
  8502. update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0));
  8503. doc.remove(from.line + 1, nlines);
  8504. } else {
  8505. update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
  8506. update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans);
  8507. var added = linesFor(1, text.length - 1);
  8508. if (nlines > 1) doc.remove(from.line + 1, nlines - 1);
  8509. doc.insert(from.line + 1, added);
  8510. }
  8511. signalLater(doc, "change", doc, change);
  8512. }
  8513. // The document is represented as a BTree consisting of leaves, with
  8514. // chunk of lines in them, and branches, with up to ten leaves or
  8515. // other branch nodes below them. The top node is always a branch
  8516. // node, and is the document object itself (meaning it has
  8517. // additional methods and properties).
  8518. //
  8519. // All nodes have parent links. The tree is used both to go from
  8520. // line numbers to line objects, and to go from objects to numbers.
  8521. // It also indexes by height, and is used to convert between height
  8522. // and line object, and to find the total height of the document.
  8523. //
  8524. // See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html
  8525. function LeafChunk(lines) {
  8526. this.lines = lines;
  8527. this.parent = null;
  8528. for (var i = 0, height = 0; i < lines.length; ++i) {
  8529. lines[i].parent = this;
  8530. height += lines[i].height;
  8531. }
  8532. this.height = height;
  8533. }
  8534. LeafChunk.prototype = {
  8535. chunkSize: function() { return this.lines.length; },
  8536. // Remove the n lines at offset 'at'.
  8537. removeInner: function(at, n) {
  8538. for (var i = at, e = at + n; i < e; ++i) {
  8539. var line = this.lines[i];
  8540. this.height -= line.height;
  8541. cleanUpLine(line);
  8542. signalLater(line, "delete");
  8543. }
  8544. this.lines.splice(at, n);
  8545. },
  8546. // Helper used to collapse a small branch into a single leaf.
  8547. collapse: function(lines) {
  8548. lines.push.apply(lines, this.lines);
  8549. },
  8550. // Insert the given array of lines at offset 'at', count them as
  8551. // having the given height.
  8552. insertInner: function(at, lines, height) {
  8553. this.height += height;
  8554. this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at));
  8555. for (var i = 0; i < lines.length; ++i) lines[i].parent = this;
  8556. },
  8557. // Used to iterate over a part of the tree.
  8558. iterN: function(at, n, op) {
  8559. for (var e = at + n; at < e; ++at)
  8560. if (op(this.lines[at])) return true;
  8561. }
  8562. };
  8563. function BranchChunk(children) {
  8564. this.children = children;
  8565. var size = 0, height = 0;
  8566. for (var i = 0; i < children.length; ++i) {
  8567. var ch = children[i];
  8568. size += ch.chunkSize(); height += ch.height;
  8569. ch.parent = this;
  8570. }
  8571. this.size = size;
  8572. this.height = height;
  8573. this.parent = null;
  8574. }
  8575. BranchChunk.prototype = {
  8576. chunkSize: function() { return this.size; },
  8577. removeInner: function(at, n) {
  8578. this.size -= n;
  8579. for (var i = 0; i < this.children.length; ++i) {
  8580. var child = this.children[i], sz = child.chunkSize();
  8581. if (at < sz) {
  8582. var rm = Math.min(n, sz - at), oldHeight = child.height;
  8583. child.removeInner(at, rm);
  8584. this.height -= oldHeight - child.height;
  8585. if (sz == rm) { this.children.splice(i--, 1); child.parent = null; }
  8586. if ((n -= rm) == 0) break;
  8587. at = 0;
  8588. } else at -= sz;
  8589. }
  8590. // If the result is smaller than 25 lines, ensure that it is a
  8591. // single leaf node.
  8592. if (this.size - n < 25 &&
  8593. (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) {
  8594. var lines = [];
  8595. this.collapse(lines);
  8596. this.children = [new LeafChunk(lines)];
  8597. this.children[0].parent = this;
  8598. }
  8599. },
  8600. collapse: function(lines) {
  8601. for (var i = 0; i < this.children.length; ++i) this.children[i].collapse(lines);
  8602. },
  8603. insertInner: function(at, lines, height) {
  8604. this.size += lines.length;
  8605. this.height += height;
  8606. for (var i = 0; i < this.children.length; ++i) {
  8607. var child = this.children[i], sz = child.chunkSize();
  8608. if (at <= sz) {
  8609. child.insertInner(at, lines, height);
  8610. if (child.lines && child.lines.length > 50) {
  8611. // To avoid memory thrashing when child.lines is huge (e.g. first view of a large file), it's never spliced.
  8612. // Instead, small slices are taken. They're taken in order because sequential memory accesses are fastest.
  8613. var remaining = child.lines.length % 25 + 25
  8614. for (var pos = remaining; pos < child.lines.length;) {
  8615. var leaf = new LeafChunk(child.lines.slice(pos, pos += 25));
  8616. child.height -= leaf.height;
  8617. this.children.splice(++i, 0, leaf);
  8618. leaf.parent = this;
  8619. }
  8620. child.lines = child.lines.slice(0, remaining);
  8621. this.maybeSpill();
  8622. }
  8623. break;
  8624. }
  8625. at -= sz;
  8626. }
  8627. },
  8628. // When a node has grown, check whether it should be split.
  8629. maybeSpill: function() {
  8630. if (this.children.length <= 10) return;
  8631. var me = this;
  8632. do {
  8633. var spilled = me.children.splice(me.children.length - 5, 5);
  8634. var sibling = new BranchChunk(spilled);
  8635. if (!me.parent) { // Become the parent node
  8636. var copy = new BranchChunk(me.children);
  8637. copy.parent = me;
  8638. me.children = [copy, sibling];
  8639. me = copy;
  8640. } else {
  8641. me.size -= sibling.size;
  8642. me.height -= sibling.height;
  8643. var myIndex = indexOf(me.parent.children, me);
  8644. me.parent.children.splice(myIndex + 1, 0, sibling);
  8645. }
  8646. sibling.parent = me.parent;
  8647. } while (me.children.length > 10);
  8648. me.parent.maybeSpill();
  8649. },
  8650. iterN: function(at, n, op) {
  8651. for (var i = 0; i < this.children.length; ++i) {
  8652. var child = this.children[i], sz = child.chunkSize();
  8653. if (at < sz) {
  8654. var used = Math.min(n, sz - at);
  8655. if (child.iterN(at, used, op)) return true;
  8656. if ((n -= used) == 0) break;
  8657. at = 0;
  8658. } else at -= sz;
  8659. }
  8660. }
  8661. };
  8662. var nextDocId = 0;
  8663. var Doc = CodeMirror.Doc = function(text, mode, firstLine, lineSep) {
  8664. if (!(this instanceof Doc)) return new Doc(text, mode, firstLine, lineSep);
  8665. if (firstLine == null) firstLine = 0;
  8666. BranchChunk.call(this, [new LeafChunk([new Line("", null)])]);
  8667. this.first = firstLine;
  8668. this.scrollTop = this.scrollLeft = 0;
  8669. this.cantEdit = false;
  8670. this.cleanGeneration = 1;
  8671. this.frontier = firstLine;
  8672. var start = Pos(firstLine, 0);
  8673. this.sel = simpleSelection(start);
  8674. this.history = new History(null);
  8675. this.id = ++nextDocId;
  8676. this.modeOption = mode;
  8677. this.lineSep = lineSep;
  8678. this.extend = false;
  8679. if (typeof text == "string") text = this.splitLines(text);
  8680. updateDoc(this, {from: start, to: start, text: text});
  8681. setSelection(this, simpleSelection(start), sel_dontScroll);
  8682. };
  8683. Doc.prototype = createObj(BranchChunk.prototype, {
  8684. constructor: Doc,
  8685. // Iterate over the document. Supports two forms -- with only one
  8686. // argument, it calls that for each line in the document. With
  8687. // three, it iterates over the range given by the first two (with
  8688. // the second being non-inclusive).
  8689. iter: function(from, to, op) {
  8690. if (op) this.iterN(from - this.first, to - from, op);
  8691. else this.iterN(this.first, this.first + this.size, from);
  8692. },
  8693. // Non-public interface for adding and removing lines.
  8694. insert: function(at, lines) {
  8695. var height = 0;
  8696. for (var i = 0; i < lines.length; ++i) height += lines[i].height;
  8697. this.insertInner(at - this.first, lines, height);
  8698. },
  8699. remove: function(at, n) { this.removeInner(at - this.first, n); },
  8700. // From here, the methods are part of the public interface. Most
  8701. // are also available from CodeMirror (editor) instances.
  8702. getValue: function(lineSep) {
  8703. var lines = getLines(this, this.first, this.first + this.size);
  8704. if (lineSep === false) return lines;
  8705. return lines.join(lineSep || this.lineSeparator());
  8706. },
  8707. setValue: docMethodOp(function(code) {
  8708. var top = Pos(this.first, 0), last = this.first + this.size - 1;
  8709. makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length),
  8710. text: this.splitLines(code), origin: "setValue", full: true}, true);
  8711. setSelection(this, simpleSelection(top));
  8712. }),
  8713. replaceRange: function(code, from, to, origin) {
  8714. from = clipPos(this, from);
  8715. to = to ? clipPos(this, to) : from;
  8716. replaceRange(this, code, from, to, origin);
  8717. },
  8718. getRange: function(from, to, lineSep) {
  8719. var lines = getBetween(this, clipPos(this, from), clipPos(this, to));
  8720. if (lineSep === false) return lines;
  8721. return lines.join(lineSep || this.lineSeparator());
  8722. },
  8723. getLine: function(line) {var l = this.getLineHandle(line); return l && l.text;},
  8724. getLineHandle: function(line) {if (isLine(this, line)) return getLine(this, line);},
  8725. getLineNumber: function(line) {return lineNo(line);},
  8726. getLineHandleVisualStart: function(line) {
  8727. if (typeof line == "number") line = getLine(this, line);
  8728. return visualLine(line);
  8729. },
  8730. lineCount: function() {return this.size;},
  8731. firstLine: function() {return this.first;},
  8732. lastLine: function() {return this.first + this.size - 1;},
  8733. clipPos: function(pos) {return clipPos(this, pos);},
  8734. getCursor: function(start) {
  8735. var range = this.sel.primary(), pos;
  8736. if (start == null || start == "head") pos = range.head;
  8737. else if (start == "anchor") pos = range.anchor;
  8738. else if (start == "end" || start == "to" || start === false) pos = range.to();
  8739. else pos = range.from();
  8740. return pos;
  8741. },
  8742. listSelections: function() { return this.sel.ranges; },
  8743. somethingSelected: function() {return this.sel.somethingSelected();},
  8744. setCursor: docMethodOp(function(line, ch, options) {
  8745. setSimpleSelection(this, clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line), null, options);
  8746. }),
  8747. setSelection: docMethodOp(function(anchor, head, options) {
  8748. setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options);
  8749. }),
  8750. extendSelection: docMethodOp(function(head, other, options) {
  8751. extendSelection(this, clipPos(this, head), other && clipPos(this, other), options);
  8752. }),
  8753. extendSelections: docMethodOp(function(heads, options) {
  8754. extendSelections(this, clipPosArray(this, heads), options);
  8755. }),
  8756. extendSelectionsBy: docMethodOp(function(f, options) {
  8757. var heads = map(this.sel.ranges, f);
  8758. extendSelections(this, clipPosArray(this, heads), options);
  8759. }),
  8760. setSelections: docMethodOp(function(ranges, primary, options) {
  8761. if (!ranges.length) return;
  8762. for (var i = 0, out = []; i < ranges.length; i++)
  8763. out[i] = new Range(clipPos(this, ranges[i].anchor),
  8764. clipPos(this, ranges[i].head));
  8765. if (primary == null) primary = Math.min(ranges.length - 1, this.sel.primIndex);
  8766. setSelection(this, normalizeSelection(out, primary), options);
  8767. }),
  8768. addSelection: docMethodOp(function(anchor, head, options) {
  8769. var ranges = this.sel.ranges.slice(0);
  8770. ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor)));
  8771. setSelection(this, normalizeSelection(ranges, ranges.length - 1), options);
  8772. }),
  8773. getSelection: function(lineSep) {
  8774. var ranges = this.sel.ranges, lines;
  8775. for (var i = 0; i < ranges.length; i++) {
  8776. var sel = getBetween(this, ranges[i].from(), ranges[i].to());
  8777. lines = lines ? lines.concat(sel) : sel;
  8778. }
  8779. if (lineSep === false) return lines;
  8780. else return lines.join(lineSep || this.lineSeparator());
  8781. },
  8782. getSelections: function(lineSep) {
  8783. var parts = [], ranges = this.sel.ranges;
  8784. for (var i = 0; i < ranges.length; i++) {
  8785. var sel = getBetween(this, ranges[i].from(), ranges[i].to());
  8786. if (lineSep !== false) sel = sel.join(lineSep || this.lineSeparator());
  8787. parts[i] = sel;
  8788. }
  8789. return parts;
  8790. },
  8791. replaceSelection: function(code, collapse, origin) {
  8792. var dup = [];
  8793. for (var i = 0; i < this.sel.ranges.length; i++)
  8794. dup[i] = code;
  8795. this.replaceSelections(dup, collapse, origin || "+input");
  8796. },
  8797. replaceSelections: docMethodOp(function(code, collapse, origin) {
  8798. var changes = [], sel = this.sel;
  8799. for (var i = 0; i < sel.ranges.length; i++) {
  8800. var range = sel.ranges[i];
  8801. changes[i] = {from: range.from(), to: range.to(), text: this.splitLines(code[i]), origin: origin};
  8802. }
  8803. var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse);
  8804. for (var i = changes.length - 1; i >= 0; i--)
  8805. makeChange(this, changes[i]);
  8806. if (newSel) setSelectionReplaceHistory(this, newSel);
  8807. else if (this.cm) ensureCursorVisible(this.cm);
  8808. }),
  8809. undo: docMethodOp(function() {makeChangeFromHistory(this, "undo");}),
  8810. redo: docMethodOp(function() {makeChangeFromHistory(this, "redo");}),
  8811. undoSelection: docMethodOp(function() {makeChangeFromHistory(this, "undo", true);}),
  8812. redoSelection: docMethodOp(function() {makeChangeFromHistory(this, "redo", true);}),
  8813. setExtending: function(val) {this.extend = val;},
  8814. getExtending: function() {return this.extend;},
  8815. historySize: function() {
  8816. var hist = this.history, done = 0, undone = 0;
  8817. for (var i = 0; i < hist.done.length; i++) if (!hist.done[i].ranges) ++done;
  8818. for (var i = 0; i < hist.undone.length; i++) if (!hist.undone[i].ranges) ++undone;
  8819. return {undo: done, redo: undone};
  8820. },
  8821. clearHistory: function() {this.history = new History(this.history.maxGeneration);},
  8822. markClean: function() {
  8823. this.cleanGeneration = this.changeGeneration(true);
  8824. },
  8825. changeGeneration: function(forceSplit) {
  8826. if (forceSplit)
  8827. this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null;
  8828. return this.history.generation;
  8829. },
  8830. isClean: function (gen) {
  8831. return this.history.generation == (gen || this.cleanGeneration);
  8832. },
  8833. getHistory: function() {
  8834. return {done: copyHistoryArray(this.history.done),
  8835. undone: copyHistoryArray(this.history.undone)};
  8836. },
  8837. setHistory: function(histData) {
  8838. var hist = this.history = new History(this.history.maxGeneration);
  8839. hist.done = copyHistoryArray(histData.done.slice(0), null, true);
  8840. hist.undone = copyHistoryArray(histData.undone.slice(0), null, true);
  8841. },
  8842. addLineClass: docMethodOp(function(handle, where, cls) {
  8843. return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function(line) {
  8844. var prop = where == "text" ? "textClass"
  8845. : where == "background" ? "bgClass"
  8846. : where == "gutter" ? "gutterClass" : "wrapClass";
  8847. if (!line[prop]) line[prop] = cls;
  8848. else if (classTest(cls).test(line[prop])) return false;
  8849. else line[prop] += " " + cls;
  8850. return true;
  8851. });
  8852. }),
  8853. removeLineClass: docMethodOp(function(handle, where, cls) {
  8854. return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function(line) {
  8855. var prop = where == "text" ? "textClass"
  8856. : where == "background" ? "bgClass"
  8857. : where == "gutter" ? "gutterClass" : "wrapClass";
  8858. var cur = line[prop];
  8859. if (!cur) return false;
  8860. else if (cls == null) line[prop] = null;
  8861. else {
  8862. var found = cur.match(classTest(cls));
  8863. if (!found) return false;
  8864. var end = found.index + found[0].length;
  8865. line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null;
  8866. }
  8867. return true;
  8868. });
  8869. }),
  8870. addLineWidget: docMethodOp(function(handle, node, options) {
  8871. return addLineWidget(this, handle, node, options);
  8872. }),
  8873. removeLineWidget: function(widget) { widget.clear(); },
  8874. markText: function(from, to, options) {
  8875. return markText(this, clipPos(this, from), clipPos(this, to), options, options && options.type || "range");
  8876. },
  8877. setBookmark: function(pos, options) {
  8878. var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options),
  8879. insertLeft: options && options.insertLeft,
  8880. clearWhenEmpty: false, shared: options && options.shared,
  8881. handleMouseEvents: options && options.handleMouseEvents};
  8882. pos = clipPos(this, pos);
  8883. return markText(this, pos, pos, realOpts, "bookmark");
  8884. },
  8885. findMarksAt: function(pos) {
  8886. pos = clipPos(this, pos);
  8887. var markers = [], spans = getLine(this, pos.line).markedSpans;
  8888. if (spans) for (var i = 0; i < spans.length; ++i) {
  8889. var span = spans[i];
  8890. if ((span.from == null || span.from <= pos.ch) &&
  8891. (span.to == null || span.to >= pos.ch))
  8892. markers.push(span.marker.parent || span.marker);
  8893. }
  8894. return markers;
  8895. },
  8896. findMarks: function(from, to, filter) {
  8897. from = clipPos(this, from); to = clipPos(this, to);
  8898. var found = [], lineNo = from.line;
  8899. this.iter(from.line, to.line + 1, function(line) {
  8900. var spans = line.markedSpans;
  8901. if (spans) for (var i = 0; i < spans.length; i++) {
  8902. var span = spans[i];
  8903. if (!(span.to != null && lineNo == from.line && from.ch >= span.to ||
  8904. span.from == null && lineNo != from.line ||
  8905. span.from != null && lineNo == to.line && span.from >= to.ch) &&
  8906. (!filter || filter(span.marker)))
  8907. found.push(span.marker.parent || span.marker);
  8908. }
  8909. ++lineNo;
  8910. });
  8911. return found;
  8912. },
  8913. getAllMarks: function() {
  8914. var markers = [];
  8915. this.iter(function(line) {
  8916. var sps = line.markedSpans;
  8917. if (sps) for (var i = 0; i < sps.length; ++i)
  8918. if (sps[i].from != null) markers.push(sps[i].marker);
  8919. });
  8920. return markers;
  8921. },
  8922. posFromIndex: function(off) {
  8923. var ch, lineNo = this.first, sepSize = this.lineSeparator().length;
  8924. this.iter(function(line) {
  8925. var sz = line.text.length + sepSize;
  8926. if (sz > off) { ch = off; return true; }
  8927. off -= sz;
  8928. ++lineNo;
  8929. });
  8930. return clipPos(this, Pos(lineNo, ch));
  8931. },
  8932. indexFromPos: function (coords) {
  8933. coords = clipPos(this, coords);
  8934. var index = coords.ch;
  8935. if (coords.line < this.first || coords.ch < 0) return 0;
  8936. var sepSize = this.lineSeparator().length;
  8937. this.iter(this.first, coords.line, function (line) {
  8938. index += line.text.length + sepSize;
  8939. });
  8940. return index;
  8941. },
  8942. copy: function(copyHistory) {
  8943. var doc = new Doc(getLines(this, this.first, this.first + this.size),
  8944. this.modeOption, this.first, this.lineSep);
  8945. doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft;
  8946. doc.sel = this.sel;
  8947. doc.extend = false;
  8948. if (copyHistory) {
  8949. doc.history.undoDepth = this.history.undoDepth;
  8950. doc.setHistory(this.getHistory());
  8951. }
  8952. return doc;
  8953. },
  8954. linkedDoc: function(options) {
  8955. if (!options) options = {};
  8956. var from = this.first, to = this.first + this.size;
  8957. if (options.from != null && options.from > from) from = options.from;
  8958. if (options.to != null && options.to < to) to = options.to;
  8959. var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from, this.lineSep);
  8960. if (options.sharedHist) copy.history = this.history;
  8961. (this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist});
  8962. copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}];
  8963. copySharedMarkers(copy, findSharedMarkers(this));
  8964. return copy;
  8965. },
  8966. unlinkDoc: function(other) {
  8967. if (other instanceof CodeMirror) other = other.doc;
  8968. if (this.linked) for (var i = 0; i < this.linked.length; ++i) {
  8969. var link = this.linked[i];
  8970. if (link.doc != other) continue;
  8971. this.linked.splice(i, 1);
  8972. other.unlinkDoc(this);
  8973. detachSharedMarkers(findSharedMarkers(this));
  8974. break;
  8975. }
  8976. // If the histories were shared, split them again
  8977. if (other.history == this.history) {
  8978. var splitIds = [other.id];
  8979. linkedDocs(other, function(doc) {splitIds.push(doc.id);}, true);
  8980. other.history = new History(null);
  8981. other.history.done = copyHistoryArray(this.history.done, splitIds);
  8982. other.history.undone = copyHistoryArray(this.history.undone, splitIds);
  8983. }
  8984. },
  8985. iterLinkedDocs: function(f) {linkedDocs(this, f);},
  8986. getMode: function() {return this.mode;},
  8987. getEditor: function() {return this.cm;},
  8988. splitLines: function(str) {
  8989. if (this.lineSep) return str.split(this.lineSep);
  8990. return splitLinesAuto(str);
  8991. },
  8992. lineSeparator: function() { return this.lineSep || "\n"; }
  8993. });
  8994. // Public alias.
  8995. Doc.prototype.eachLine = Doc.prototype.iter;
  8996. // Set up methods on CodeMirror's prototype to redirect to the editor's document.
  8997. var dontDelegate = "iter insert remove copy getEditor constructor".split(" ");
  8998. for (var prop in Doc.prototype) if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0)
  8999. CodeMirror.prototype[prop] = (function(method) {
  9000. return function() {return method.apply(this.doc, arguments);};
  9001. })(Doc.prototype[prop]);
  9002. eventMixin(Doc);
  9003. // Call f for all linked documents.
  9004. function linkedDocs(doc, f, sharedHistOnly) {
  9005. function propagate(doc, skip, sharedHist) {
  9006. if (doc.linked) for (var i = 0; i < doc.linked.length; ++i) {
  9007. var rel = doc.linked[i];
  9008. if (rel.doc == skip) continue;
  9009. var shared = sharedHist && rel.sharedHist;
  9010. if (sharedHistOnly && !shared) continue;
  9011. f(rel.doc, shared);
  9012. propagate(rel.doc, doc, shared);
  9013. }
  9014. }
  9015. propagate(doc, null, true);
  9016. }
  9017. // Attach a document to an editor.
  9018. function attachDoc(cm, doc) {
  9019. if (doc.cm) throw new Error("This document is already in use.");
  9020. cm.doc = doc;
  9021. doc.cm = cm;
  9022. estimateLineHeights(cm);
  9023. loadMode(cm);
  9024. if (!cm.options.lineWrapping) findMaxLine(cm);
  9025. cm.options.mode = doc.modeOption;
  9026. regChange(cm);
  9027. }
  9028. // LINE UTILITIES
  9029. // Find the line object corresponding to the given line number.
  9030. function getLine(doc, n) {
  9031. n -= doc.first;
  9032. if (n < 0 || n >= doc.size) throw new Error("There is no line " + (n + doc.first) + " in the document.");
  9033. for (var chunk = doc; !chunk.lines;) {
  9034. for (var i = 0;; ++i) {
  9035. var child = chunk.children[i], sz = child.chunkSize();
  9036. if (n < sz) { chunk = child; break; }
  9037. n -= sz;
  9038. }
  9039. }
  9040. return chunk.lines[n];
  9041. }
  9042. // Get the part of a document between two positions, as an array of
  9043. // strings.
  9044. function getBetween(doc, start, end) {
  9045. var out = [], n = start.line;
  9046. doc.iter(start.line, end.line + 1, function(line) {
  9047. var text = line.text;
  9048. if (n == end.line) text = text.slice(0, end.ch);
  9049. if (n == start.line) text = text.slice(start.ch);
  9050. out.push(text);
  9051. ++n;
  9052. });
  9053. return out;
  9054. }
  9055. // Get the lines between from and to, as array of strings.
  9056. function getLines(doc, from, to) {
  9057. var out = [];
  9058. doc.iter(from, to, function(line) { out.push(line.text); });
  9059. return out;
  9060. }
  9061. // Update the height of a line, propagating the height change
  9062. // upwards to parent nodes.
  9063. function updateLineHeight(line, height) {
  9064. var diff = height - line.height;
  9065. if (diff) for (var n = line; n; n = n.parent) n.height += diff;
  9066. }
  9067. // Given a line object, find its line number by walking up through
  9068. // its parent links.
  9069. function lineNo(line) {
  9070. if (line.parent == null) return null;
  9071. var cur = line.parent, no = indexOf(cur.lines, line);
  9072. for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) {
  9073. for (var i = 0;; ++i) {
  9074. if (chunk.children[i] == cur) break;
  9075. no += chunk.children[i].chunkSize();
  9076. }
  9077. }
  9078. return no + cur.first;
  9079. }
  9080. // Find the line at the given vertical position, using the height
  9081. // information in the document tree.
  9082. function lineAtHeight(chunk, h) {
  9083. var n = chunk.first;
  9084. outer: do {
  9085. for (var i = 0; i < chunk.children.length; ++i) {
  9086. var child = chunk.children[i], ch = child.height;
  9087. if (h < ch) { chunk = child; continue outer; }
  9088. h -= ch;
  9089. n += child.chunkSize();
  9090. }
  9091. return n;
  9092. } while (!chunk.lines);
  9093. for (var i = 0; i < chunk.lines.length; ++i) {
  9094. var line = chunk.lines[i], lh = line.height;
  9095. if (h < lh) break;
  9096. h -= lh;
  9097. }
  9098. return n + i;
  9099. }
  9100. // Find the height above the given line.
  9101. function heightAtLine(lineObj) {
  9102. lineObj = visualLine(lineObj);
  9103. var h = 0, chunk = lineObj.parent;
  9104. for (var i = 0; i < chunk.lines.length; ++i) {
  9105. var line = chunk.lines[i];
  9106. if (line == lineObj) break;
  9107. else h += line.height;
  9108. }
  9109. for (var p = chunk.parent; p; chunk = p, p = chunk.parent) {
  9110. for (var i = 0; i < p.children.length; ++i) {
  9111. var cur = p.children[i];
  9112. if (cur == chunk) break;
  9113. else h += cur.height;
  9114. }
  9115. }
  9116. return h;
  9117. }
  9118. // Get the bidi ordering for the given line (and cache it). Returns
  9119. // false for lines that are fully left-to-right, and an array of
  9120. // BidiSpan objects otherwise.
  9121. function getOrder(line) {
  9122. var order = line.order;
  9123. if (order == null) order = line.order = bidiOrdering(line.text);
  9124. return order;
  9125. }
  9126. // HISTORY
  9127. function History(startGen) {
  9128. // Arrays of change events and selections. Doing something adds an
  9129. // event to done and clears undo. Undoing moves events from done
  9130. // to undone, redoing moves them in the other direction.
  9131. this.done = []; this.undone = [];
  9132. this.undoDepth = Infinity;
  9133. // Used to track when changes can be merged into a single undo
  9134. // event
  9135. this.lastModTime = this.lastSelTime = 0;
  9136. this.lastOp = this.lastSelOp = null;
  9137. this.lastOrigin = this.lastSelOrigin = null;
  9138. // Used by the isClean() method
  9139. this.generation = this.maxGeneration = startGen || 1;
  9140. }
  9141. // Create a history change event from an updateDoc-style change
  9142. // object.
  9143. function historyChangeFromChange(doc, change) {
  9144. var histChange = {from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to)};
  9145. attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);
  9146. linkedDocs(doc, function(doc) {attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);}, true);
  9147. return histChange;
  9148. }
  9149. // Pop all selection events off the end of a history array. Stop at
  9150. // a change event.
  9151. function clearSelectionEvents(array) {
  9152. while (array.length) {
  9153. var last = lst(array);
  9154. if (last.ranges) array.pop();
  9155. else break;
  9156. }
  9157. }
  9158. // Find the top change event in the history. Pop off selection
  9159. // events that are in the way.
  9160. function lastChangeEvent(hist, force) {
  9161. if (force) {
  9162. clearSelectionEvents(hist.done);
  9163. return lst(hist.done);
  9164. } else if (hist.done.length && !lst(hist.done).ranges) {
  9165. return lst(hist.done);
  9166. } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) {
  9167. hist.done.pop();
  9168. return lst(hist.done);
  9169. }
  9170. }
  9171. // Register a change in the history. Merges changes that are within
  9172. // a single operation, ore are close together with an origin that
  9173. // allows merging (starting with "+") into a single event.
  9174. function addChangeToHistory(doc, change, selAfter, opId) {
  9175. var hist = doc.history;
  9176. hist.undone.length = 0;
  9177. var time = +new Date, cur;
  9178. if ((hist.lastOp == opId ||
  9179. hist.lastOrigin == change.origin && change.origin &&
  9180. ((change.origin.charAt(0) == "+" && doc.cm && hist.lastModTime > time - doc.cm.options.historyEventDelay) ||
  9181. change.origin.charAt(0) == "*")) &&
  9182. (cur = lastChangeEvent(hist, hist.lastOp == opId))) {
  9183. // Merge this change into the last event
  9184. var last = lst(cur.changes);
  9185. if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) {
  9186. // Optimized case for simple insertion -- don't want to add
  9187. // new changesets for every character typed
  9188. last.to = changeEnd(change);
  9189. } else {
  9190. // Add new sub-event
  9191. cur.changes.push(historyChangeFromChange(doc, change));
  9192. }
  9193. } else {
  9194. // Can not be merged, start a new event.
  9195. var before = lst(hist.done);
  9196. if (!before || !before.ranges)
  9197. pushSelectionToHistory(doc.sel, hist.done);
  9198. cur = {changes: [historyChangeFromChange(doc, change)],
  9199. generation: hist.generation};
  9200. hist.done.push(cur);
  9201. while (hist.done.length > hist.undoDepth) {
  9202. hist.done.shift();
  9203. if (!hist.done[0].ranges) hist.done.shift();
  9204. }
  9205. }
  9206. hist.done.push(selAfter);
  9207. hist.generation = ++hist.maxGeneration;
  9208. hist.lastModTime = hist.lastSelTime = time;
  9209. hist.lastOp = hist.lastSelOp = opId;
  9210. hist.lastOrigin = hist.lastSelOrigin = change.origin;
  9211. if (!last) signal(doc, "historyAdded");
  9212. }
  9213. function selectionEventCanBeMerged(doc, origin, prev, sel) {
  9214. var ch = origin.charAt(0);
  9215. return ch == "*" ||
  9216. ch == "+" &&
  9217. prev.ranges.length == sel.ranges.length &&
  9218. prev.somethingSelected() == sel.somethingSelected() &&
  9219. new Date - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500);
  9220. }
  9221. // Called whenever the selection changes, sets the new selection as
  9222. // the pending selection in the history, and pushes the old pending
  9223. // selection into the 'done' array when it was significantly
  9224. // different (in number of selected ranges, emptiness, or time).
  9225. function addSelectionToHistory(doc, sel, opId, options) {
  9226. var hist = doc.history, origin = options && options.origin;
  9227. // A new event is started when the previous origin does not match
  9228. // the current, or the origins don't allow matching. Origins
  9229. // starting with * are always merged, those starting with + are
  9230. // merged when similar and close together in time.
  9231. if (opId == hist.lastSelOp ||
  9232. (origin && hist.lastSelOrigin == origin &&
  9233. (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin ||
  9234. selectionEventCanBeMerged(doc, origin, lst(hist.done), sel))))
  9235. hist.done[hist.done.length - 1] = sel;
  9236. else
  9237. pushSelectionToHistory(sel, hist.done);
  9238. hist.lastSelTime = +new Date;
  9239. hist.lastSelOrigin = origin;
  9240. hist.lastSelOp = opId;
  9241. if (options && options.clearRedo !== false)
  9242. clearSelectionEvents(hist.undone);
  9243. }
  9244. function pushSelectionToHistory(sel, dest) {
  9245. var top = lst(dest);
  9246. if (!(top && top.ranges && top.equals(sel)))
  9247. dest.push(sel);
  9248. }
  9249. // Used to store marked span information in the history.
  9250. function attachLocalSpans(doc, change, from, to) {
  9251. var existing = change["spans_" + doc.id], n = 0;
  9252. doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function(line) {
  9253. if (line.markedSpans)
  9254. (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans;
  9255. ++n;
  9256. });
  9257. }
  9258. // When un/re-doing restores text containing marked spans, those
  9259. // that have been explicitly cleared should not be restored.
  9260. function removeClearedSpans(spans) {
  9261. if (!spans) return null;
  9262. for (var i = 0, out; i < spans.length; ++i) {
  9263. if (spans[i].marker.explicitlyCleared) { if (!out) out = spans.slice(0, i); }
  9264. else if (out) out.push(spans[i]);
  9265. }
  9266. return !out ? spans : out.length ? out : null;
  9267. }
  9268. // Retrieve and filter the old marked spans stored in a change event.
  9269. function getOldSpans(doc, change) {
  9270. var found = change["spans_" + doc.id];
  9271. if (!found) return null;
  9272. for (var i = 0, nw = []; i < change.text.length; ++i)
  9273. nw.push(removeClearedSpans(found[i]));
  9274. return nw;
  9275. }
  9276. // Used both to provide a JSON-safe object in .getHistory, and, when
  9277. // detaching a document, to split the history in two
  9278. function copyHistoryArray(events, newGroup, instantiateSel) {
  9279. for (var i = 0, copy = []; i < events.length; ++i) {
  9280. var event = events[i];
  9281. if (event.ranges) {
  9282. copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event);
  9283. continue;
  9284. }
  9285. var changes = event.changes, newChanges = [];
  9286. copy.push({changes: newChanges});
  9287. for (var j = 0; j < changes.length; ++j) {
  9288. var change = changes[j], m;
  9289. newChanges.push({from: change.from, to: change.to, text: change.text});
  9290. if (newGroup) for (var prop in change) if (m = prop.match(/^spans_(\d+)$/)) {
  9291. if (indexOf(newGroup, Number(m[1])) > -1) {
  9292. lst(newChanges)[prop] = change[prop];
  9293. delete change[prop];
  9294. }
  9295. }
  9296. }
  9297. }
  9298. return copy;
  9299. }
  9300. // Rebasing/resetting history to deal with externally-sourced changes
  9301. function rebaseHistSelSingle(pos, from, to, diff) {
  9302. if (to < pos.line) {
  9303. pos.line += diff;
  9304. } else if (from < pos.line) {
  9305. pos.line = from;
  9306. pos.ch = 0;
  9307. }
  9308. }
  9309. // Tries to rebase an array of history events given a change in the
  9310. // document. If the change touches the same lines as the event, the
  9311. // event, and everything 'behind' it, is discarded. If the change is
  9312. // before the event, the event's positions are updated. Uses a
  9313. // copy-on-write scheme for the positions, to avoid having to
  9314. // reallocate them all on every rebase, but also avoid problems with
  9315. // shared position objects being unsafely updated.
  9316. function rebaseHistArray(array, from, to, diff) {
  9317. for (var i = 0; i < array.length; ++i) {
  9318. var sub = array[i], ok = true;
  9319. if (sub.ranges) {
  9320. if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true; }
  9321. for (var j = 0; j < sub.ranges.length; j++) {
  9322. rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff);
  9323. rebaseHistSelSingle(sub.ranges[j].head, from, to, diff);
  9324. }
  9325. continue;
  9326. }
  9327. for (var j = 0; j < sub.changes.length; ++j) {
  9328. var cur = sub.changes[j];
  9329. if (to < cur.from.line) {
  9330. cur.from = Pos(cur.from.line + diff, cur.from.ch);
  9331. cur.to = Pos(cur.to.line + diff, cur.to.ch);
  9332. } else if (from <= cur.to.line) {
  9333. ok = false;
  9334. break;
  9335. }
  9336. }
  9337. if (!ok) {
  9338. array.splice(0, i + 1);
  9339. i = 0;
  9340. }
  9341. }
  9342. }
  9343. function rebaseHist(hist, change) {
  9344. var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1;
  9345. rebaseHistArray(hist.done, from, to, diff);
  9346. rebaseHistArray(hist.undone, from, to, diff);
  9347. }
  9348. // EVENT UTILITIES
  9349. // Due to the fact that we still support jurassic IE versions, some
  9350. // compatibility wrappers are needed.
  9351. var e_preventDefault = CodeMirror.e_preventDefault = function(e) {
  9352. if (e.preventDefault) e.preventDefault();
  9353. else e.returnValue = false;
  9354. };
  9355. var e_stopPropagation = CodeMirror.e_stopPropagation = function(e) {
  9356. if (e.stopPropagation) e.stopPropagation();
  9357. else e.cancelBubble = true;
  9358. };
  9359. function e_defaultPrevented(e) {
  9360. return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false;
  9361. }
  9362. var e_stop = CodeMirror.e_stop = function(e) {e_preventDefault(e); e_stopPropagation(e);};
  9363. function e_target(e) {return e.target || e.srcElement;}
  9364. function e_button(e) {
  9365. var b = e.which;
  9366. if (b == null) {
  9367. if (e.button & 1) b = 1;
  9368. else if (e.button & 2) b = 3;
  9369. else if (e.button & 4) b = 2;
  9370. }
  9371. if (mac && e.ctrlKey && b == 1) b = 3;
  9372. return b;
  9373. }
  9374. // EVENT HANDLING
  9375. // Lightweight event framework. on/off also work on DOM nodes,
  9376. // registering native DOM handlers.
  9377. var on = CodeMirror.on = function(emitter, type, f) {
  9378. if (emitter.addEventListener)
  9379. emitter.addEventListener(type, f, false);
  9380. else if (emitter.attachEvent)
  9381. emitter.attachEvent("on" + type, f);
  9382. else {
  9383. var map = emitter._handlers || (emitter._handlers = {});
  9384. var arr = map[type] || (map[type] = []);
  9385. arr.push(f);
  9386. }
  9387. };
  9388. var noHandlers = []
  9389. function getHandlers(emitter, type, copy) {
  9390. var arr = emitter._handlers && emitter._handlers[type]
  9391. if (copy) return arr && arr.length > 0 ? arr.slice() : noHandlers
  9392. else return arr || noHandlers
  9393. }
  9394. var off = CodeMirror.off = function(emitter, type, f) {
  9395. if (emitter.removeEventListener)
  9396. emitter.removeEventListener(type, f, false);
  9397. else if (emitter.detachEvent)
  9398. emitter.detachEvent("on" + type, f);
  9399. else {
  9400. var handlers = getHandlers(emitter, type, false)
  9401. for (var i = 0; i < handlers.length; ++i)
  9402. if (handlers[i] == f) { handlers.splice(i, 1); break; }
  9403. }
  9404. };
  9405. var signal = CodeMirror.signal = function(emitter, type /*, values...*/) {
  9406. var handlers = getHandlers(emitter, type, true)
  9407. if (!handlers.length) return;
  9408. var args = Array.prototype.slice.call(arguments, 2);
  9409. for (var i = 0; i < handlers.length; ++i) handlers[i].apply(null, args);
  9410. };
  9411. var orphanDelayedCallbacks = null;
  9412. // Often, we want to signal events at a point where we are in the
  9413. // middle of some work, but don't want the handler to start calling
  9414. // other methods on the editor, which might be in an inconsistent
  9415. // state or simply not expect any other events to happen.
  9416. // signalLater looks whether there are any handlers, and schedules
  9417. // them to be executed when the last operation ends, or, if no
  9418. // operation is active, when a timeout fires.
  9419. function signalLater(emitter, type /*, values...*/) {
  9420. var arr = getHandlers(emitter, type, false)
  9421. if (!arr.length) return;
  9422. var args = Array.prototype.slice.call(arguments, 2), list;
  9423. if (operationGroup) {
  9424. list = operationGroup.delayedCallbacks;
  9425. } else if (orphanDelayedCallbacks) {
  9426. list = orphanDelayedCallbacks;
  9427. } else {
  9428. list = orphanDelayedCallbacks = [];
  9429. setTimeout(fireOrphanDelayed, 0);
  9430. }
  9431. function bnd(f) {return function(){f.apply(null, args);};};
  9432. for (var i = 0; i < arr.length; ++i)
  9433. list.push(bnd(arr[i]));
  9434. }
  9435. function fireOrphanDelayed() {
  9436. var delayed = orphanDelayedCallbacks;
  9437. orphanDelayedCallbacks = null;
  9438. for (var i = 0; i < delayed.length; ++i) delayed[i]();
  9439. }
  9440. // The DOM events that CodeMirror handles can be overridden by
  9441. // registering a (non-DOM) handler on the editor for the event name,
  9442. // and preventDefault-ing the event in that handler.
  9443. function signalDOMEvent(cm, e, override) {
  9444. if (typeof e == "string")
  9445. e = {type: e, preventDefault: function() { this.defaultPrevented = true; }};
  9446. signal(cm, override || e.type, cm, e);
  9447. return e_defaultPrevented(e) || e.codemirrorIgnore;
  9448. }
  9449. function signalCursorActivity(cm) {
  9450. var arr = cm._handlers && cm._handlers.cursorActivity;
  9451. if (!arr) return;
  9452. var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = []);
  9453. for (var i = 0; i < arr.length; ++i) if (indexOf(set, arr[i]) == -1)
  9454. set.push(arr[i]);
  9455. }
  9456. function hasHandler(emitter, type) {
  9457. return getHandlers(emitter, type).length > 0
  9458. }
  9459. // Add on and off methods to a constructor's prototype, to make
  9460. // registering events on such objects more convenient.
  9461. function eventMixin(ctor) {
  9462. ctor.prototype.on = function(type, f) {on(this, type, f);};
  9463. ctor.prototype.off = function(type, f) {off(this, type, f);};
  9464. }
  9465. // MISC UTILITIES
  9466. // Number of pixels added to scroller and sizer to hide scrollbar
  9467. var scrollerGap = 30;
  9468. // Returned or thrown by various protocols to signal 'I'm not
  9469. // handling this'.
  9470. var Pass = CodeMirror.Pass = {toString: function(){return "CodeMirror.Pass";}};
  9471. // Reused option objects for setSelection & friends
  9472. var sel_dontScroll = {scroll: false}, sel_mouse = {origin: "*mouse"}, sel_move = {origin: "+move"};
  9473. function Delayed() {this.id = null;}
  9474. Delayed.prototype.set = function(ms, f) {
  9475. clearTimeout(this.id);
  9476. this.id = setTimeout(f, ms);
  9477. };
  9478. // Counts the column offset in a string, taking tabs into account.
  9479. // Used mostly to find indentation.
  9480. var countColumn = CodeMirror.countColumn = function(string, end, tabSize, startIndex, startValue) {
  9481. if (end == null) {
  9482. end = string.search(/[^\s\u00a0]/);
  9483. if (end == -1) end = string.length;
  9484. }
  9485. for (var i = startIndex || 0, n = startValue || 0;;) {
  9486. var nextTab = string.indexOf("\t", i);
  9487. if (nextTab < 0 || nextTab >= end)
  9488. return n + (end - i);
  9489. n += nextTab - i;
  9490. n += tabSize - (n % tabSize);
  9491. i = nextTab + 1;
  9492. }
  9493. };
  9494. // The inverse of countColumn -- find the offset that corresponds to
  9495. // a particular column.
  9496. var findColumn = CodeMirror.findColumn = function(string, goal, tabSize) {
  9497. for (var pos = 0, col = 0;;) {
  9498. var nextTab = string.indexOf("\t", pos);
  9499. if (nextTab == -1) nextTab = string.length;
  9500. var skipped = nextTab - pos;
  9501. if (nextTab == string.length || col + skipped >= goal)
  9502. return pos + Math.min(skipped, goal - col);
  9503. col += nextTab - pos;
  9504. col += tabSize - (col % tabSize);
  9505. pos = nextTab + 1;
  9506. if (col >= goal) return pos;
  9507. }
  9508. }
  9509. var spaceStrs = [""];
  9510. function spaceStr(n) {
  9511. while (spaceStrs.length <= n)
  9512. spaceStrs.push(lst(spaceStrs) + " ");
  9513. return spaceStrs[n];
  9514. }
  9515. function lst(arr) { return arr[arr.length-1]; }
  9516. var selectInput = function(node) { node.select(); };
  9517. if (ios) // Mobile Safari apparently has a bug where select() is broken.
  9518. selectInput = function(node) { node.selectionStart = 0; node.selectionEnd = node.value.length; };
  9519. else if (ie) // Suppress mysterious IE10 errors
  9520. selectInput = function(node) { try { node.select(); } catch(_e) {} };
  9521. function indexOf(array, elt) {
  9522. for (var i = 0; i < array.length; ++i)
  9523. if (array[i] == elt) return i;
  9524. return -1;
  9525. }
  9526. function map(array, f) {
  9527. var out = [];
  9528. for (var i = 0; i < array.length; i++) out[i] = f(array[i], i);
  9529. return out;
  9530. }
  9531. function nothing() {}
  9532. function createObj(base, props) {
  9533. var inst;
  9534. if (Object.create) {
  9535. inst = Object.create(base);
  9536. } else {
  9537. nothing.prototype = base;
  9538. inst = new nothing();
  9539. }
  9540. if (props) copyObj(props, inst);
  9541. return inst;
  9542. };
  9543. function copyObj(obj, target, overwrite) {
  9544. if (!target) target = {};
  9545. for (var prop in obj)
  9546. if (obj.hasOwnProperty(prop) && (overwrite !== false || !target.hasOwnProperty(prop)))
  9547. target[prop] = obj[prop];
  9548. return target;
  9549. }
  9550. function bind(f) {
  9551. var args = Array.prototype.slice.call(arguments, 1);
  9552. return function(){return f.apply(null, args);};
  9553. }
  9554. var nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;
  9555. var isWordCharBasic = CodeMirror.isWordChar = function(ch) {
  9556. return /\w/.test(ch) || ch > "\x80" &&
  9557. (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch));
  9558. };
  9559. function isWordChar(ch, helper) {
  9560. if (!helper) return isWordCharBasic(ch);
  9561. if (helper.source.indexOf("\\w") > -1 && isWordCharBasic(ch)) return true;
  9562. return helper.test(ch);
  9563. }
  9564. function isEmpty(obj) {
  9565. for (var n in obj) if (obj.hasOwnProperty(n) && obj[n]) return false;
  9566. return true;
  9567. }
  9568. // Extending unicode characters. A series of a non-extending char +
  9569. // any number of extending chars is treated as a single unit as far
  9570. // as editing and measuring is concerned. This is not fully correct,
  9571. // since some scripts/fonts/browsers also treat other configurations
  9572. // of code points as a group.
  9573. 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]/;
  9574. function isExtendingChar(ch) { return ch.charCodeAt(0) >= 768 && extendingChars.test(ch); }
  9575. // DOM UTILITIES
  9576. function elt(tag, content, className, style) {
  9577. var e = document.createElement(tag);
  9578. if (className) e.className = className;
  9579. if (style) e.style.cssText = style;
  9580. if (typeof content == "string") e.appendChild(document.createTextNode(content));
  9581. else if (content) for (var i = 0; i < content.length; ++i) e.appendChild(content[i]);
  9582. return e;
  9583. }
  9584. var range;
  9585. if (document.createRange) range = function(node, start, end, endNode) {
  9586. var r = document.createRange();
  9587. r.setEnd(endNode || node, end);
  9588. r.setStart(node, start);
  9589. return r;
  9590. };
  9591. else range = function(node, start, end) {
  9592. var r = document.body.createTextRange();
  9593. try { r.moveToElementText(node.parentNode); }
  9594. catch(e) { return r; }
  9595. r.collapse(true);
  9596. r.moveEnd("character", end);
  9597. r.moveStart("character", start);
  9598. return r;
  9599. };
  9600. function removeChildren(e) {
  9601. for (var count = e.childNodes.length; count > 0; --count)
  9602. e.removeChild(e.firstChild);
  9603. return e;
  9604. }
  9605. function removeChildrenAndAdd(parent, e) {
  9606. return removeChildren(parent).appendChild(e);
  9607. }
  9608. var contains = CodeMirror.contains = function(parent, child) {
  9609. if (child.nodeType == 3) // Android browser always returns false when child is a textnode
  9610. child = child.parentNode;
  9611. if (parent.contains)
  9612. return parent.contains(child);
  9613. do {
  9614. if (child.nodeType == 11) child = child.host;
  9615. if (child == parent) return true;
  9616. } while (child = child.parentNode);
  9617. };
  9618. function activeElt() {
  9619. var activeElement = document.activeElement;
  9620. while (activeElement && activeElement.root && activeElement.root.activeElement)
  9621. activeElement = activeElement.root.activeElement;
  9622. return activeElement;
  9623. }
  9624. // Older versions of IE throws unspecified error when touching
  9625. // document.activeElement in some cases (during loading, in iframe)
  9626. if (ie && ie_version < 11) activeElt = function() {
  9627. try { return document.activeElement; }
  9628. catch(e) { return document.body; }
  9629. };
  9630. function classTest(cls) { return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*"); }
  9631. var rmClass = CodeMirror.rmClass = function(node, cls) {
  9632. var current = node.className;
  9633. var match = classTest(cls).exec(current);
  9634. if (match) {
  9635. var after = current.slice(match.index + match[0].length);
  9636. node.className = current.slice(0, match.index) + (after ? match[1] + after : "");
  9637. }
  9638. };
  9639. var addClass = CodeMirror.addClass = function(node, cls) {
  9640. var current = node.className;
  9641. if (!classTest(cls).test(current)) node.className += (current ? " " : "") + cls;
  9642. };
  9643. function joinClasses(a, b) {
  9644. var as = a.split(" ");
  9645. for (var i = 0; i < as.length; i++)
  9646. if (as[i] && !classTest(as[i]).test(b)) b += " " + as[i];
  9647. return b;
  9648. }
  9649. // WINDOW-WIDE EVENTS
  9650. // These must be handled carefully, because naively registering a
  9651. // handler for each editor will cause the editors to never be
  9652. // garbage collected.
  9653. function forEachCodeMirror(f) {
  9654. if (!document.body.getElementsByClassName) return;
  9655. var byClass = document.body.getElementsByClassName("CodeMirror");
  9656. for (var i = 0; i < byClass.length; i++) {
  9657. var cm = byClass[i].CodeMirror;
  9658. if (cm) f(cm);
  9659. }
  9660. }
  9661. var globalsRegistered = false;
  9662. function ensureGlobalHandlers() {
  9663. if (globalsRegistered) return;
  9664. registerGlobalHandlers();
  9665. globalsRegistered = true;
  9666. }
  9667. function registerGlobalHandlers() {
  9668. // When the window resizes, we need to refresh active editors.
  9669. var resizeTimer;
  9670. on(window, "resize", function() {
  9671. if (resizeTimer == null) resizeTimer = setTimeout(function() {
  9672. resizeTimer = null;
  9673. forEachCodeMirror(onResize);
  9674. }, 100);
  9675. });
  9676. // When the window loses focus, we want to show the editor as blurred
  9677. on(window, "blur", function() {
  9678. forEachCodeMirror(onBlur);
  9679. });
  9680. }
  9681. // FEATURE DETECTION
  9682. // Detect drag-and-drop
  9683. var dragAndDrop = function() {
  9684. // There is *some* kind of drag-and-drop support in IE6-8, but I
  9685. // couldn't get it to work yet.
  9686. if (ie && ie_version < 9) return false;
  9687. var div = elt('div');
  9688. return "draggable" in div || "dragDrop" in div;
  9689. }();
  9690. var zwspSupported;
  9691. function zeroWidthElement(measure) {
  9692. if (zwspSupported == null) {
  9693. var test = elt("span", "\u200b");
  9694. removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")]));
  9695. if (measure.firstChild.offsetHeight != 0)
  9696. zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8);
  9697. }
  9698. var node = zwspSupported ? elt("span", "\u200b") :
  9699. elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px");
  9700. node.setAttribute("cm-text", "");
  9701. return node;
  9702. }
  9703. // Feature-detect IE's crummy client rect reporting for bidi text
  9704. var badBidiRects;
  9705. function hasBadBidiRects(measure) {
  9706. if (badBidiRects != null) return badBidiRects;
  9707. var txt = removeChildrenAndAdd(measure, document.createTextNode("A\u062eA"));
  9708. var r0 = range(txt, 0, 1).getBoundingClientRect();
  9709. if (!r0 || r0.left == r0.right) return false; // Safari returns null in some cases (#2780)
  9710. var r1 = range(txt, 1, 2).getBoundingClientRect();
  9711. return badBidiRects = (r1.right - r0.right < 3);
  9712. }
  9713. // See if "".split is the broken IE version, if so, provide an
  9714. // alternative way to split lines.
  9715. var splitLinesAuto = CodeMirror.splitLines = "\n\nb".split(/\n/).length != 3 ? function(string) {
  9716. var pos = 0, result = [], l = string.length;
  9717. while (pos <= l) {
  9718. var nl = string.indexOf("\n", pos);
  9719. if (nl == -1) nl = string.length;
  9720. var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl);
  9721. var rt = line.indexOf("\r");
  9722. if (rt != -1) {
  9723. result.push(line.slice(0, rt));
  9724. pos += rt + 1;
  9725. } else {
  9726. result.push(line);
  9727. pos = nl + 1;
  9728. }
  9729. }
  9730. return result;
  9731. } : function(string){return string.split(/\r\n?|\n/);};
  9732. var hasSelection = window.getSelection ? function(te) {
  9733. try { return te.selectionStart != te.selectionEnd; }
  9734. catch(e) { return false; }
  9735. } : function(te) {
  9736. try {var range = te.ownerDocument.selection.createRange();}
  9737. catch(e) {}
  9738. if (!range || range.parentElement() != te) return false;
  9739. return range.compareEndPoints("StartToEnd", range) != 0;
  9740. };
  9741. var hasCopyEvent = (function() {
  9742. var e = elt("div");
  9743. if ("oncopy" in e) return true;
  9744. e.setAttribute("oncopy", "return;");
  9745. return typeof e.oncopy == "function";
  9746. })();
  9747. var badZoomedRects = null;
  9748. function hasBadZoomedRects(measure) {
  9749. if (badZoomedRects != null) return badZoomedRects;
  9750. var node = removeChildrenAndAdd(measure, elt("span", "x"));
  9751. var normal = node.getBoundingClientRect();
  9752. var fromRange = range(node, 0, 1).getBoundingClientRect();
  9753. return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1;
  9754. }
  9755. // KEY NAMES
  9756. var keyNames = CodeMirror.keyNames = {
  9757. 3: "Enter", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt",
  9758. 19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End",
  9759. 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert",
  9760. 46: "Delete", 59: ";", 61: "=", 91: "Mod", 92: "Mod", 93: "Mod",
  9761. 106: "*", 107: "=", 109: "-", 110: ".", 111: "/", 127: "Delete",
  9762. 173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\",
  9763. 221: "]", 222: "'", 63232: "Up", 63233: "Down", 63234: "Left", 63235: "Right", 63272: "Delete",
  9764. 63273: "Home", 63275: "End", 63276: "PageUp", 63277: "PageDown", 63302: "Insert"
  9765. };
  9766. (function() {
  9767. // Number keys
  9768. for (var i = 0; i < 10; i++) keyNames[i + 48] = keyNames[i + 96] = String(i);
  9769. // Alphabetic keys
  9770. for (var i = 65; i <= 90; i++) keyNames[i] = String.fromCharCode(i);
  9771. // Function keys
  9772. for (var i = 1; i <= 12; i++) keyNames[i + 111] = keyNames[i + 63235] = "F" + i;
  9773. })();
  9774. // BIDI HELPERS
  9775. function iterateBidiSections(order, from, to, f) {
  9776. if (!order) return f(from, to, "ltr");
  9777. var found = false;
  9778. for (var i = 0; i < order.length; ++i) {
  9779. var part = order[i];
  9780. if (part.from < to && part.to > from || from == to && part.to == from) {
  9781. f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr");
  9782. found = true;
  9783. }
  9784. }
  9785. if (!found) f(from, to, "ltr");
  9786. }
  9787. function bidiLeft(part) { return part.level % 2 ? part.to : part.from; }
  9788. function bidiRight(part) { return part.level % 2 ? part.from : part.to; }
  9789. function lineLeft(line) { var order = getOrder(line); return order ? bidiLeft(order[0]) : 0; }
  9790. function lineRight(line) {
  9791. var order = getOrder(line);
  9792. if (!order) return line.text.length;
  9793. return bidiRight(lst(order));
  9794. }
  9795. function lineStart(cm, lineN) {
  9796. var line = getLine(cm.doc, lineN);
  9797. var visual = visualLine(line);
  9798. if (visual != line) lineN = lineNo(visual);
  9799. var order = getOrder(visual);
  9800. var ch = !order ? 0 : order[0].level % 2 ? lineRight(visual) : lineLeft(visual);
  9801. return Pos(lineN, ch);
  9802. }
  9803. function lineEnd(cm, lineN) {
  9804. var merged, line = getLine(cm.doc, lineN);
  9805. while (merged = collapsedSpanAtEnd(line)) {
  9806. line = merged.find(1, true).line;
  9807. lineN = null;
  9808. }
  9809. var order = getOrder(line);
  9810. var ch = !order ? line.text.length : order[0].level % 2 ? lineLeft(line) : lineRight(line);
  9811. return Pos(lineN == null ? lineNo(line) : lineN, ch);
  9812. }
  9813. function lineStartSmart(cm, pos) {
  9814. var start = lineStart(cm, pos.line);
  9815. var line = getLine(cm.doc, start.line);
  9816. var order = getOrder(line);
  9817. if (!order || order[0].level == 0) {
  9818. var firstNonWS = Math.max(0, line.text.search(/\S/));
  9819. var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch;
  9820. return Pos(start.line, inWS ? 0 : firstNonWS);
  9821. }
  9822. return start;
  9823. }
  9824. function compareBidiLevel(order, a, b) {
  9825. var linedir = order[0].level;
  9826. if (a == linedir) return true;
  9827. if (b == linedir) return false;
  9828. return a < b;
  9829. }
  9830. var bidiOther;
  9831. function getBidiPartAt(order, pos) {
  9832. bidiOther = null;
  9833. for (var i = 0, found; i < order.length; ++i) {
  9834. var cur = order[i];
  9835. if (cur.from < pos && cur.to > pos) return i;
  9836. if ((cur.from == pos || cur.to == pos)) {
  9837. if (found == null) {
  9838. found = i;
  9839. } else if (compareBidiLevel(order, cur.level, order[found].level)) {
  9840. if (cur.from != cur.to) bidiOther = found;
  9841. return i;
  9842. } else {
  9843. if (cur.from != cur.to) bidiOther = i;
  9844. return found;
  9845. }
  9846. }
  9847. }
  9848. return found;
  9849. }
  9850. function moveInLine(line, pos, dir, byUnit) {
  9851. if (!byUnit) return pos + dir;
  9852. do pos += dir;
  9853. while (pos > 0 && isExtendingChar(line.text.charAt(pos)));
  9854. return pos;
  9855. }
  9856. // This is needed in order to move 'visually' through bi-directional
  9857. // text -- i.e., pressing left should make the cursor go left, even
  9858. // when in RTL text. The tricky part is the 'jumps', where RTL and
  9859. // LTR text touch each other. This often requires the cursor offset
  9860. // to move more than one unit, in order to visually move one unit.
  9861. function moveVisually(line, start, dir, byUnit) {
  9862. var bidi = getOrder(line);
  9863. if (!bidi) return moveLogically(line, start, dir, byUnit);
  9864. var pos = getBidiPartAt(bidi, start), part = bidi[pos];
  9865. var target = moveInLine(line, start, part.level % 2 ? -dir : dir, byUnit);
  9866. for (;;) {
  9867. if (target > part.from && target < part.to) return target;
  9868. if (target == part.from || target == part.to) {
  9869. if (getBidiPartAt(bidi, target) == pos) return target;
  9870. part = bidi[pos += dir];
  9871. return (dir > 0) == part.level % 2 ? part.to : part.from;
  9872. } else {
  9873. part = bidi[pos += dir];
  9874. if (!part) return null;
  9875. if ((dir > 0) == part.level % 2)
  9876. target = moveInLine(line, part.to, -1, byUnit);
  9877. else
  9878. target = moveInLine(line, part.from, 1, byUnit);
  9879. }
  9880. }
  9881. }
  9882. function moveLogically(line, start, dir, byUnit) {
  9883. var target = start + dir;
  9884. if (byUnit) while (target > 0 && isExtendingChar(line.text.charAt(target))) target += dir;
  9885. return target < 0 || target > line.text.length ? null : target;
  9886. }
  9887. // Bidirectional ordering algorithm
  9888. // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm
  9889. // that this (partially) implements.
  9890. // One-char codes used for character types:
  9891. // L (L): Left-to-Right
  9892. // R (R): Right-to-Left
  9893. // r (AL): Right-to-Left Arabic
  9894. // 1 (EN): European Number
  9895. // + (ES): European Number Separator
  9896. // % (ET): European Number Terminator
  9897. // n (AN): Arabic Number
  9898. // , (CS): Common Number Separator
  9899. // m (NSM): Non-Spacing Mark
  9900. // b (BN): Boundary Neutral
  9901. // s (B): Paragraph Separator
  9902. // t (S): Segment Separator
  9903. // w (WS): Whitespace
  9904. // N (ON): Other Neutrals
  9905. // Returns null if characters are ordered as they appear
  9906. // (left-to-right), or an array of sections ({from, to, level}
  9907. // objects) in the order in which they occur visually.
  9908. var bidiOrdering = (function() {
  9909. // Character types for codepoints 0 to 0xff
  9910. var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN";
  9911. // Character types for codepoints 0x600 to 0x6ff
  9912. var arabicTypes = "rrrrrrrrrrrr,rNNmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmrrrrrrrnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmNmmmm";
  9913. function charType(code) {
  9914. if (code <= 0xf7) return lowTypes.charAt(code);
  9915. else if (0x590 <= code && code <= 0x5f4) return "R";
  9916. else if (0x600 <= code && code <= 0x6ed) return arabicTypes.charAt(code - 0x600);
  9917. else if (0x6ee <= code && code <= 0x8ac) return "r";
  9918. else if (0x2000 <= code && code <= 0x200b) return "w";
  9919. else if (code == 0x200c) return "b";
  9920. else return "L";
  9921. }
  9922. var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/;
  9923. var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/;
  9924. // Browsers seem to always treat the boundaries of block elements as being L.
  9925. var outerType = "L";
  9926. function BidiSpan(level, from, to) {
  9927. this.level = level;
  9928. this.from = from; this.to = to;
  9929. }
  9930. return function(str) {
  9931. if (!bidiRE.test(str)) return false;
  9932. var len = str.length, types = [];
  9933. for (var i = 0, type; i < len; ++i)
  9934. types.push(type = charType(str.charCodeAt(i)));
  9935. // W1. Examine each non-spacing mark (NSM) in the level run, and
  9936. // change the type of the NSM to the type of the previous
  9937. // character. If the NSM is at the start of the level run, it will
  9938. // get the type of sor.
  9939. for (var i = 0, prev = outerType; i < len; ++i) {
  9940. var type = types[i];
  9941. if (type == "m") types[i] = prev;
  9942. else prev = type;
  9943. }
  9944. // W2. Search backwards from each instance of a European number
  9945. // until the first strong type (R, L, AL, or sor) is found. If an
  9946. // AL is found, change the type of the European number to Arabic
  9947. // number.
  9948. // W3. Change all ALs to R.
  9949. for (var i = 0, cur = outerType; i < len; ++i) {
  9950. var type = types[i];
  9951. if (type == "1" && cur == "r") types[i] = "n";
  9952. else if (isStrong.test(type)) { cur = type; if (type == "r") types[i] = "R"; }
  9953. }
  9954. // W4. A single European separator between two European numbers
  9955. // changes to a European number. A single common separator between
  9956. // two numbers of the same type changes to that type.
  9957. for (var i = 1, prev = types[0]; i < len - 1; ++i) {
  9958. var type = types[i];
  9959. if (type == "+" && prev == "1" && types[i+1] == "1") types[i] = "1";
  9960. else if (type == "," && prev == types[i+1] &&
  9961. (prev == "1" || prev == "n")) types[i] = prev;
  9962. prev = type;
  9963. }
  9964. // W5. A sequence of European terminators adjacent to European
  9965. // numbers changes to all European numbers.
  9966. // W6. Otherwise, separators and terminators change to Other
  9967. // Neutral.
  9968. for (var i = 0; i < len; ++i) {
  9969. var type = types[i];
  9970. if (type == ",") types[i] = "N";
  9971. else if (type == "%") {
  9972. for (var end = i + 1; end < len && types[end] == "%"; ++end) {}
  9973. var replace = (i && types[i-1] == "!") || (end < len && types[end] == "1") ? "1" : "N";
  9974. for (var j = i; j < end; ++j) types[j] = replace;
  9975. i = end - 1;
  9976. }
  9977. }
  9978. // W7. Search backwards from each instance of a European number
  9979. // until the first strong type (R, L, or sor) is found. If an L is
  9980. // found, then change the type of the European number to L.
  9981. for (var i = 0, cur = outerType; i < len; ++i) {
  9982. var type = types[i];
  9983. if (cur == "L" && type == "1") types[i] = "L";
  9984. else if (isStrong.test(type)) cur = type;
  9985. }
  9986. // N1. A sequence of neutrals takes the direction of the
  9987. // surrounding strong text if the text on both sides has the same
  9988. // direction. European and Arabic numbers act as if they were R in
  9989. // terms of their influence on neutrals. Start-of-level-run (sor)
  9990. // and end-of-level-run (eor) are used at level run boundaries.
  9991. // N2. Any remaining neutrals take the embedding direction.
  9992. for (var i = 0; i < len; ++i) {
  9993. if (isNeutral.test(types[i])) {
  9994. for (var end = i + 1; end < len && isNeutral.test(types[end]); ++end) {}
  9995. var before = (i ? types[i-1] : outerType) == "L";
  9996. var after = (end < len ? types[end] : outerType) == "L";
  9997. var replace = before || after ? "L" : "R";
  9998. for (var j = i; j < end; ++j) types[j] = replace;
  9999. i = end - 1;
  10000. }
  10001. }
  10002. // Here we depart from the documented algorithm, in order to avoid
  10003. // building up an actual levels array. Since there are only three
  10004. // levels (0, 1, 2) in an implementation that doesn't take
  10005. // explicit embedding into account, we can build up the order on
  10006. // the fly, without following the level-based algorithm.
  10007. var order = [], m;
  10008. for (var i = 0; i < len;) {
  10009. if (countsAsLeft.test(types[i])) {
  10010. var start = i;
  10011. for (++i; i < len && countsAsLeft.test(types[i]); ++i) {}
  10012. order.push(new BidiSpan(0, start, i));
  10013. } else {
  10014. var pos = i, at = order.length;
  10015. for (++i; i < len && types[i] != "L"; ++i) {}
  10016. for (var j = pos; j < i;) {
  10017. if (countsAsNum.test(types[j])) {
  10018. if (pos < j) order.splice(at, 0, new BidiSpan(1, pos, j));
  10019. var nstart = j;
  10020. for (++j; j < i && countsAsNum.test(types[j]); ++j) {}
  10021. order.splice(at, 0, new BidiSpan(2, nstart, j));
  10022. pos = j;
  10023. } else ++j;
  10024. }
  10025. if (pos < i) order.splice(at, 0, new BidiSpan(1, pos, i));
  10026. }
  10027. }
  10028. if (order[0].level == 1 && (m = str.match(/^\s+/))) {
  10029. order[0].from = m[0].length;
  10030. order.unshift(new BidiSpan(0, 0, m[0].length));
  10031. }
  10032. if (lst(order).level == 1 && (m = str.match(/\s+$/))) {
  10033. lst(order).to -= m[0].length;
  10034. order.push(new BidiSpan(0, len - m[0].length, len));
  10035. }
  10036. if (order[0].level == 2)
  10037. order.unshift(new BidiSpan(1, order[0].to, order[0].to));
  10038. if (order[0].level != lst(order).level)
  10039. order.push(new BidiSpan(order[0].level, len, len));
  10040. return order;
  10041. };
  10042. })();
  10043. // THE END
  10044. CodeMirror.version = "5.15.2";
  10045. return CodeMirror;
  10046. });
  10047. },{}],11:[function(require,module,exports){
  10048. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  10049. // Distributed under an MIT license: http://codemirror.net/LICENSE
  10050. (function(mod) {
  10051. if (typeof exports == "object" && typeof module == "object") // CommonJS
  10052. mod(require("../../lib/codemirror"), require("../markdown/markdown"), require("../../addon/mode/overlay"));
  10053. else if (typeof define == "function" && define.amd) // AMD
  10054. define(["../../lib/codemirror", "../markdown/markdown", "../../addon/mode/overlay"], mod);
  10055. else // Plain browser env
  10056. mod(CodeMirror);
  10057. })(function(CodeMirror) {
  10058. "use strict";
  10059. 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
  10060. CodeMirror.defineMode("gfm", function(config, modeConfig) {
  10061. var codeDepth = 0;
  10062. function blankLine(state) {
  10063. state.code = false;
  10064. return null;
  10065. }
  10066. var gfmOverlay = {
  10067. startState: function() {
  10068. return {
  10069. code: false,
  10070. codeBlock: false,
  10071. ateSpace: false
  10072. };
  10073. },
  10074. copyState: function(s) {
  10075. return {
  10076. code: s.code,
  10077. codeBlock: s.codeBlock,
  10078. ateSpace: s.ateSpace
  10079. };
  10080. },
  10081. token: function(stream, state) {
  10082. state.combineTokens = null;
  10083. // Hack to prevent formatting override inside code blocks (block and inline)
  10084. if (state.codeBlock) {
  10085. if (stream.match(/^```+/)) {
  10086. state.codeBlock = false;
  10087. return null;
  10088. }
  10089. stream.skipToEnd();
  10090. return null;
  10091. }
  10092. if (stream.sol()) {
  10093. state.code = false;
  10094. }
  10095. if (stream.sol() && stream.match(/^```+/)) {
  10096. stream.skipToEnd();
  10097. state.codeBlock = true;
  10098. return null;
  10099. }
  10100. // If this block is changed, it may need to be updated in Markdown mode
  10101. if (stream.peek() === '`') {
  10102. stream.next();
  10103. var before = stream.pos;
  10104. stream.eatWhile('`');
  10105. var difference = 1 + stream.pos - before;
  10106. if (!state.code) {
  10107. codeDepth = difference;
  10108. state.code = true;
  10109. } else {
  10110. if (difference === codeDepth) { // Must be exact
  10111. state.code = false;
  10112. }
  10113. }
  10114. return null;
  10115. } else if (state.code) {
  10116. stream.next();
  10117. return null;
  10118. }
  10119. // Check if space. If so, links can be formatted later on
  10120. if (stream.eatSpace()) {
  10121. state.ateSpace = true;
  10122. return null;
  10123. }
  10124. if (stream.sol() || state.ateSpace) {
  10125. state.ateSpace = false;
  10126. if (modeConfig.gitHubSpice !== false) {
  10127. if(stream.match(/^(?:[a-zA-Z0-9\-_]+\/)?(?:[a-zA-Z0-9\-_]+@)?(?:[a-f0-9]{7,40}\b)/)) {
  10128. // User/Project@SHA
  10129. // User@SHA
  10130. // SHA
  10131. state.combineTokens = true;
  10132. return "link";
  10133. } else if (stream.match(/^(?:[a-zA-Z0-9\-_]+\/)?(?:[a-zA-Z0-9\-_]+)?#[0-9]+\b/)) {
  10134. // User/Project#Num
  10135. // User#Num
  10136. // #Num
  10137. state.combineTokens = true;
  10138. return "link";
  10139. }
  10140. }
  10141. }
  10142. if (stream.match(urlRE) &&
  10143. stream.string.slice(stream.start - 2, stream.start) != "](" &&
  10144. (stream.start == 0 || /\W/.test(stream.string.charAt(stream.start - 1)))) {
  10145. // URLs
  10146. // Taken from http://daringfireball.net/2010/07/improved_regex_for_matching_urls
  10147. // And then (issue #1160) simplified to make it not crash the Chrome Regexp engine
  10148. // And then limited url schemes to the CommonMark list, so foo:bar isn't matched as a URL
  10149. state.combineTokens = true;
  10150. return "link";
  10151. }
  10152. stream.next();
  10153. return null;
  10154. },
  10155. blankLine: blankLine
  10156. };
  10157. var markdownConfig = {
  10158. underscoresBreakWords: false,
  10159. taskLists: true,
  10160. fencedCodeBlocks: '```',
  10161. strikethrough: true
  10162. };
  10163. for (var attr in modeConfig) {
  10164. markdownConfig[attr] = modeConfig[attr];
  10165. }
  10166. markdownConfig.name = "markdown";
  10167. return CodeMirror.overlayMode(CodeMirror.getMode(config, markdownConfig), gfmOverlay);
  10168. }, "markdown");
  10169. CodeMirror.defineMIME("text/x-gfm", "gfm");
  10170. });
  10171. },{"../../addon/mode/overlay":8,"../../lib/codemirror":10,"../markdown/markdown":12}],12:[function(require,module,exports){
  10172. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  10173. // Distributed under an MIT license: http://codemirror.net/LICENSE
  10174. (function(mod) {
  10175. if (typeof exports == "object" && typeof module == "object") // CommonJS
  10176. mod(require("../../lib/codemirror"), require("../xml/xml"), require("../meta"));
  10177. else if (typeof define == "function" && define.amd) // AMD
  10178. define(["../../lib/codemirror", "../xml/xml", "../meta"], mod);
  10179. else // Plain browser env
  10180. mod(CodeMirror);
  10181. })(function(CodeMirror) {
  10182. "use strict";
  10183. CodeMirror.defineMode("markdown", function(cmCfg, modeCfg) {
  10184. var htmlMode = CodeMirror.getMode(cmCfg, "text/html");
  10185. var htmlModeMissing = htmlMode.name == "null"
  10186. function getMode(name) {
  10187. if (CodeMirror.findModeByName) {
  10188. var found = CodeMirror.findModeByName(name);
  10189. if (found) name = found.mime || found.mimes[0];
  10190. }
  10191. var mode = CodeMirror.getMode(cmCfg, name);
  10192. return mode.name == "null" ? null : mode;
  10193. }
  10194. // Should characters that affect highlighting be highlighted separate?
  10195. // Does not include characters that will be output (such as `1.` and `-` for lists)
  10196. if (modeCfg.highlightFormatting === undefined)
  10197. modeCfg.highlightFormatting = false;
  10198. // Maximum number of nested blockquotes. Set to 0 for infinite nesting.
  10199. // Excess `>` will emit `error` token.
  10200. if (modeCfg.maxBlockquoteDepth === undefined)
  10201. modeCfg.maxBlockquoteDepth = 0;
  10202. // Should underscores in words open/close em/strong?
  10203. if (modeCfg.underscoresBreakWords === undefined)
  10204. modeCfg.underscoresBreakWords = true;
  10205. // Use `fencedCodeBlocks` to configure fenced code blocks. false to
  10206. // disable, string to specify a precise regexp that the fence should
  10207. // match, and true to allow three or more backticks or tildes (as
  10208. // per CommonMark).
  10209. // Turn on task lists? ("- [ ] " and "- [x] ")
  10210. if (modeCfg.taskLists === undefined) modeCfg.taskLists = false;
  10211. // Turn on strikethrough syntax
  10212. if (modeCfg.strikethrough === undefined)
  10213. modeCfg.strikethrough = false;
  10214. // Allow token types to be overridden by user-provided token types.
  10215. if (modeCfg.tokenTypeOverrides === undefined)
  10216. modeCfg.tokenTypeOverrides = {};
  10217. var tokenTypes = {
  10218. header: "header",
  10219. code: "comment",
  10220. quote: "quote",
  10221. list1: "variable-2",
  10222. list2: "variable-3",
  10223. list3: "keyword",
  10224. hr: "hr",
  10225. image: "tag",
  10226. formatting: "formatting",
  10227. linkInline: "link",
  10228. linkEmail: "link",
  10229. linkText: "link",
  10230. linkHref: "string",
  10231. em: "em",
  10232. strong: "strong",
  10233. strikethrough: "strikethrough"
  10234. };
  10235. for (var tokenType in tokenTypes) {
  10236. if (tokenTypes.hasOwnProperty(tokenType) && modeCfg.tokenTypeOverrides[tokenType]) {
  10237. tokenTypes[tokenType] = modeCfg.tokenTypeOverrides[tokenType];
  10238. }
  10239. }
  10240. var hrRE = /^([*\-_])(?:\s*\1){2,}\s*$/
  10241. , ulRE = /^[*\-+]\s+/
  10242. , olRE = /^[0-9]+([.)])\s+/
  10243. , taskListRE = /^\[(x| )\](?=\s)/ // Must follow ulRE or olRE
  10244. , atxHeaderRE = modeCfg.allowAtxHeaderWithoutSpace ? /^(#+)/ : /^(#+)(?: |$)/
  10245. , setextHeaderRE = /^ *(?:\={1,}|-{1,})\s*$/
  10246. , textRE = /^[^#!\[\]*_\\<>` "'(~]+/
  10247. , fencedCodeRE = new RegExp("^(" + (modeCfg.fencedCodeBlocks === true ? "~~~+|```+" : modeCfg.fencedCodeBlocks) +
  10248. ")[ \\t]*([\\w+#\-]*)");
  10249. function switchInline(stream, state, f) {
  10250. state.f = state.inline = f;
  10251. return f(stream, state);
  10252. }
  10253. function switchBlock(stream, state, f) {
  10254. state.f = state.block = f;
  10255. return f(stream, state);
  10256. }
  10257. function lineIsEmpty(line) {
  10258. return !line || !/\S/.test(line.string)
  10259. }
  10260. // Blocks
  10261. function blankLine(state) {
  10262. // Reset linkTitle state
  10263. state.linkTitle = false;
  10264. // Reset EM state
  10265. state.em = false;
  10266. // Reset STRONG state
  10267. state.strong = false;
  10268. // Reset strikethrough state
  10269. state.strikethrough = false;
  10270. // Reset state.quote
  10271. state.quote = 0;
  10272. // Reset state.indentedCode
  10273. state.indentedCode = false;
  10274. if (htmlModeMissing && state.f == htmlBlock) {
  10275. state.f = inlineNormal;
  10276. state.block = blockNormal;
  10277. }
  10278. // Reset state.trailingSpace
  10279. state.trailingSpace = 0;
  10280. state.trailingSpaceNewLine = false;
  10281. // Mark this line as blank
  10282. state.prevLine = state.thisLine
  10283. state.thisLine = null
  10284. return null;
  10285. }
  10286. function blockNormal(stream, state) {
  10287. var sol = stream.sol();
  10288. var prevLineIsList = state.list !== false,
  10289. prevLineIsIndentedCode = state.indentedCode;
  10290. state.indentedCode = false;
  10291. if (prevLineIsList) {
  10292. if (state.indentationDiff >= 0) { // Continued list
  10293. if (state.indentationDiff < 4) { // Only adjust indentation if *not* a code block
  10294. state.indentation -= state.indentationDiff;
  10295. }
  10296. state.list = null;
  10297. } else if (state.indentation > 0) {
  10298. state.list = null;
  10299. } else { // No longer a list
  10300. state.list = false;
  10301. }
  10302. }
  10303. var match = null;
  10304. if (state.indentationDiff >= 4) {
  10305. stream.skipToEnd();
  10306. if (prevLineIsIndentedCode || lineIsEmpty(state.prevLine)) {
  10307. state.indentation -= 4;
  10308. state.indentedCode = true;
  10309. return tokenTypes.code;
  10310. } else {
  10311. return null;
  10312. }
  10313. } else if (stream.eatSpace()) {
  10314. return null;
  10315. } else if ((match = stream.match(atxHeaderRE)) && match[1].length <= 6) {
  10316. state.header = match[1].length;
  10317. if (modeCfg.highlightFormatting) state.formatting = "header";
  10318. state.f = state.inline;
  10319. return getType(state);
  10320. } else if (!lineIsEmpty(state.prevLine) && !state.quote && !prevLineIsList &&
  10321. !prevLineIsIndentedCode && (match = stream.match(setextHeaderRE))) {
  10322. state.header = match[0].charAt(0) == '=' ? 1 : 2;
  10323. if (modeCfg.highlightFormatting) state.formatting = "header";
  10324. state.f = state.inline;
  10325. return getType(state);
  10326. } else if (stream.eat('>')) {
  10327. state.quote = sol ? 1 : state.quote + 1;
  10328. if (modeCfg.highlightFormatting) state.formatting = "quote";
  10329. stream.eatSpace();
  10330. return getType(state);
  10331. } else if (stream.peek() === '[') {
  10332. return switchInline(stream, state, footnoteLink);
  10333. } else if (stream.match(hrRE, true)) {
  10334. state.hr = true;
  10335. return tokenTypes.hr;
  10336. } else if ((lineIsEmpty(state.prevLine) || prevLineIsList) && (stream.match(ulRE, false) || stream.match(olRE, false))) {
  10337. var listType = null;
  10338. if (stream.match(ulRE, true)) {
  10339. listType = 'ul';
  10340. } else {
  10341. stream.match(olRE, true);
  10342. listType = 'ol';
  10343. }
  10344. state.indentation = stream.column() + stream.current().length;
  10345. state.list = true;
  10346. // While this list item's marker's indentation
  10347. // is less than the deepest list item's content's indentation,
  10348. // pop the deepest list item indentation off the stack.
  10349. while (state.listStack && stream.column() < state.listStack[state.listStack.length - 1]) {
  10350. state.listStack.pop();
  10351. }
  10352. // Add this list item's content's indentation to the stack
  10353. state.listStack.push(state.indentation);
  10354. if (modeCfg.taskLists && stream.match(taskListRE, false)) {
  10355. state.taskList = true;
  10356. }
  10357. state.f = state.inline;
  10358. if (modeCfg.highlightFormatting) state.formatting = ["list", "list-" + listType];
  10359. return getType(state);
  10360. } else if (modeCfg.fencedCodeBlocks && (match = stream.match(fencedCodeRE, true))) {
  10361. state.fencedChars = match[1]
  10362. // try switching mode
  10363. state.localMode = getMode(match[2]);
  10364. if (state.localMode) state.localState = CodeMirror.startState(state.localMode);
  10365. state.f = state.block = local;
  10366. if (modeCfg.highlightFormatting) state.formatting = "code-block";
  10367. state.code = -1
  10368. return getType(state);
  10369. }
  10370. return switchInline(stream, state, state.inline);
  10371. }
  10372. function htmlBlock(stream, state) {
  10373. var style = htmlMode.token(stream, state.htmlState);
  10374. if (!htmlModeMissing) {
  10375. var inner = CodeMirror.innerMode(htmlMode, state.htmlState)
  10376. if ((inner.mode.name == "xml" && inner.state.tagStart === null &&
  10377. (!inner.state.context && inner.state.tokenize.isInText)) ||
  10378. (state.md_inside && stream.current().indexOf(">") > -1)) {
  10379. state.f = inlineNormal;
  10380. state.block = blockNormal;
  10381. state.htmlState = null;
  10382. }
  10383. }
  10384. return style;
  10385. }
  10386. function local(stream, state) {
  10387. if (state.fencedChars && stream.match(state.fencedChars, false)) {
  10388. state.localMode = state.localState = null;
  10389. state.f = state.block = leavingLocal;
  10390. return null;
  10391. } else if (state.localMode) {
  10392. return state.localMode.token(stream, state.localState);
  10393. } else {
  10394. stream.skipToEnd();
  10395. return tokenTypes.code;
  10396. }
  10397. }
  10398. function leavingLocal(stream, state) {
  10399. stream.match(state.fencedChars);
  10400. state.block = blockNormal;
  10401. state.f = inlineNormal;
  10402. state.fencedChars = null;
  10403. if (modeCfg.highlightFormatting) state.formatting = "code-block";
  10404. state.code = 1
  10405. var returnType = getType(state);
  10406. state.code = 0
  10407. return returnType;
  10408. }
  10409. // Inline
  10410. function getType(state) {
  10411. var styles = [];
  10412. if (state.formatting) {
  10413. styles.push(tokenTypes.formatting);
  10414. if (typeof state.formatting === "string") state.formatting = [state.formatting];
  10415. for (var i = 0; i < state.formatting.length; i++) {
  10416. styles.push(tokenTypes.formatting + "-" + state.formatting[i]);
  10417. if (state.formatting[i] === "header") {
  10418. styles.push(tokenTypes.formatting + "-" + state.formatting[i] + "-" + state.header);
  10419. }
  10420. // Add `formatting-quote` and `formatting-quote-#` for blockquotes
  10421. // Add `error` instead if the maximum blockquote nesting depth is passed
  10422. if (state.formatting[i] === "quote") {
  10423. if (!modeCfg.maxBlockquoteDepth || modeCfg.maxBlockquoteDepth >= state.quote) {
  10424. styles.push(tokenTypes.formatting + "-" + state.formatting[i] + "-" + state.quote);
  10425. } else {
  10426. styles.push("error");
  10427. }
  10428. }
  10429. }
  10430. }
  10431. if (state.taskOpen) {
  10432. styles.push("meta");
  10433. return styles.length ? styles.join(' ') : null;
  10434. }
  10435. if (state.taskClosed) {
  10436. styles.push("property");
  10437. return styles.length ? styles.join(' ') : null;
  10438. }
  10439. if (state.linkHref) {
  10440. styles.push(tokenTypes.linkHref, "url");
  10441. } else { // Only apply inline styles to non-url text
  10442. if (state.strong) { styles.push(tokenTypes.strong); }
  10443. if (state.em) { styles.push(tokenTypes.em); }
  10444. if (state.strikethrough) { styles.push(tokenTypes.strikethrough); }
  10445. if (state.linkText) { styles.push(tokenTypes.linkText); }
  10446. if (state.code) { styles.push(tokenTypes.code); }
  10447. }
  10448. if (state.header) { styles.push(tokenTypes.header, tokenTypes.header + "-" + state.header); }
  10449. if (state.quote) {
  10450. styles.push(tokenTypes.quote);
  10451. // Add `quote-#` where the maximum for `#` is modeCfg.maxBlockquoteDepth
  10452. if (!modeCfg.maxBlockquoteDepth || modeCfg.maxBlockquoteDepth >= state.quote) {
  10453. styles.push(tokenTypes.quote + "-" + state.quote);
  10454. } else {
  10455. styles.push(tokenTypes.quote + "-" + modeCfg.maxBlockquoteDepth);
  10456. }
  10457. }
  10458. if (state.list !== false) {
  10459. var listMod = (state.listStack.length - 1) % 3;
  10460. if (!listMod) {
  10461. styles.push(tokenTypes.list1);
  10462. } else if (listMod === 1) {
  10463. styles.push(tokenTypes.list2);
  10464. } else {
  10465. styles.push(tokenTypes.list3);
  10466. }
  10467. }
  10468. if (state.trailingSpaceNewLine) {
  10469. styles.push("trailing-space-new-line");
  10470. } else if (state.trailingSpace) {
  10471. styles.push("trailing-space-" + (state.trailingSpace % 2 ? "a" : "b"));
  10472. }
  10473. return styles.length ? styles.join(' ') : null;
  10474. }
  10475. function handleText(stream, state) {
  10476. if (stream.match(textRE, true)) {
  10477. return getType(state);
  10478. }
  10479. return undefined;
  10480. }
  10481. function inlineNormal(stream, state) {
  10482. var style = state.text(stream, state);
  10483. if (typeof style !== 'undefined')
  10484. return style;
  10485. if (state.list) { // List marker (*, +, -, 1., etc)
  10486. state.list = null;
  10487. return getType(state);
  10488. }
  10489. if (state.taskList) {
  10490. var taskOpen = stream.match(taskListRE, true)[1] !== "x";
  10491. if (taskOpen) state.taskOpen = true;
  10492. else state.taskClosed = true;
  10493. if (modeCfg.highlightFormatting) state.formatting = "task";
  10494. state.taskList = false;
  10495. return getType(state);
  10496. }
  10497. state.taskOpen = false;
  10498. state.taskClosed = false;
  10499. if (state.header && stream.match(/^#+$/, true)) {
  10500. if (modeCfg.highlightFormatting) state.formatting = "header";
  10501. return getType(state);
  10502. }
  10503. // Get sol() value now, before character is consumed
  10504. var sol = stream.sol();
  10505. var ch = stream.next();
  10506. // Matches link titles present on next line
  10507. if (state.linkTitle) {
  10508. state.linkTitle = false;
  10509. var matchCh = ch;
  10510. if (ch === '(') {
  10511. matchCh = ')';
  10512. }
  10513. matchCh = (matchCh+'').replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1");
  10514. var regex = '^\\s*(?:[^' + matchCh + '\\\\]+|\\\\\\\\|\\\\.)' + matchCh;
  10515. if (stream.match(new RegExp(regex), true)) {
  10516. return tokenTypes.linkHref;
  10517. }
  10518. }
  10519. // If this block is changed, it may need to be updated in GFM mode
  10520. if (ch === '`') {
  10521. var previousFormatting = state.formatting;
  10522. if (modeCfg.highlightFormatting) state.formatting = "code";
  10523. stream.eatWhile('`');
  10524. var count = stream.current().length
  10525. if (state.code == 0) {
  10526. state.code = count
  10527. return getType(state)
  10528. } else if (count == state.code) { // Must be exact
  10529. var t = getType(state)
  10530. state.code = 0
  10531. return t
  10532. } else {
  10533. state.formatting = previousFormatting
  10534. return getType(state)
  10535. }
  10536. } else if (state.code) {
  10537. return getType(state);
  10538. }
  10539. if (ch === '\\') {
  10540. stream.next();
  10541. if (modeCfg.highlightFormatting) {
  10542. var type = getType(state);
  10543. var formattingEscape = tokenTypes.formatting + "-escape";
  10544. return type ? type + " " + formattingEscape : formattingEscape;
  10545. }
  10546. }
  10547. if (ch === '!' && stream.match(/\[[^\]]*\] ?(?:\(|\[)/, false)) {
  10548. stream.match(/\[[^\]]*\]/);
  10549. state.inline = state.f = linkHref;
  10550. return tokenTypes.image;
  10551. }
  10552. if (ch === '[' && stream.match(/[^\]]*\](\(.*\)| ?\[.*?\])/, false)) {
  10553. state.linkText = true;
  10554. if (modeCfg.highlightFormatting) state.formatting = "link";
  10555. return getType(state);
  10556. }
  10557. if (ch === ']' && state.linkText && stream.match(/\(.*?\)| ?\[.*?\]/, false)) {
  10558. if (modeCfg.highlightFormatting) state.formatting = "link";
  10559. var type = getType(state);
  10560. state.linkText = false;
  10561. state.inline = state.f = linkHref;
  10562. return type;
  10563. }
  10564. if (ch === '<' && stream.match(/^(https?|ftps?):\/\/(?:[^\\>]|\\.)+>/, false)) {
  10565. state.f = state.inline = linkInline;
  10566. if (modeCfg.highlightFormatting) state.formatting = "link";
  10567. var type = getType(state);
  10568. if (type){
  10569. type += " ";
  10570. } else {
  10571. type = "";
  10572. }
  10573. return type + tokenTypes.linkInline;
  10574. }
  10575. if (ch === '<' && stream.match(/^[^> \\]+@(?:[^\\>]|\\.)+>/, false)) {
  10576. state.f = state.inline = linkInline;
  10577. if (modeCfg.highlightFormatting) state.formatting = "link";
  10578. var type = getType(state);
  10579. if (type){
  10580. type += " ";
  10581. } else {
  10582. type = "";
  10583. }
  10584. return type + tokenTypes.linkEmail;
  10585. }
  10586. if (ch === '<' && stream.match(/^(!--|\w)/, false)) {
  10587. var end = stream.string.indexOf(">", stream.pos);
  10588. if (end != -1) {
  10589. var atts = stream.string.substring(stream.start, end);
  10590. if (/markdown\s*=\s*('|"){0,1}1('|"){0,1}/.test(atts)) state.md_inside = true;
  10591. }
  10592. stream.backUp(1);
  10593. state.htmlState = CodeMirror.startState(htmlMode);
  10594. return switchBlock(stream, state, htmlBlock);
  10595. }
  10596. if (ch === '<' && stream.match(/^\/\w*?>/)) {
  10597. state.md_inside = false;
  10598. return "tag";
  10599. }
  10600. var ignoreUnderscore = false;
  10601. if (!modeCfg.underscoresBreakWords) {
  10602. if (ch === '_' && stream.peek() !== '_' && stream.match(/(\w)/, false)) {
  10603. var prevPos = stream.pos - 2;
  10604. if (prevPos >= 0) {
  10605. var prevCh = stream.string.charAt(prevPos);
  10606. if (prevCh !== '_' && prevCh.match(/(\w)/, false)) {
  10607. ignoreUnderscore = true;
  10608. }
  10609. }
  10610. }
  10611. }
  10612. if (ch === '*' || (ch === '_' && !ignoreUnderscore)) {
  10613. if (sol && stream.peek() === ' ') {
  10614. // Do nothing, surrounded by newline and space
  10615. } else if (state.strong === ch && stream.eat(ch)) { // Remove STRONG
  10616. if (modeCfg.highlightFormatting) state.formatting = "strong";
  10617. var t = getType(state);
  10618. state.strong = false;
  10619. return t;
  10620. } else if (!state.strong && stream.eat(ch)) { // Add STRONG
  10621. state.strong = ch;
  10622. if (modeCfg.highlightFormatting) state.formatting = "strong";
  10623. return getType(state);
  10624. } else if (state.em === ch) { // Remove EM
  10625. if (modeCfg.highlightFormatting) state.formatting = "em";
  10626. var t = getType(state);
  10627. state.em = false;
  10628. return t;
  10629. } else if (!state.em) { // Add EM
  10630. state.em = ch;
  10631. if (modeCfg.highlightFormatting) state.formatting = "em";
  10632. return getType(state);
  10633. }
  10634. } else if (ch === ' ') {
  10635. if (stream.eat('*') || stream.eat('_')) { // Probably surrounded by spaces
  10636. if (stream.peek() === ' ') { // Surrounded by spaces, ignore
  10637. return getType(state);
  10638. } else { // Not surrounded by spaces, back up pointer
  10639. stream.backUp(1);
  10640. }
  10641. }
  10642. }
  10643. if (modeCfg.strikethrough) {
  10644. if (ch === '~' && stream.eatWhile(ch)) {
  10645. if (state.strikethrough) {// Remove strikethrough
  10646. if (modeCfg.highlightFormatting) state.formatting = "strikethrough";
  10647. var t = getType(state);
  10648. state.strikethrough = false;
  10649. return t;
  10650. } else if (stream.match(/^[^\s]/, false)) {// Add strikethrough
  10651. state.strikethrough = true;
  10652. if (modeCfg.highlightFormatting) state.formatting = "strikethrough";
  10653. return getType(state);
  10654. }
  10655. } else if (ch === ' ') {
  10656. if (stream.match(/^~~/, true)) { // Probably surrounded by space
  10657. if (stream.peek() === ' ') { // Surrounded by spaces, ignore
  10658. return getType(state);
  10659. } else { // Not surrounded by spaces, back up pointer
  10660. stream.backUp(2);
  10661. }
  10662. }
  10663. }
  10664. }
  10665. if (ch === ' ') {
  10666. if (stream.match(/ +$/, false)) {
  10667. state.trailingSpace++;
  10668. } else if (state.trailingSpace) {
  10669. state.trailingSpaceNewLine = true;
  10670. }
  10671. }
  10672. return getType(state);
  10673. }
  10674. function linkInline(stream, state) {
  10675. var ch = stream.next();
  10676. if (ch === ">") {
  10677. state.f = state.inline = inlineNormal;
  10678. if (modeCfg.highlightFormatting) state.formatting = "link";
  10679. var type = getType(state);
  10680. if (type){
  10681. type += " ";
  10682. } else {
  10683. type = "";
  10684. }
  10685. return type + tokenTypes.linkInline;
  10686. }
  10687. stream.match(/^[^>]+/, true);
  10688. return tokenTypes.linkInline;
  10689. }
  10690. function linkHref(stream, state) {
  10691. // Check if space, and return NULL if so (to avoid marking the space)
  10692. if(stream.eatSpace()){
  10693. return null;
  10694. }
  10695. var ch = stream.next();
  10696. if (ch === '(' || ch === '[') {
  10697. state.f = state.inline = getLinkHrefInside(ch === "(" ? ")" : "]", 0);
  10698. if (modeCfg.highlightFormatting) state.formatting = "link-string";
  10699. state.linkHref = true;
  10700. return getType(state);
  10701. }
  10702. return 'error';
  10703. }
  10704. var linkRE = {
  10705. ")": /^(?:[^\\\(\)]|\\.|\((?:[^\\\(\)]|\\.)*\))*?(?=\))/,
  10706. "]": /^(?:[^\\\[\]]|\\.|\[(?:[^\\\[\\]]|\\.)*\])*?(?=\])/
  10707. }
  10708. function getLinkHrefInside(endChar) {
  10709. return function(stream, state) {
  10710. var ch = stream.next();
  10711. if (ch === endChar) {
  10712. state.f = state.inline = inlineNormal;
  10713. if (modeCfg.highlightFormatting) state.formatting = "link-string";
  10714. var returnState = getType(state);
  10715. state.linkHref = false;
  10716. return returnState;
  10717. }
  10718. stream.match(linkRE[endChar])
  10719. state.linkHref = true;
  10720. return getType(state);
  10721. };
  10722. }
  10723. function footnoteLink(stream, state) {
  10724. if (stream.match(/^([^\]\\]|\\.)*\]:/, false)) {
  10725. state.f = footnoteLinkInside;
  10726. stream.next(); // Consume [
  10727. if (modeCfg.highlightFormatting) state.formatting = "link";
  10728. state.linkText = true;
  10729. return getType(state);
  10730. }
  10731. return switchInline(stream, state, inlineNormal);
  10732. }
  10733. function footnoteLinkInside(stream, state) {
  10734. if (stream.match(/^\]:/, true)) {
  10735. state.f = state.inline = footnoteUrl;
  10736. if (modeCfg.highlightFormatting) state.formatting = "link";
  10737. var returnType = getType(state);
  10738. state.linkText = false;
  10739. return returnType;
  10740. }
  10741. stream.match(/^([^\]\\]|\\.)+/, true);
  10742. return tokenTypes.linkText;
  10743. }
  10744. function footnoteUrl(stream, state) {
  10745. // Check if space, and return NULL if so (to avoid marking the space)
  10746. if(stream.eatSpace()){
  10747. return null;
  10748. }
  10749. // Match URL
  10750. stream.match(/^[^\s]+/, true);
  10751. // Check for link title
  10752. if (stream.peek() === undefined) { // End of line, set flag to check next line
  10753. state.linkTitle = true;
  10754. } else { // More content on line, check if link title
  10755. stream.match(/^(?:\s+(?:"(?:[^"\\]|\\\\|\\.)+"|'(?:[^'\\]|\\\\|\\.)+'|\((?:[^)\\]|\\\\|\\.)+\)))?/, true);
  10756. }
  10757. state.f = state.inline = inlineNormal;
  10758. return tokenTypes.linkHref + " url";
  10759. }
  10760. var mode = {
  10761. startState: function() {
  10762. return {
  10763. f: blockNormal,
  10764. prevLine: null,
  10765. thisLine: null,
  10766. block: blockNormal,
  10767. htmlState: null,
  10768. indentation: 0,
  10769. inline: inlineNormal,
  10770. text: handleText,
  10771. formatting: false,
  10772. linkText: false,
  10773. linkHref: false,
  10774. linkTitle: false,
  10775. code: 0,
  10776. em: false,
  10777. strong: false,
  10778. header: 0,
  10779. hr: false,
  10780. taskList: false,
  10781. list: false,
  10782. listStack: [],
  10783. quote: 0,
  10784. trailingSpace: 0,
  10785. trailingSpaceNewLine: false,
  10786. strikethrough: false,
  10787. fencedChars: null
  10788. };
  10789. },
  10790. copyState: function(s) {
  10791. return {
  10792. f: s.f,
  10793. prevLine: s.prevLine,
  10794. thisLine: s.thisLine,
  10795. block: s.block,
  10796. htmlState: s.htmlState && CodeMirror.copyState(htmlMode, s.htmlState),
  10797. indentation: s.indentation,
  10798. localMode: s.localMode,
  10799. localState: s.localMode ? CodeMirror.copyState(s.localMode, s.localState) : null,
  10800. inline: s.inline,
  10801. text: s.text,
  10802. formatting: false,
  10803. linkTitle: s.linkTitle,
  10804. code: s.code,
  10805. em: s.em,
  10806. strong: s.strong,
  10807. strikethrough: s.strikethrough,
  10808. header: s.header,
  10809. hr: s.hr,
  10810. taskList: s.taskList,
  10811. list: s.list,
  10812. listStack: s.listStack.slice(0),
  10813. quote: s.quote,
  10814. indentedCode: s.indentedCode,
  10815. trailingSpace: s.trailingSpace,
  10816. trailingSpaceNewLine: s.trailingSpaceNewLine,
  10817. md_inside: s.md_inside,
  10818. fencedChars: s.fencedChars
  10819. };
  10820. },
  10821. token: function(stream, state) {
  10822. // Reset state.formatting
  10823. state.formatting = false;
  10824. if (stream != state.thisLine) {
  10825. var forceBlankLine = state.header || state.hr;
  10826. // Reset state.header and state.hr
  10827. state.header = 0;
  10828. state.hr = false;
  10829. if (stream.match(/^\s*$/, true) || forceBlankLine) {
  10830. blankLine(state);
  10831. if (!forceBlankLine) return null
  10832. state.prevLine = null
  10833. }
  10834. state.prevLine = state.thisLine
  10835. state.thisLine = stream
  10836. // Reset state.taskList
  10837. state.taskList = false;
  10838. // Reset state.trailingSpace
  10839. state.trailingSpace = 0;
  10840. state.trailingSpaceNewLine = false;
  10841. state.f = state.block;
  10842. var indentation = stream.match(/^\s*/, true)[0].replace(/\t/g, ' ').length;
  10843. state.indentationDiff = Math.min(indentation - state.indentation, 4);
  10844. state.indentation = state.indentation + state.indentationDiff;
  10845. if (indentation > 0) return null;
  10846. }
  10847. return state.f(stream, state);
  10848. },
  10849. innerMode: function(state) {
  10850. if (state.block == htmlBlock) return {state: state.htmlState, mode: htmlMode};
  10851. if (state.localState) return {state: state.localState, mode: state.localMode};
  10852. return {state: state, mode: mode};
  10853. },
  10854. blankLine: blankLine,
  10855. getType: getType,
  10856. fold: "markdown"
  10857. };
  10858. return mode;
  10859. }, "xml");
  10860. CodeMirror.defineMIME("text/x-markdown", "markdown");
  10861. });
  10862. },{"../../lib/codemirror":10,"../meta":13,"../xml/xml":14}],13:[function(require,module,exports){
  10863. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  10864. // Distributed under an MIT license: http://codemirror.net/LICENSE
  10865. (function(mod) {
  10866. if (typeof exports == "object" && typeof module == "object") // CommonJS
  10867. mod(require("../lib/codemirror"));
  10868. else if (typeof define == "function" && define.amd) // AMD
  10869. define(["../lib/codemirror"], mod);
  10870. else // Plain browser env
  10871. mod(CodeMirror);
  10872. })(function(CodeMirror) {
  10873. "use strict";
  10874. CodeMirror.modeInfo = [
  10875. {name: "APL", mime: "text/apl", mode: "apl", ext: ["dyalog", "apl"]},
  10876. {name: "PGP", mimes: ["application/pgp", "application/pgp-keys", "application/pgp-signature"], mode: "asciiarmor", ext: ["pgp"]},
  10877. {name: "ASN.1", mime: "text/x-ttcn-asn", mode: "asn.1", ext: ["asn", "asn1"]},
  10878. {name: "Asterisk", mime: "text/x-asterisk", mode: "asterisk", file: /^extensions\.conf$/i},
  10879. {name: "Brainfuck", mime: "text/x-brainfuck", mode: "brainfuck", ext: ["b", "bf"]},
  10880. {name: "C", mime: "text/x-csrc", mode: "clike", ext: ["c", "h"]},
  10881. {name: "C++", mime: "text/x-c++src", mode: "clike", ext: ["cpp", "c++", "cc", "cxx", "hpp", "h++", "hh", "hxx"], alias: ["cpp"]},
  10882. {name: "Cobol", mime: "text/x-cobol", mode: "cobol", ext: ["cob", "cpy"]},
  10883. {name: "C#", mime: "text/x-csharp", mode: "clike", ext: ["cs"], alias: ["csharp"]},
  10884. {name: "Clojure", mime: "text/x-clojure", mode: "clojure", ext: ["clj", "cljc", "cljx"]},
  10885. {name: "ClojureScript", mime: "text/x-clojurescript", mode: "clojure", ext: ["cljs"]},
  10886. {name: "Closure Stylesheets (GSS)", mime: "text/x-gss", mode: "css", ext: ["gss"]},
  10887. {name: "CMake", mime: "text/x-cmake", mode: "cmake", ext: ["cmake", "cmake.in"], file: /^CMakeLists.txt$/},
  10888. {name: "CoffeeScript", mime: "text/x-coffeescript", mode: "coffeescript", ext: ["coffee"], alias: ["coffee", "coffee-script"]},
  10889. {name: "Common Lisp", mime: "text/x-common-lisp", mode: "commonlisp", ext: ["cl", "lisp", "el"], alias: ["lisp"]},
  10890. {name: "Cypher", mime: "application/x-cypher-query", mode: "cypher", ext: ["cyp", "cypher"]},
  10891. {name: "Cython", mime: "text/x-cython", mode: "python", ext: ["pyx", "pxd", "pxi"]},
  10892. {name: "Crystal", mime: "text/x-crystal", mode: "crystal", ext: ["cr"]},
  10893. {name: "CSS", mime: "text/css", mode: "css", ext: ["css"]},
  10894. {name: "CQL", mime: "text/x-cassandra", mode: "sql", ext: ["cql"]},
  10895. {name: "D", mime: "text/x-d", mode: "d", ext: ["d"]},
  10896. {name: "Dart", mimes: ["application/dart", "text/x-dart"], mode: "dart", ext: ["dart"]},
  10897. {name: "diff", mime: "text/x-diff", mode: "diff", ext: ["diff", "patch"]},
  10898. {name: "Django", mime: "text/x-django", mode: "django"},
  10899. {name: "Dockerfile", mime: "text/x-dockerfile", mode: "dockerfile", file: /^Dockerfile$/},
  10900. {name: "DTD", mime: "application/xml-dtd", mode: "dtd", ext: ["dtd"]},
  10901. {name: "Dylan", mime: "text/x-dylan", mode: "dylan", ext: ["dylan", "dyl", "intr"]},
  10902. {name: "EBNF", mime: "text/x-ebnf", mode: "ebnf"},
  10903. {name: "ECL", mime: "text/x-ecl", mode: "ecl", ext: ["ecl"]},
  10904. {name: "edn", mime: "application/edn", mode: "clojure", ext: ["edn"]},
  10905. {name: "Eiffel", mime: "text/x-eiffel", mode: "eiffel", ext: ["e"]},
  10906. {name: "Elm", mime: "text/x-elm", mode: "elm", ext: ["elm"]},
  10907. {name: "Embedded Javascript", mime: "application/x-ejs", mode: "htmlembedded", ext: ["ejs"]},
  10908. {name: "Embedded Ruby", mime: "application/x-erb", mode: "htmlembedded", ext: ["erb"]},
  10909. {name: "Erlang", mime: "text/x-erlang", mode: "erlang", ext: ["erl"]},
  10910. {name: "Factor", mime: "text/x-factor", mode: "factor", ext: ["factor"]},
  10911. {name: "FCL", mime: "text/x-fcl", mode: "fcl"},
  10912. {name: "Forth", mime: "text/x-forth", mode: "forth", ext: ["forth", "fth", "4th"]},
  10913. {name: "Fortran", mime: "text/x-fortran", mode: "fortran", ext: ["f", "for", "f77", "f90"]},
  10914. {name: "F#", mime: "text/x-fsharp", mode: "mllike", ext: ["fs"], alias: ["fsharp"]},
  10915. {name: "Gas", mime: "text/x-gas", mode: "gas", ext: ["s"]},
  10916. {name: "Gherkin", mime: "text/x-feature", mode: "gherkin", ext: ["feature"]},
  10917. {name: "GitHub Flavored Markdown", mime: "text/x-gfm", mode: "gfm", file: /^(readme|contributing|history).md$/i},
  10918. {name: "Go", mime: "text/x-go", mode: "go", ext: ["go"]},
  10919. {name: "Groovy", mime: "text/x-groovy", mode: "groovy", ext: ["groovy", "gradle"]},
  10920. {name: "HAML", mime: "text/x-haml", mode: "haml", ext: ["haml"]},
  10921. {name: "Haskell", mime: "text/x-haskell", mode: "haskell", ext: ["hs"]},
  10922. {name: "Haskell (Literate)", mime: "text/x-literate-haskell", mode: "haskell-literate", ext: ["lhs"]},
  10923. {name: "Haxe", mime: "text/x-haxe", mode: "haxe", ext: ["hx"]},
  10924. {name: "HXML", mime: "text/x-hxml", mode: "haxe", ext: ["hxml"]},
  10925. {name: "ASP.NET", mime: "application/x-aspx", mode: "htmlembedded", ext: ["aspx"], alias: ["asp", "aspx"]},
  10926. {name: "HTML", mime: "text/html", mode: "htmlmixed", ext: ["html", "htm"], alias: ["xhtml"]},
  10927. {name: "HTTP", mime: "message/http", mode: "http"},
  10928. {name: "IDL", mime: "text/x-idl", mode: "idl", ext: ["pro"]},
  10929. {name: "Jade", mime: "text/x-jade", mode: "jade", ext: ["jade"]},
  10930. {name: "Java", mime: "text/x-java", mode: "clike", ext: ["java"]},
  10931. {name: "Java Server Pages", mime: "application/x-jsp", mode: "htmlembedded", ext: ["jsp"], alias: ["jsp"]},
  10932. {name: "JavaScript", mimes: ["text/javascript", "text/ecmascript", "application/javascript", "application/x-javascript", "application/ecmascript"],
  10933. mode: "javascript", ext: ["js"], alias: ["ecmascript", "js", "node"]},
  10934. {name: "JSON", mimes: ["application/json", "application/x-json"], mode: "javascript", ext: ["json", "map"], alias: ["json5"]},
  10935. {name: "JSON-LD", mime: "application/ld+json", mode: "javascript", ext: ["jsonld"], alias: ["jsonld"]},
  10936. {name: "JSX", mime: "text/jsx", mode: "jsx", ext: ["jsx"]},
  10937. {name: "Jinja2", mime: "null", mode: "jinja2"},
  10938. {name: "Julia", mime: "text/x-julia", mode: "julia", ext: ["jl"]},
  10939. {name: "Kotlin", mime: "text/x-kotlin", mode: "clike", ext: ["kt"]},
  10940. {name: "LESS", mime: "text/x-less", mode: "css", ext: ["less"]},
  10941. {name: "LiveScript", mime: "text/x-livescript", mode: "livescript", ext: ["ls"], alias: ["ls"]},
  10942. {name: "Lua", mime: "text/x-lua", mode: "lua", ext: ["lua"]},
  10943. {name: "Markdown", mime: "text/x-markdown", mode: "markdown", ext: ["markdown", "md", "mkd"]},
  10944. {name: "mIRC", mime: "text/mirc", mode: "mirc"},
  10945. {name: "MariaDB SQL", mime: "text/x-mariadb", mode: "sql"},
  10946. {name: "Mathematica", mime: "text/x-mathematica", mode: "mathematica", ext: ["m", "nb"]},
  10947. {name: "Modelica", mime: "text/x-modelica", mode: "modelica", ext: ["mo"]},
  10948. {name: "MUMPS", mime: "text/x-mumps", mode: "mumps", ext: ["mps"]},
  10949. {name: "MS SQL", mime: "text/x-mssql", mode: "sql"},
  10950. {name: "mbox", mime: "application/mbox", mode: "mbox", ext: ["mbox"]},
  10951. {name: "MySQL", mime: "text/x-mysql", mode: "sql"},
  10952. {name: "Nginx", mime: "text/x-nginx-conf", mode: "nginx", file: /nginx.*\.conf$/i},
  10953. {name: "NSIS", mime: "text/x-nsis", mode: "nsis", ext: ["nsh", "nsi"]},
  10954. {name: "NTriples", mime: "text/n-triples", mode: "ntriples", ext: ["nt"]},
  10955. {name: "Objective C", mime: "text/x-objectivec", mode: "clike", ext: ["m", "mm"], alias: ["objective-c", "objc"]},
  10956. {name: "OCaml", mime: "text/x-ocaml", mode: "mllike", ext: ["ml", "mli", "mll", "mly"]},
  10957. {name: "Octave", mime: "text/x-octave", mode: "octave", ext: ["m"]},
  10958. {name: "Oz", mime: "text/x-oz", mode: "oz", ext: ["oz"]},
  10959. {name: "Pascal", mime: "text/x-pascal", mode: "pascal", ext: ["p", "pas"]},
  10960. {name: "PEG.js", mime: "null", mode: "pegjs", ext: ["jsonld"]},
  10961. {name: "Perl", mime: "text/x-perl", mode: "perl", ext: ["pl", "pm"]},
  10962. {name: "PHP", mime: "application/x-httpd-php", mode: "php", ext: ["php", "php3", "php4", "php5", "phtml"]},
  10963. {name: "Pig", mime: "text/x-pig", mode: "pig", ext: ["pig"]},
  10964. {name: "Plain Text", mime: "text/plain", mode: "null", ext: ["txt", "text", "conf", "def", "list", "log"]},
  10965. {name: "PLSQL", mime: "text/x-plsql", mode: "sql", ext: ["pls"]},
  10966. {name: "PowerShell", mime: "application/x-powershell", mode: "powershell", ext: ["ps1", "psd1", "psm1"]},
  10967. {name: "Properties files", mime: "text/x-properties", mode: "properties", ext: ["properties", "ini", "in"], alias: ["ini", "properties"]},
  10968. {name: "ProtoBuf", mime: "text/x-protobuf", mode: "protobuf", ext: ["proto"]},
  10969. {name: "Python", mime: "text/x-python", mode: "python", ext: ["BUILD", "bzl", "py", "pyw"], file: /^(BUCK|BUILD)$/},
  10970. {name: "Puppet", mime: "text/x-puppet", mode: "puppet", ext: ["pp"]},
  10971. {name: "Q", mime: "text/x-q", mode: "q", ext: ["q"]},
  10972. {name: "R", mime: "text/x-rsrc", mode: "r", ext: ["r"], alias: ["rscript"]},
  10973. {name: "reStructuredText", mime: "text/x-rst", mode: "rst", ext: ["rst"], alias: ["rst"]},
  10974. {name: "RPM Changes", mime: "text/x-rpm-changes", mode: "rpm"},
  10975. {name: "RPM Spec", mime: "text/x-rpm-spec", mode: "rpm", ext: ["spec"]},
  10976. {name: "Ruby", mime: "text/x-ruby", mode: "ruby", ext: ["rb"], alias: ["jruby", "macruby", "rake", "rb", "rbx"]},
  10977. {name: "Rust", mime: "text/x-rustsrc", mode: "rust", ext: ["rs"]},
  10978. {name: "SAS", mime: "text/x-sas", mode: "sas", ext: ["sas"]},
  10979. {name: "Sass", mime: "text/x-sass", mode: "sass", ext: ["sass"]},
  10980. {name: "Scala", mime: "text/x-scala", mode: "clike", ext: ["scala"]},
  10981. {name: "Scheme", mime: "text/x-scheme", mode: "scheme", ext: ["scm", "ss"]},
  10982. {name: "SCSS", mime: "text/x-scss", mode: "css", ext: ["scss"]},
  10983. {name: "Shell", mime: "text/x-sh", mode: "shell", ext: ["sh", "ksh", "bash"], alias: ["bash", "sh", "zsh"], file: /^PKGBUILD$/},
  10984. {name: "Sieve", mime: "application/sieve", mode: "sieve", ext: ["siv", "sieve"]},
  10985. {name: "Slim", mimes: ["text/x-slim", "application/x-slim"], mode: "slim", ext: ["slim"]},
  10986. {name: "Smalltalk", mime: "text/x-stsrc", mode: "smalltalk", ext: ["st"]},
  10987. {name: "Smarty", mime: "text/x-smarty", mode: "smarty", ext: ["tpl"]},
  10988. {name: "Solr", mime: "text/x-solr", mode: "solr"},
  10989. {name: "Soy", mime: "text/x-soy", mode: "soy", ext: ["soy"], alias: ["closure template"]},
  10990. {name: "SPARQL", mime: "application/sparql-query", mode: "sparql", ext: ["rq", "sparql"], alias: ["sparul"]},
  10991. {name: "Spreadsheet", mime: "text/x-spreadsheet", mode: "spreadsheet", alias: ["excel", "formula"]},
  10992. {name: "SQL", mime: "text/x-sql", mode: "sql", ext: ["sql"]},
  10993. {name: "Squirrel", mime: "text/x-squirrel", mode: "clike", ext: ["nut"]},
  10994. {name: "Swift", mime: "text/x-swift", mode: "swift", ext: ["swift"]},
  10995. {name: "sTeX", mime: "text/x-stex", mode: "stex"},
  10996. {name: "LaTeX", mime: "text/x-latex", mode: "stex", ext: ["text", "ltx"], alias: ["tex"]},
  10997. {name: "SystemVerilog", mime: "text/x-systemverilog", mode: "verilog", ext: ["v"]},
  10998. {name: "Tcl", mime: "text/x-tcl", mode: "tcl", ext: ["tcl"]},
  10999. {name: "Textile", mime: "text/x-textile", mode: "textile", ext: ["textile"]},
  11000. {name: "TiddlyWiki ", mime: "text/x-tiddlywiki", mode: "tiddlywiki"},
  11001. {name: "Tiki wiki", mime: "text/tiki", mode: "tiki"},
  11002. {name: "TOML", mime: "text/x-toml", mode: "toml", ext: ["toml"]},
  11003. {name: "Tornado", mime: "text/x-tornado", mode: "tornado"},
  11004. {name: "troff", mime: "text/troff", mode: "troff", ext: ["1", "2", "3", "4", "5", "6", "7", "8", "9"]},
  11005. {name: "TTCN", mime: "text/x-ttcn", mode: "ttcn", ext: ["ttcn", "ttcn3", "ttcnpp"]},
  11006. {name: "TTCN_CFG", mime: "text/x-ttcn-cfg", mode: "ttcn-cfg", ext: ["cfg"]},
  11007. {name: "Turtle", mime: "text/turtle", mode: "turtle", ext: ["ttl"]},
  11008. {name: "TypeScript", mime: "application/typescript", mode: "javascript", ext: ["ts"], alias: ["ts"]},
  11009. {name: "Twig", mime: "text/x-twig", mode: "twig"},
  11010. {name: "Web IDL", mime: "text/x-webidl", mode: "webidl", ext: ["webidl"]},
  11011. {name: "VB.NET", mime: "text/x-vb", mode: "vb", ext: ["vb"]},
  11012. {name: "VBScript", mime: "text/vbscript", mode: "vbscript", ext: ["vbs"]},
  11013. {name: "Velocity", mime: "text/velocity", mode: "velocity", ext: ["vtl"]},
  11014. {name: "Verilog", mime: "text/x-verilog", mode: "verilog", ext: ["v"]},
  11015. {name: "VHDL", mime: "text/x-vhdl", mode: "vhdl", ext: ["vhd", "vhdl"]},
  11016. {name: "XML", mimes: ["application/xml", "text/xml"], mode: "xml", ext: ["xml", "xsl", "xsd"], alias: ["rss", "wsdl", "xsd"]},
  11017. {name: "XQuery", mime: "application/xquery", mode: "xquery", ext: ["xy", "xquery"]},
  11018. {name: "Yacas", mime: "text/x-yacas", mode: "yacas", ext: ["ys"]},
  11019. {name: "YAML", mime: "text/x-yaml", mode: "yaml", ext: ["yaml", "yml"], alias: ["yml"]},
  11020. {name: "Z80", mime: "text/x-z80", mode: "z80", ext: ["z80"]},
  11021. {name: "mscgen", mime: "text/x-mscgen", mode: "mscgen", ext: ["mscgen", "mscin", "msc"]},
  11022. {name: "xu", mime: "text/x-xu", mode: "mscgen", ext: ["xu"]},
  11023. {name: "msgenny", mime: "text/x-msgenny", mode: "mscgen", ext: ["msgenny"]}
  11024. ];
  11025. // Ensure all modes have a mime property for backwards compatibility
  11026. for (var i = 0; i < CodeMirror.modeInfo.length; i++) {
  11027. var info = CodeMirror.modeInfo[i];
  11028. if (info.mimes) info.mime = info.mimes[0];
  11029. }
  11030. CodeMirror.findModeByMIME = function(mime) {
  11031. mime = mime.toLowerCase();
  11032. for (var i = 0; i < CodeMirror.modeInfo.length; i++) {
  11033. var info = CodeMirror.modeInfo[i];
  11034. if (info.mime == mime) return info;
  11035. if (info.mimes) for (var j = 0; j < info.mimes.length; j++)
  11036. if (info.mimes[j] == mime) return info;
  11037. }
  11038. };
  11039. CodeMirror.findModeByExtension = function(ext) {
  11040. for (var i = 0; i < CodeMirror.modeInfo.length; i++) {
  11041. var info = CodeMirror.modeInfo[i];
  11042. if (info.ext) for (var j = 0; j < info.ext.length; j++)
  11043. if (info.ext[j] == ext) return info;
  11044. }
  11045. };
  11046. CodeMirror.findModeByFileName = function(filename) {
  11047. for (var i = 0; i < CodeMirror.modeInfo.length; i++) {
  11048. var info = CodeMirror.modeInfo[i];
  11049. if (info.file && info.file.test(filename)) return info;
  11050. }
  11051. var dot = filename.lastIndexOf(".");
  11052. var ext = dot > -1 && filename.substring(dot + 1, filename.length);
  11053. if (ext) return CodeMirror.findModeByExtension(ext);
  11054. };
  11055. CodeMirror.findModeByName = function(name) {
  11056. name = name.toLowerCase();
  11057. for (var i = 0; i < CodeMirror.modeInfo.length; i++) {
  11058. var info = CodeMirror.modeInfo[i];
  11059. if (info.name.toLowerCase() == name) return info;
  11060. if (info.alias) for (var j = 0; j < info.alias.length; j++)
  11061. if (info.alias[j].toLowerCase() == name) return info;
  11062. }
  11063. };
  11064. });
  11065. },{"../lib/codemirror":10}],14:[function(require,module,exports){
  11066. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  11067. // Distributed under an MIT license: http://codemirror.net/LICENSE
  11068. (function(mod) {
  11069. if (typeof exports == "object" && typeof module == "object") // CommonJS
  11070. mod(require("../../lib/codemirror"));
  11071. else if (typeof define == "function" && define.amd) // AMD
  11072. define(["../../lib/codemirror"], mod);
  11073. else // Plain browser env
  11074. mod(CodeMirror);
  11075. })(function(CodeMirror) {
  11076. "use strict";
  11077. var htmlConfig = {
  11078. autoSelfClosers: {'area': true, 'base': true, 'br': true, 'col': true, 'command': true,
  11079. 'embed': true, 'frame': true, 'hr': true, 'img': true, 'input': true,
  11080. 'keygen': true, 'link': true, 'meta': true, 'param': true, 'source': true,
  11081. 'track': true, 'wbr': true, 'menuitem': true},
  11082. implicitlyClosed: {'dd': true, 'li': true, 'optgroup': true, 'option': true, 'p': true,
  11083. 'rp': true, 'rt': true, 'tbody': true, 'td': true, 'tfoot': true,
  11084. 'th': true, 'tr': true},
  11085. contextGrabbers: {
  11086. 'dd': {'dd': true, 'dt': true},
  11087. 'dt': {'dd': true, 'dt': true},
  11088. 'li': {'li': true},
  11089. 'option': {'option': true, 'optgroup': true},
  11090. 'optgroup': {'optgroup': true},
  11091. 'p': {'address': true, 'article': true, 'aside': true, 'blockquote': true, 'dir': true,
  11092. 'div': true, 'dl': true, 'fieldset': true, 'footer': true, 'form': true,
  11093. 'h1': true, 'h2': true, 'h3': true, 'h4': true, 'h5': true, 'h6': true,
  11094. 'header': true, 'hgroup': true, 'hr': true, 'menu': true, 'nav': true, 'ol': true,
  11095. 'p': true, 'pre': true, 'section': true, 'table': true, 'ul': true},
  11096. 'rp': {'rp': true, 'rt': true},
  11097. 'rt': {'rp': true, 'rt': true},
  11098. 'tbody': {'tbody': true, 'tfoot': true},
  11099. 'td': {'td': true, 'th': true},
  11100. 'tfoot': {'tbody': true},
  11101. 'th': {'td': true, 'th': true},
  11102. 'thead': {'tbody': true, 'tfoot': true},
  11103. 'tr': {'tr': true}
  11104. },
  11105. doNotIndent: {"pre": true},
  11106. allowUnquoted: true,
  11107. allowMissing: true,
  11108. caseFold: true
  11109. }
  11110. var xmlConfig = {
  11111. autoSelfClosers: {},
  11112. implicitlyClosed: {},
  11113. contextGrabbers: {},
  11114. doNotIndent: {},
  11115. allowUnquoted: false,
  11116. allowMissing: false,
  11117. caseFold: false
  11118. }
  11119. CodeMirror.defineMode("xml", function(editorConf, config_) {
  11120. var indentUnit = editorConf.indentUnit
  11121. var config = {}
  11122. var defaults = config_.htmlMode ? htmlConfig : xmlConfig
  11123. for (var prop in defaults) config[prop] = defaults[prop]
  11124. for (var prop in config_) config[prop] = config_[prop]
  11125. // Return variables for tokenizers
  11126. var type, setStyle;
  11127. function inText(stream, state) {
  11128. function chain(parser) {
  11129. state.tokenize = parser;
  11130. return parser(stream, state);
  11131. }
  11132. var ch = stream.next();
  11133. if (ch == "<") {
  11134. if (stream.eat("!")) {
  11135. if (stream.eat("[")) {
  11136. if (stream.match("CDATA[")) return chain(inBlock("atom", "]]>"));
  11137. else return null;
  11138. } else if (stream.match("--")) {
  11139. return chain(inBlock("comment", "-->"));
  11140. } else if (stream.match("DOCTYPE", true, true)) {
  11141. stream.eatWhile(/[\w\._\-]/);
  11142. return chain(doctype(1));
  11143. } else {
  11144. return null;
  11145. }
  11146. } else if (stream.eat("?")) {
  11147. stream.eatWhile(/[\w\._\-]/);
  11148. state.tokenize = inBlock("meta", "?>");
  11149. return "meta";
  11150. } else {
  11151. type = stream.eat("/") ? "closeTag" : "openTag";
  11152. state.tokenize = inTag;
  11153. return "tag bracket";
  11154. }
  11155. } else if (ch == "&") {
  11156. var ok;
  11157. if (stream.eat("#")) {
  11158. if (stream.eat("x")) {
  11159. ok = stream.eatWhile(/[a-fA-F\d]/) && stream.eat(";");
  11160. } else {
  11161. ok = stream.eatWhile(/[\d]/) && stream.eat(";");
  11162. }
  11163. } else {
  11164. ok = stream.eatWhile(/[\w\.\-:]/) && stream.eat(";");
  11165. }
  11166. return ok ? "atom" : "error";
  11167. } else {
  11168. stream.eatWhile(/[^&<]/);
  11169. return null;
  11170. }
  11171. }
  11172. inText.isInText = true;
  11173. function inTag(stream, state) {
  11174. var ch = stream.next();
  11175. if (ch == ">" || (ch == "/" && stream.eat(">"))) {
  11176. state.tokenize = inText;
  11177. type = ch == ">" ? "endTag" : "selfcloseTag";
  11178. return "tag bracket";
  11179. } else if (ch == "=") {
  11180. type = "equals";
  11181. return null;
  11182. } else if (ch == "<") {
  11183. state.tokenize = inText;
  11184. state.state = baseState;
  11185. state.tagName = state.tagStart = null;
  11186. var next = state.tokenize(stream, state);
  11187. return next ? next + " tag error" : "tag error";
  11188. } else if (/[\'\"]/.test(ch)) {
  11189. state.tokenize = inAttribute(ch);
  11190. state.stringStartCol = stream.column();
  11191. return state.tokenize(stream, state);
  11192. } else {
  11193. stream.match(/^[^\s\u00a0=<>\"\']*[^\s\u00a0=<>\"\'\/]/);
  11194. return "word";
  11195. }
  11196. }
  11197. function inAttribute(quote) {
  11198. var closure = function(stream, state) {
  11199. while (!stream.eol()) {
  11200. if (stream.next() == quote) {
  11201. state.tokenize = inTag;
  11202. break;
  11203. }
  11204. }
  11205. return "string";
  11206. };
  11207. closure.isInAttribute = true;
  11208. return closure;
  11209. }
  11210. function inBlock(style, terminator) {
  11211. return function(stream, state) {
  11212. while (!stream.eol()) {
  11213. if (stream.match(terminator)) {
  11214. state.tokenize = inText;
  11215. break;
  11216. }
  11217. stream.next();
  11218. }
  11219. return style;
  11220. };
  11221. }
  11222. function doctype(depth) {
  11223. return function(stream, state) {
  11224. var ch;
  11225. while ((ch = stream.next()) != null) {
  11226. if (ch == "<") {
  11227. state.tokenize = doctype(depth + 1);
  11228. return state.tokenize(stream, state);
  11229. } else if (ch == ">") {
  11230. if (depth == 1) {
  11231. state.tokenize = inText;
  11232. break;
  11233. } else {
  11234. state.tokenize = doctype(depth - 1);
  11235. return state.tokenize(stream, state);
  11236. }
  11237. }
  11238. }
  11239. return "meta";
  11240. };
  11241. }
  11242. function Context(state, tagName, startOfLine) {
  11243. this.prev = state.context;
  11244. this.tagName = tagName;
  11245. this.indent = state.indented;
  11246. this.startOfLine = startOfLine;
  11247. if (config.doNotIndent.hasOwnProperty(tagName) || (state.context && state.context.noIndent))
  11248. this.noIndent = true;
  11249. }
  11250. function popContext(state) {
  11251. if (state.context) state.context = state.context.prev;
  11252. }
  11253. function maybePopContext(state, nextTagName) {
  11254. var parentTagName;
  11255. while (true) {
  11256. if (!state.context) {
  11257. return;
  11258. }
  11259. parentTagName = state.context.tagName;
  11260. if (!config.contextGrabbers.hasOwnProperty(parentTagName) ||
  11261. !config.contextGrabbers[parentTagName].hasOwnProperty(nextTagName)) {
  11262. return;
  11263. }
  11264. popContext(state);
  11265. }
  11266. }
  11267. function baseState(type, stream, state) {
  11268. if (type == "openTag") {
  11269. state.tagStart = stream.column();
  11270. return tagNameState;
  11271. } else if (type == "closeTag") {
  11272. return closeTagNameState;
  11273. } else {
  11274. return baseState;
  11275. }
  11276. }
  11277. function tagNameState(type, stream, state) {
  11278. if (type == "word") {
  11279. state.tagName = stream.current();
  11280. setStyle = "tag";
  11281. return attrState;
  11282. } else {
  11283. setStyle = "error";
  11284. return tagNameState;
  11285. }
  11286. }
  11287. function closeTagNameState(type, stream, state) {
  11288. if (type == "word") {
  11289. var tagName = stream.current();
  11290. if (state.context && state.context.tagName != tagName &&
  11291. config.implicitlyClosed.hasOwnProperty(state.context.tagName))
  11292. popContext(state);
  11293. if ((state.context && state.context.tagName == tagName) || config.matchClosing === false) {
  11294. setStyle = "tag";
  11295. return closeState;
  11296. } else {
  11297. setStyle = "tag error";
  11298. return closeStateErr;
  11299. }
  11300. } else {
  11301. setStyle = "error";
  11302. return closeStateErr;
  11303. }
  11304. }
  11305. function closeState(type, _stream, state) {
  11306. if (type != "endTag") {
  11307. setStyle = "error";
  11308. return closeState;
  11309. }
  11310. popContext(state);
  11311. return baseState;
  11312. }
  11313. function closeStateErr(type, stream, state) {
  11314. setStyle = "error";
  11315. return closeState(type, stream, state);
  11316. }
  11317. function attrState(type, _stream, state) {
  11318. if (type == "word") {
  11319. setStyle = "attribute";
  11320. return attrEqState;
  11321. } else if (type == "endTag" || type == "selfcloseTag") {
  11322. var tagName = state.tagName, tagStart = state.tagStart;
  11323. state.tagName = state.tagStart = null;
  11324. if (type == "selfcloseTag" ||
  11325. config.autoSelfClosers.hasOwnProperty(tagName)) {
  11326. maybePopContext(state, tagName);
  11327. } else {
  11328. maybePopContext(state, tagName);
  11329. state.context = new Context(state, tagName, tagStart == state.indented);
  11330. }
  11331. return baseState;
  11332. }
  11333. setStyle = "error";
  11334. return attrState;
  11335. }
  11336. function attrEqState(type, stream, state) {
  11337. if (type == "equals") return attrValueState;
  11338. if (!config.allowMissing) setStyle = "error";
  11339. return attrState(type, stream, state);
  11340. }
  11341. function attrValueState(type, stream, state) {
  11342. if (type == "string") return attrContinuedState;
  11343. if (type == "word" && config.allowUnquoted) {setStyle = "string"; return attrState;}
  11344. setStyle = "error";
  11345. return attrState(type, stream, state);
  11346. }
  11347. function attrContinuedState(type, stream, state) {
  11348. if (type == "string") return attrContinuedState;
  11349. return attrState(type, stream, state);
  11350. }
  11351. return {
  11352. startState: function(baseIndent) {
  11353. var state = {tokenize: inText,
  11354. state: baseState,
  11355. indented: baseIndent || 0,
  11356. tagName: null, tagStart: null,
  11357. context: null}
  11358. if (baseIndent != null) state.baseIndent = baseIndent
  11359. return state
  11360. },
  11361. token: function(stream, state) {
  11362. if (!state.tagName && stream.sol())
  11363. state.indented = stream.indentation();
  11364. if (stream.eatSpace()) return null;
  11365. type = null;
  11366. var style = state.tokenize(stream, state);
  11367. if ((style || type) && style != "comment") {
  11368. setStyle = null;
  11369. state.state = state.state(type || style, stream, state);
  11370. if (setStyle)
  11371. style = setStyle == "error" ? style + " error" : setStyle;
  11372. }
  11373. return style;
  11374. },
  11375. indent: function(state, textAfter, fullLine) {
  11376. var context = state.context;
  11377. // Indent multi-line strings (e.g. css).
  11378. if (state.tokenize.isInAttribute) {
  11379. if (state.tagStart == state.indented)
  11380. return state.stringStartCol + 1;
  11381. else
  11382. return state.indented + indentUnit;
  11383. }
  11384. if (context && context.noIndent) return CodeMirror.Pass;
  11385. if (state.tokenize != inTag && state.tokenize != inText)
  11386. return fullLine ? fullLine.match(/^(\s*)/)[0].length : 0;
  11387. // Indent the starts of attribute names.
  11388. if (state.tagName) {
  11389. if (config.multilineTagIndentPastTag !== false)
  11390. return state.tagStart + state.tagName.length + 2;
  11391. else
  11392. return state.tagStart + indentUnit * (config.multilineTagIndentFactor || 1);
  11393. }
  11394. if (config.alignCDATA && /<!\[CDATA\[/.test(textAfter)) return 0;
  11395. var tagAfter = textAfter && /^<(\/)?([\w_:\.-]*)/.exec(textAfter);
  11396. if (tagAfter && tagAfter[1]) { // Closing tag spotted
  11397. while (context) {
  11398. if (context.tagName == tagAfter[2]) {
  11399. context = context.prev;
  11400. break;
  11401. } else if (config.implicitlyClosed.hasOwnProperty(context.tagName)) {
  11402. context = context.prev;
  11403. } else {
  11404. break;
  11405. }
  11406. }
  11407. } else if (tagAfter) { // Opening tag spotted
  11408. while (context) {
  11409. var grabbers = config.contextGrabbers[context.tagName];
  11410. if (grabbers && grabbers.hasOwnProperty(tagAfter[2]))
  11411. context = context.prev;
  11412. else
  11413. break;
  11414. }
  11415. }
  11416. while (context && context.prev && !context.startOfLine)
  11417. context = context.prev;
  11418. if (context) return context.indent + indentUnit;
  11419. else return state.baseIndent || 0;
  11420. },
  11421. electricInput: /<\/[\s\w:]+>$/,
  11422. blockCommentStart: "<!--",
  11423. blockCommentEnd: "-->",
  11424. configuration: config.htmlMode ? "html" : "xml",
  11425. helperType: config.htmlMode ? "html" : "xml",
  11426. skipAttribute: function(state) {
  11427. if (state.state == attrValueState)
  11428. state.state = attrState
  11429. }
  11430. };
  11431. });
  11432. CodeMirror.defineMIME("text/xml", "xml");
  11433. CodeMirror.defineMIME("application/xml", "xml");
  11434. if (!CodeMirror.mimeModes.hasOwnProperty("text/html"))
  11435. CodeMirror.defineMIME("text/html", {name: "xml", htmlMode: true});
  11436. });
  11437. },{"../../lib/codemirror":10}],15:[function(require,module,exports){
  11438. exports.read = function (buffer, offset, isLE, mLen, nBytes) {
  11439. var e, m
  11440. var eLen = nBytes * 8 - mLen - 1
  11441. var eMax = (1 << eLen) - 1
  11442. var eBias = eMax >> 1
  11443. var nBits = -7
  11444. var i = isLE ? (nBytes - 1) : 0
  11445. var d = isLE ? -1 : 1
  11446. var s = buffer[offset + i]
  11447. i += d
  11448. e = s & ((1 << (-nBits)) - 1)
  11449. s >>= (-nBits)
  11450. nBits += eLen
  11451. for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
  11452. m = e & ((1 << (-nBits)) - 1)
  11453. e >>= (-nBits)
  11454. nBits += mLen
  11455. for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
  11456. if (e === 0) {
  11457. e = 1 - eBias
  11458. } else if (e === eMax) {
  11459. return m ? NaN : ((s ? -1 : 1) * Infinity)
  11460. } else {
  11461. m = m + Math.pow(2, mLen)
  11462. e = e - eBias
  11463. }
  11464. return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
  11465. }
  11466. exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
  11467. var e, m, c
  11468. var eLen = nBytes * 8 - mLen - 1
  11469. var eMax = (1 << eLen) - 1
  11470. var eBias = eMax >> 1
  11471. var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
  11472. var i = isLE ? 0 : (nBytes - 1)
  11473. var d = isLE ? 1 : -1
  11474. var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
  11475. value = Math.abs(value)
  11476. if (isNaN(value) || value === Infinity) {
  11477. m = isNaN(value) ? 1 : 0
  11478. e = eMax
  11479. } else {
  11480. e = Math.floor(Math.log(value) / Math.LN2)
  11481. if (value * (c = Math.pow(2, -e)) < 1) {
  11482. e--
  11483. c *= 2
  11484. }
  11485. if (e + eBias >= 1) {
  11486. value += rt / c
  11487. } else {
  11488. value += rt * Math.pow(2, 1 - eBias)
  11489. }
  11490. if (value * c >= 2) {
  11491. e++
  11492. c /= 2
  11493. }
  11494. if (e + eBias >= eMax) {
  11495. m = 0
  11496. e = eMax
  11497. } else if (e + eBias >= 1) {
  11498. m = (value * c - 1) * Math.pow(2, mLen)
  11499. e = e + eBias
  11500. } else {
  11501. m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
  11502. e = 0
  11503. }
  11504. }
  11505. for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
  11506. e = (e << mLen) | m
  11507. eLen += mLen
  11508. for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
  11509. buffer[offset + i - d] |= s * 128
  11510. }
  11511. },{}],16:[function(require,module,exports){
  11512. var toString = {}.toString;
  11513. module.exports = Array.isArray || function (arr) {
  11514. return toString.call(arr) == '[object Array]';
  11515. };
  11516. },{}],17:[function(require,module,exports){
  11517. (function (global){
  11518. /**
  11519. * marked - a markdown parser
  11520. * Copyright (c) 2011-2014, Christopher Jeffrey. (MIT Licensed)
  11521. * https://github.com/chjj/marked
  11522. */
  11523. ;(function() {
  11524. /**
  11525. * Block-Level Grammar
  11526. */
  11527. var block = {
  11528. newline: /^\n+/,
  11529. code: /^( {4}[^\n]+\n*)+/,
  11530. fences: noop,
  11531. hr: /^( *[-*_]){3,} *(?:\n+|$)/,
  11532. heading: /^ *(#{1,6}) *([^\n]+?) *#* *(?:\n+|$)/,
  11533. nptable: noop,
  11534. lheading: /^([^\n]+)\n *(=|-){2,} *(?:\n+|$)/,
  11535. blockquote: /^( *>[^\n]+(\n(?!def)[^\n]+)*\n*)+/,
  11536. list: /^( *)(bull) [\s\S]+?(?:hr|def|\n{2,}(?! )(?!\1bull )\n*|\s*$)/,
  11537. html: /^ *(?:comment *(?:\n|\s*$)|closed *(?:\n{2,}|\s*$)|closing *(?:\n{2,}|\s*$))/,
  11538. def: /^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +["(]([^\n]+)[")])? *(?:\n+|$)/,
  11539. table: noop,
  11540. paragraph: /^((?:[^\n]+\n?(?!hr|heading|lheading|blockquote|tag|def))+)\n*/,
  11541. text: /^[^\n]+/
  11542. };
  11543. block.bullet = /(?:[*+-]|\d+\.)/;
  11544. block.item = /^( *)(bull) [^\n]*(?:\n(?!\1bull )[^\n]*)*/;
  11545. block.item = replace(block.item, 'gm')
  11546. (/bull/g, block.bullet)
  11547. ();
  11548. block.list = replace(block.list)
  11549. (/bull/g, block.bullet)
  11550. ('hr', '\\n+(?=\\1?(?:[-*_] *){3,}(?:\\n+|$))')
  11551. ('def', '\\n+(?=' + block.def.source + ')')
  11552. ();
  11553. block.blockquote = replace(block.blockquote)
  11554. ('def', block.def)
  11555. ();
  11556. block._tag = '(?!(?:'
  11557. + 'a|em|strong|small|s|cite|q|dfn|abbr|data|time|code'
  11558. + '|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo'
  11559. + '|span|br|wbr|ins|del|img)\\b)\\w+(?!:/|[^\\w\\s@]*@)\\b';
  11560. block.html = replace(block.html)
  11561. ('comment', /<!--[\s\S]*?-->/)
  11562. ('closed', /<(tag)[\s\S]+?<\/\1>/)
  11563. ('closing', /<tag(?:"[^"]*"|'[^']*'|[^'">])*?>/)
  11564. (/tag/g, block._tag)
  11565. ();
  11566. block.paragraph = replace(block.paragraph)
  11567. ('hr', block.hr)
  11568. ('heading', block.heading)
  11569. ('lheading', block.lheading)
  11570. ('blockquote', block.blockquote)
  11571. ('tag', '<' + block._tag)
  11572. ('def', block.def)
  11573. ();
  11574. /**
  11575. * Normal Block Grammar
  11576. */
  11577. block.normal = merge({}, block);
  11578. /**
  11579. * GFM Block Grammar
  11580. */
  11581. block.gfm = merge({}, block.normal, {
  11582. fences: /^ *(`{3,}|~{3,})[ \.]*(\S+)? *\n([\s\S]*?)\s*\1 *(?:\n+|$)/,
  11583. paragraph: /^/,
  11584. heading: /^ *(#{1,6}) +([^\n]+?) *#* *(?:\n+|$)/
  11585. });
  11586. block.gfm.paragraph = replace(block.paragraph)
  11587. ('(?!', '(?!'
  11588. + block.gfm.fences.source.replace('\\1', '\\2') + '|'
  11589. + block.list.source.replace('\\1', '\\3') + '|')
  11590. ();
  11591. /**
  11592. * GFM + Tables Block Grammar
  11593. */
  11594. block.tables = merge({}, block.gfm, {
  11595. nptable: /^ *(\S.*\|.*)\n *([-:]+ *\|[-| :]*)\n((?:.*\|.*(?:\n|$))*)\n*/,
  11596. table: /^ *\|(.+)\n *\|( *[-:]+[-| :]*)\n((?: *\|.*(?:\n|$))*)\n*/
  11597. });
  11598. /**
  11599. * Block Lexer
  11600. */
  11601. function Lexer(options) {
  11602. this.tokens = [];
  11603. this.tokens.links = {};
  11604. this.options = options || marked.defaults;
  11605. this.rules = block.normal;
  11606. if (this.options.gfm) {
  11607. if (this.options.tables) {
  11608. this.rules = block.tables;
  11609. } else {
  11610. this.rules = block.gfm;
  11611. }
  11612. }
  11613. }
  11614. /**
  11615. * Expose Block Rules
  11616. */
  11617. Lexer.rules = block;
  11618. /**
  11619. * Static Lex Method
  11620. */
  11621. Lexer.lex = function(src, options) {
  11622. var lexer = new Lexer(options);
  11623. return lexer.lex(src);
  11624. };
  11625. /**
  11626. * Preprocessing
  11627. */
  11628. Lexer.prototype.lex = function(src) {
  11629. src = src
  11630. .replace(/\r\n|\r/g, '\n')
  11631. .replace(/\t/g, ' ')
  11632. .replace(/\u00a0/g, ' ')
  11633. .replace(/\u2424/g, '\n');
  11634. return this.token(src, true);
  11635. };
  11636. /**
  11637. * Lexing
  11638. */
  11639. Lexer.prototype.token = function(src, top, bq) {
  11640. var src = src.replace(/^ +$/gm, '')
  11641. , next
  11642. , loose
  11643. , cap
  11644. , bull
  11645. , b
  11646. , item
  11647. , space
  11648. , i
  11649. , l;
  11650. while (src) {
  11651. // newline
  11652. if (cap = this.rules.newline.exec(src)) {
  11653. src = src.substring(cap[0].length);
  11654. if (cap[0].length > 1) {
  11655. this.tokens.push({
  11656. type: 'space'
  11657. });
  11658. }
  11659. }
  11660. // code
  11661. if (cap = this.rules.code.exec(src)) {
  11662. src = src.substring(cap[0].length);
  11663. cap = cap[0].replace(/^ {4}/gm, '');
  11664. this.tokens.push({
  11665. type: 'code',
  11666. text: !this.options.pedantic
  11667. ? cap.replace(/\n+$/, '')
  11668. : cap
  11669. });
  11670. continue;
  11671. }
  11672. // fences (gfm)
  11673. if (cap = this.rules.fences.exec(src)) {
  11674. src = src.substring(cap[0].length);
  11675. this.tokens.push({
  11676. type: 'code',
  11677. lang: cap[2],
  11678. text: cap[3] || ''
  11679. });
  11680. continue;
  11681. }
  11682. // heading
  11683. if (cap = this.rules.heading.exec(src)) {
  11684. src = src.substring(cap[0].length);
  11685. this.tokens.push({
  11686. type: 'heading',
  11687. depth: cap[1].length,
  11688. text: cap[2]
  11689. });
  11690. continue;
  11691. }
  11692. // table no leading pipe (gfm)
  11693. if (top && (cap = this.rules.nptable.exec(src))) {
  11694. src = src.substring(cap[0].length);
  11695. item = {
  11696. type: 'table',
  11697. header: cap[1].replace(/^ *| *\| *$/g, '').split(/ *\| */),
  11698. align: cap[2].replace(/^ *|\| *$/g, '').split(/ *\| */),
  11699. cells: cap[3].replace(/\n$/, '').split('\n')
  11700. };
  11701. for (i = 0; i < item.align.length; i++) {
  11702. if (/^ *-+: *$/.test(item.align[i])) {
  11703. item.align[i] = 'right';
  11704. } else if (/^ *:-+: *$/.test(item.align[i])) {
  11705. item.align[i] = 'center';
  11706. } else if (/^ *:-+ *$/.test(item.align[i])) {
  11707. item.align[i] = 'left';
  11708. } else {
  11709. item.align[i] = null;
  11710. }
  11711. }
  11712. for (i = 0; i < item.cells.length; i++) {
  11713. item.cells[i] = item.cells[i].split(/ *\| */);
  11714. }
  11715. this.tokens.push(item);
  11716. continue;
  11717. }
  11718. // lheading
  11719. if (cap = this.rules.lheading.exec(src)) {
  11720. src = src.substring(cap[0].length);
  11721. this.tokens.push({
  11722. type: 'heading',
  11723. depth: cap[2] === '=' ? 1 : 2,
  11724. text: cap[1]
  11725. });
  11726. continue;
  11727. }
  11728. // hr
  11729. if (cap = this.rules.hr.exec(src)) {
  11730. src = src.substring(cap[0].length);
  11731. this.tokens.push({
  11732. type: 'hr'
  11733. });
  11734. continue;
  11735. }
  11736. // blockquote
  11737. if (cap = this.rules.blockquote.exec(src)) {
  11738. src = src.substring(cap[0].length);
  11739. this.tokens.push({
  11740. type: 'blockquote_start'
  11741. });
  11742. cap = cap[0].replace(/^ *> ?/gm, '');
  11743. // Pass `top` to keep the current
  11744. // "toplevel" state. This is exactly
  11745. // how markdown.pl works.
  11746. this.token(cap, top, true);
  11747. this.tokens.push({
  11748. type: 'blockquote_end'
  11749. });
  11750. continue;
  11751. }
  11752. // list
  11753. if (cap = this.rules.list.exec(src)) {
  11754. src = src.substring(cap[0].length);
  11755. bull = cap[2];
  11756. this.tokens.push({
  11757. type: 'list_start',
  11758. ordered: bull.length > 1
  11759. });
  11760. // Get each top-level item.
  11761. cap = cap[0].match(this.rules.item);
  11762. next = false;
  11763. l = cap.length;
  11764. i = 0;
  11765. for (; i < l; i++) {
  11766. item = cap[i];
  11767. // Remove the list item's bullet
  11768. // so it is seen as the next token.
  11769. space = item.length;
  11770. item = item.replace(/^ *([*+-]|\d+\.) +/, '');
  11771. // Outdent whatever the
  11772. // list item contains. Hacky.
  11773. if (~item.indexOf('\n ')) {
  11774. space -= item.length;
  11775. item = !this.options.pedantic
  11776. ? item.replace(new RegExp('^ {1,' + space + '}', 'gm'), '')
  11777. : item.replace(/^ {1,4}/gm, '');
  11778. }
  11779. // Determine whether the next list item belongs here.
  11780. // Backpedal if it does not belong in this list.
  11781. if (this.options.smartLists && i !== l - 1) {
  11782. b = block.bullet.exec(cap[i + 1])[0];
  11783. if (bull !== b && !(bull.length > 1 && b.length > 1)) {
  11784. src = cap.slice(i + 1).join('\n') + src;
  11785. i = l - 1;
  11786. }
  11787. }
  11788. // Determine whether item is loose or not.
  11789. // Use: /(^|\n)(?! )[^\n]+\n\n(?!\s*$)/
  11790. // for discount behavior.
  11791. loose = next || /\n\n(?!\s*$)/.test(item);
  11792. if (i !== l - 1) {
  11793. next = item.charAt(item.length - 1) === '\n';
  11794. if (!loose) loose = next;
  11795. }
  11796. this.tokens.push({
  11797. type: loose
  11798. ? 'loose_item_start'
  11799. : 'list_item_start'
  11800. });
  11801. // Recurse.
  11802. this.token(item, false, bq);
  11803. this.tokens.push({
  11804. type: 'list_item_end'
  11805. });
  11806. }
  11807. this.tokens.push({
  11808. type: 'list_end'
  11809. });
  11810. continue;
  11811. }
  11812. // html
  11813. if (cap = this.rules.html.exec(src)) {
  11814. src = src.substring(cap[0].length);
  11815. this.tokens.push({
  11816. type: this.options.sanitize
  11817. ? 'paragraph'
  11818. : 'html',
  11819. pre: !this.options.sanitizer
  11820. && (cap[1] === 'pre' || cap[1] === 'script' || cap[1] === 'style'),
  11821. text: cap[0]
  11822. });
  11823. continue;
  11824. }
  11825. // def
  11826. if ((!bq && top) && (cap = this.rules.def.exec(src))) {
  11827. src = src.substring(cap[0].length);
  11828. this.tokens.links[cap[1].toLowerCase()] = {
  11829. href: cap[2],
  11830. title: cap[3]
  11831. };
  11832. continue;
  11833. }
  11834. // table (gfm)
  11835. if (top && (cap = this.rules.table.exec(src))) {
  11836. src = src.substring(cap[0].length);
  11837. item = {
  11838. type: 'table',
  11839. header: cap[1].replace(/^ *| *\| *$/g, '').split(/ *\| */),
  11840. align: cap[2].replace(/^ *|\| *$/g, '').split(/ *\| */),
  11841. cells: cap[3].replace(/(?: *\| *)?\n$/, '').split('\n')
  11842. };
  11843. for (i = 0; i < item.align.length; i++) {
  11844. if (/^ *-+: *$/.test(item.align[i])) {
  11845. item.align[i] = 'right';
  11846. } else if (/^ *:-+: *$/.test(item.align[i])) {
  11847. item.align[i] = 'center';
  11848. } else if (/^ *:-+ *$/.test(item.align[i])) {
  11849. item.align[i] = 'left';
  11850. } else {
  11851. item.align[i] = null;
  11852. }
  11853. }
  11854. for (i = 0; i < item.cells.length; i++) {
  11855. item.cells[i] = item.cells[i]
  11856. .replace(/^ *\| *| *\| *$/g, '')
  11857. .split(/ *\| */);
  11858. }
  11859. this.tokens.push(item);
  11860. continue;
  11861. }
  11862. // top-level paragraph
  11863. if (top && (cap = this.rules.paragraph.exec(src))) {
  11864. src = src.substring(cap[0].length);
  11865. this.tokens.push({
  11866. type: 'paragraph',
  11867. text: cap[1].charAt(cap[1].length - 1) === '\n'
  11868. ? cap[1].slice(0, -1)
  11869. : cap[1]
  11870. });
  11871. continue;
  11872. }
  11873. // text
  11874. if (cap = this.rules.text.exec(src)) {
  11875. // Top-level should never reach here.
  11876. src = src.substring(cap[0].length);
  11877. this.tokens.push({
  11878. type: 'text',
  11879. text: cap[0]
  11880. });
  11881. continue;
  11882. }
  11883. if (src) {
  11884. throw new
  11885. Error('Infinite loop on byte: ' + src.charCodeAt(0));
  11886. }
  11887. }
  11888. return this.tokens;
  11889. };
  11890. /**
  11891. * Inline-Level Grammar
  11892. */
  11893. var inline = {
  11894. escape: /^\\([\\`*{}\[\]()#+\-.!_>])/,
  11895. autolink: /^<([^ >]+(@|:\/)[^ >]+)>/,
  11896. url: noop,
  11897. tag: /^<!--[\s\S]*?-->|^<\/?\w+(?:"[^"]*"|'[^']*'|[^'">])*?>/,
  11898. link: /^!?\[(inside)\]\(href\)/,
  11899. reflink: /^!?\[(inside)\]\s*\[([^\]]*)\]/,
  11900. nolink: /^!?\[((?:\[[^\]]*\]|[^\[\]])*)\]/,
  11901. strong: /^__([\s\S]+?)__(?!_)|^\*\*([\s\S]+?)\*\*(?!\*)/,
  11902. em: /^\b_((?:[^_]|__)+?)_\b|^\*((?:\*\*|[\s\S])+?)\*(?!\*)/,
  11903. code: /^(`+)\s*([\s\S]*?[^`])\s*\1(?!`)/,
  11904. br: /^ {2,}\n(?!\s*$)/,
  11905. del: noop,
  11906. text: /^[\s\S]+?(?=[\\<!\[_*`]| {2,}\n|$)/
  11907. };
  11908. inline._inside = /(?:\[[^\]]*\]|[^\[\]]|\](?=[^\[]*\]))*/;
  11909. inline._href = /\s*<?([\s\S]*?)>?(?:\s+['"]([\s\S]*?)['"])?\s*/;
  11910. inline.link = replace(inline.link)
  11911. ('inside', inline._inside)
  11912. ('href', inline._href)
  11913. ();
  11914. inline.reflink = replace(inline.reflink)
  11915. ('inside', inline._inside)
  11916. ();
  11917. /**
  11918. * Normal Inline Grammar
  11919. */
  11920. inline.normal = merge({}, inline);
  11921. /**
  11922. * Pedantic Inline Grammar
  11923. */
  11924. inline.pedantic = merge({}, inline.normal, {
  11925. strong: /^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/,
  11926. em: /^_(?=\S)([\s\S]*?\S)_(?!_)|^\*(?=\S)([\s\S]*?\S)\*(?!\*)/
  11927. });
  11928. /**
  11929. * GFM Inline Grammar
  11930. */
  11931. inline.gfm = merge({}, inline.normal, {
  11932. escape: replace(inline.escape)('])', '~|])')(),
  11933. url: /^(https?:\/\/[^\s<]+[^<.,:;"')\]\s])/,
  11934. del: /^~~(?=\S)([\s\S]*?\S)~~/,
  11935. text: replace(inline.text)
  11936. (']|', '~]|')
  11937. ('|', '|https?://|')
  11938. ()
  11939. });
  11940. /**
  11941. * GFM + Line Breaks Inline Grammar
  11942. */
  11943. inline.breaks = merge({}, inline.gfm, {
  11944. br: replace(inline.br)('{2,}', '*')(),
  11945. text: replace(inline.gfm.text)('{2,}', '*')()
  11946. });
  11947. /**
  11948. * Inline Lexer & Compiler
  11949. */
  11950. function InlineLexer(links, options) {
  11951. this.options = options || marked.defaults;
  11952. this.links = links;
  11953. this.rules = inline.normal;
  11954. this.renderer = this.options.renderer || new Renderer;
  11955. this.renderer.options = this.options;
  11956. if (!this.links) {
  11957. throw new
  11958. Error('Tokens array requires a `links` property.');
  11959. }
  11960. if (this.options.gfm) {
  11961. if (this.options.breaks) {
  11962. this.rules = inline.breaks;
  11963. } else {
  11964. this.rules = inline.gfm;
  11965. }
  11966. } else if (this.options.pedantic) {
  11967. this.rules = inline.pedantic;
  11968. }
  11969. }
  11970. /**
  11971. * Expose Inline Rules
  11972. */
  11973. InlineLexer.rules = inline;
  11974. /**
  11975. * Static Lexing/Compiling Method
  11976. */
  11977. InlineLexer.output = function(src, links, options) {
  11978. var inline = new InlineLexer(links, options);
  11979. return inline.output(src);
  11980. };
  11981. /**
  11982. * Lexing/Compiling
  11983. */
  11984. InlineLexer.prototype.output = function(src) {
  11985. var out = ''
  11986. , link
  11987. , text
  11988. , href
  11989. , cap;
  11990. while (src) {
  11991. // escape
  11992. if (cap = this.rules.escape.exec(src)) {
  11993. src = src.substring(cap[0].length);
  11994. out += cap[1];
  11995. continue;
  11996. }
  11997. // autolink
  11998. if (cap = this.rules.autolink.exec(src)) {
  11999. src = src.substring(cap[0].length);
  12000. if (cap[2] === '@') {
  12001. text = cap[1].charAt(6) === ':'
  12002. ? this.mangle(cap[1].substring(7))
  12003. : this.mangle(cap[1]);
  12004. href = this.mangle('mailto:') + text;
  12005. } else {
  12006. text = escape(cap[1]);
  12007. href = text;
  12008. }
  12009. out += this.renderer.link(href, null, text);
  12010. continue;
  12011. }
  12012. // url (gfm)
  12013. if (!this.inLink && (cap = this.rules.url.exec(src))) {
  12014. src = src.substring(cap[0].length);
  12015. text = escape(cap[1]);
  12016. href = text;
  12017. out += this.renderer.link(href, null, text);
  12018. continue;
  12019. }
  12020. // tag
  12021. if (cap = this.rules.tag.exec(src)) {
  12022. if (!this.inLink && /^<a /i.test(cap[0])) {
  12023. this.inLink = true;
  12024. } else if (this.inLink && /^<\/a>/i.test(cap[0])) {
  12025. this.inLink = false;
  12026. }
  12027. src = src.substring(cap[0].length);
  12028. out += this.options.sanitize
  12029. ? this.options.sanitizer
  12030. ? this.options.sanitizer(cap[0])
  12031. : escape(cap[0])
  12032. : cap[0]
  12033. continue;
  12034. }
  12035. // link
  12036. if (cap = this.rules.link.exec(src)) {
  12037. src = src.substring(cap[0].length);
  12038. this.inLink = true;
  12039. out += this.outputLink(cap, {
  12040. href: cap[2],
  12041. title: cap[3]
  12042. });
  12043. this.inLink = false;
  12044. continue;
  12045. }
  12046. // reflink, nolink
  12047. if ((cap = this.rules.reflink.exec(src))
  12048. || (cap = this.rules.nolink.exec(src))) {
  12049. src = src.substring(cap[0].length);
  12050. link = (cap[2] || cap[1]).replace(/\s+/g, ' ');
  12051. link = this.links[link.toLowerCase()];
  12052. if (!link || !link.href) {
  12053. out += cap[0].charAt(0);
  12054. src = cap[0].substring(1) + src;
  12055. continue;
  12056. }
  12057. this.inLink = true;
  12058. out += this.outputLink(cap, link);
  12059. this.inLink = false;
  12060. continue;
  12061. }
  12062. // strong
  12063. if (cap = this.rules.strong.exec(src)) {
  12064. src = src.substring(cap[0].length);
  12065. out += this.renderer.strong(this.output(cap[2] || cap[1]));
  12066. continue;
  12067. }
  12068. // em
  12069. if (cap = this.rules.em.exec(src)) {
  12070. src = src.substring(cap[0].length);
  12071. out += this.renderer.em(this.output(cap[2] || cap[1]));
  12072. continue;
  12073. }
  12074. // code
  12075. if (cap = this.rules.code.exec(src)) {
  12076. src = src.substring(cap[0].length);
  12077. out += this.renderer.codespan(escape(cap[2], true));
  12078. continue;
  12079. }
  12080. // br
  12081. if (cap = this.rules.br.exec(src)) {
  12082. src = src.substring(cap[0].length);
  12083. out += this.renderer.br();
  12084. continue;
  12085. }
  12086. // del (gfm)
  12087. if (cap = this.rules.del.exec(src)) {
  12088. src = src.substring(cap[0].length);
  12089. out += this.renderer.del(this.output(cap[1]));
  12090. continue;
  12091. }
  12092. // text
  12093. if (cap = this.rules.text.exec(src)) {
  12094. src = src.substring(cap[0].length);
  12095. out += this.renderer.text(escape(this.smartypants(cap[0])));
  12096. continue;
  12097. }
  12098. if (src) {
  12099. throw new
  12100. Error('Infinite loop on byte: ' + src.charCodeAt(0));
  12101. }
  12102. }
  12103. return out;
  12104. };
  12105. /**
  12106. * Compile Link
  12107. */
  12108. InlineLexer.prototype.outputLink = function(cap, link) {
  12109. var href = escape(link.href)
  12110. , title = link.title ? escape(link.title) : null;
  12111. return cap[0].charAt(0) !== '!'
  12112. ? this.renderer.link(href, title, this.output(cap[1]))
  12113. : this.renderer.image(href, title, escape(cap[1]));
  12114. };
  12115. /**
  12116. * Smartypants Transformations
  12117. */
  12118. InlineLexer.prototype.smartypants = function(text) {
  12119. if (!this.options.smartypants) return text;
  12120. return text
  12121. // em-dashes
  12122. .replace(/---/g, '\u2014')
  12123. // en-dashes
  12124. .replace(/--/g, '\u2013')
  12125. // opening singles
  12126. .replace(/(^|[-\u2014/(\[{"\s])'/g, '$1\u2018')
  12127. // closing singles & apostrophes
  12128. .replace(/'/g, '\u2019')
  12129. // opening doubles
  12130. .replace(/(^|[-\u2014/(\[{\u2018\s])"/g, '$1\u201c')
  12131. // closing doubles
  12132. .replace(/"/g, '\u201d')
  12133. // ellipses
  12134. .replace(/\.{3}/g, '\u2026');
  12135. };
  12136. /**
  12137. * Mangle Links
  12138. */
  12139. InlineLexer.prototype.mangle = function(text) {
  12140. if (!this.options.mangle) return text;
  12141. var out = ''
  12142. , l = text.length
  12143. , i = 0
  12144. , ch;
  12145. for (; i < l; i++) {
  12146. ch = text.charCodeAt(i);
  12147. if (Math.random() > 0.5) {
  12148. ch = 'x' + ch.toString(16);
  12149. }
  12150. out += '&#' + ch + ';';
  12151. }
  12152. return out;
  12153. };
  12154. /**
  12155. * Renderer
  12156. */
  12157. function Renderer(options) {
  12158. this.options = options || {};
  12159. }
  12160. Renderer.prototype.code = function(code, lang, escaped) {
  12161. if (this.options.highlight) {
  12162. var out = this.options.highlight(code, lang);
  12163. if (out != null && out !== code) {
  12164. escaped = true;
  12165. code = out;
  12166. }
  12167. }
  12168. if (!lang) {
  12169. return '<pre><code>'
  12170. + (escaped ? code : escape(code, true))
  12171. + '\n</code></pre>';
  12172. }
  12173. return '<pre><code class="'
  12174. + this.options.langPrefix
  12175. + escape(lang, true)
  12176. + '">'
  12177. + (escaped ? code : escape(code, true))
  12178. + '\n</code></pre>\n';
  12179. };
  12180. Renderer.prototype.blockquote = function(quote) {
  12181. return '<blockquote>\n' + quote + '</blockquote>\n';
  12182. };
  12183. Renderer.prototype.html = function(html) {
  12184. return html;
  12185. };
  12186. Renderer.prototype.heading = function(text, level, raw) {
  12187. return '<h'
  12188. + level
  12189. + ' id="'
  12190. + this.options.headerPrefix
  12191. + raw.toLowerCase().replace(/[^\w]+/g, '-')
  12192. + '">'
  12193. + text
  12194. + '</h'
  12195. + level
  12196. + '>\n';
  12197. };
  12198. Renderer.prototype.hr = function() {
  12199. return this.options.xhtml ? '<hr/>\n' : '<hr>\n';
  12200. };
  12201. Renderer.prototype.list = function(body, ordered) {
  12202. var type = ordered ? 'ol' : 'ul';
  12203. return '<' + type + '>\n' + body + '</' + type + '>\n';
  12204. };
  12205. Renderer.prototype.listitem = function(text) {
  12206. return '<li>' + text + '</li>\n';
  12207. };
  12208. Renderer.prototype.paragraph = function(text) {
  12209. return '<p>' + text + '</p>\n';
  12210. };
  12211. Renderer.prototype.table = function(header, body) {
  12212. return '<table>\n'
  12213. + '<thead>\n'
  12214. + header
  12215. + '</thead>\n'
  12216. + '<tbody>\n'
  12217. + body
  12218. + '</tbody>\n'
  12219. + '</table>\n';
  12220. };
  12221. Renderer.prototype.tablerow = function(content) {
  12222. return '<tr>\n' + content + '</tr>\n';
  12223. };
  12224. Renderer.prototype.tablecell = function(content, flags) {
  12225. var type = flags.header ? 'th' : 'td';
  12226. var tag = flags.align
  12227. ? '<' + type + ' style="text-align:' + flags.align + '">'
  12228. : '<' + type + '>';
  12229. return tag + content + '</' + type + '>\n';
  12230. };
  12231. // span level renderer
  12232. Renderer.prototype.strong = function(text) {
  12233. return '<strong>' + text + '</strong>';
  12234. };
  12235. Renderer.prototype.em = function(text) {
  12236. return '<em>' + text + '</em>';
  12237. };
  12238. Renderer.prototype.codespan = function(text) {
  12239. return '<code>' + text + '</code>';
  12240. };
  12241. Renderer.prototype.br = function() {
  12242. return this.options.xhtml ? '<br/>' : '<br>';
  12243. };
  12244. Renderer.prototype.del = function(text) {
  12245. return '<del>' + text + '</del>';
  12246. };
  12247. Renderer.prototype.link = function(href, title, text) {
  12248. if (this.options.sanitize) {
  12249. try {
  12250. var prot = decodeURIComponent(unescape(href))
  12251. .replace(/[^\w:]/g, '')
  12252. .toLowerCase();
  12253. } catch (e) {
  12254. return '';
  12255. }
  12256. if (prot.indexOf('javascript:') === 0 || prot.indexOf('vbscript:') === 0) {
  12257. return '';
  12258. }
  12259. }
  12260. var out = '<a href="' + href + '"';
  12261. if (title) {
  12262. out += ' title="' + title + '"';
  12263. }
  12264. out += '>' + text + '</a>';
  12265. return out;
  12266. };
  12267. Renderer.prototype.image = function(href, title, text) {
  12268. var out = '<img src="' + href + '" alt="' + text + '"';
  12269. if (title) {
  12270. out += ' title="' + title + '"';
  12271. }
  12272. out += this.options.xhtml ? '/>' : '>';
  12273. return out;
  12274. };
  12275. Renderer.prototype.text = function(text) {
  12276. return text;
  12277. };
  12278. /**
  12279. * Parsing & Compiling
  12280. */
  12281. function Parser(options) {
  12282. this.tokens = [];
  12283. this.token = null;
  12284. this.options = options || marked.defaults;
  12285. this.options.renderer = this.options.renderer || new Renderer;
  12286. this.renderer = this.options.renderer;
  12287. this.renderer.options = this.options;
  12288. }
  12289. /**
  12290. * Static Parse Method
  12291. */
  12292. Parser.parse = function(src, options, renderer) {
  12293. var parser = new Parser(options, renderer);
  12294. return parser.parse(src);
  12295. };
  12296. /**
  12297. * Parse Loop
  12298. */
  12299. Parser.prototype.parse = function(src) {
  12300. this.inline = new InlineLexer(src.links, this.options, this.renderer);
  12301. this.tokens = src.reverse();
  12302. var out = '';
  12303. while (this.next()) {
  12304. out += this.tok();
  12305. }
  12306. return out;
  12307. };
  12308. /**
  12309. * Next Token
  12310. */
  12311. Parser.prototype.next = function() {
  12312. return this.token = this.tokens.pop();
  12313. };
  12314. /**
  12315. * Preview Next Token
  12316. */
  12317. Parser.prototype.peek = function() {
  12318. return this.tokens[this.tokens.length - 1] || 0;
  12319. };
  12320. /**
  12321. * Parse Text Tokens
  12322. */
  12323. Parser.prototype.parseText = function() {
  12324. var body = this.token.text;
  12325. while (this.peek().type === 'text') {
  12326. body += '\n' + this.next().text;
  12327. }
  12328. return this.inline.output(body);
  12329. };
  12330. /**
  12331. * Parse Current Token
  12332. */
  12333. Parser.prototype.tok = function() {
  12334. switch (this.token.type) {
  12335. case 'space': {
  12336. return '';
  12337. }
  12338. case 'hr': {
  12339. return this.renderer.hr();
  12340. }
  12341. case 'heading': {
  12342. return this.renderer.heading(
  12343. this.inline.output(this.token.text),
  12344. this.token.depth,
  12345. this.token.text);
  12346. }
  12347. case 'code': {
  12348. return this.renderer.code(this.token.text,
  12349. this.token.lang,
  12350. this.token.escaped);
  12351. }
  12352. case 'table': {
  12353. var header = ''
  12354. , body = ''
  12355. , i
  12356. , row
  12357. , cell
  12358. , flags
  12359. , j;
  12360. // header
  12361. cell = '';
  12362. for (i = 0; i < this.token.header.length; i++) {
  12363. flags = { header: true, align: this.token.align[i] };
  12364. cell += this.renderer.tablecell(
  12365. this.inline.output(this.token.header[i]),
  12366. { header: true, align: this.token.align[i] }
  12367. );
  12368. }
  12369. header += this.renderer.tablerow(cell);
  12370. for (i = 0; i < this.token.cells.length; i++) {
  12371. row = this.token.cells[i];
  12372. cell = '';
  12373. for (j = 0; j < row.length; j++) {
  12374. cell += this.renderer.tablecell(
  12375. this.inline.output(row[j]),
  12376. { header: false, align: this.token.align[j] }
  12377. );
  12378. }
  12379. body += this.renderer.tablerow(cell);
  12380. }
  12381. return this.renderer.table(header, body);
  12382. }
  12383. case 'blockquote_start': {
  12384. var body = '';
  12385. while (this.next().type !== 'blockquote_end') {
  12386. body += this.tok();
  12387. }
  12388. return this.renderer.blockquote(body);
  12389. }
  12390. case 'list_start': {
  12391. var body = ''
  12392. , ordered = this.token.ordered;
  12393. while (this.next().type !== 'list_end') {
  12394. body += this.tok();
  12395. }
  12396. return this.renderer.list(body, ordered);
  12397. }
  12398. case 'list_item_start': {
  12399. var body = '';
  12400. while (this.next().type !== 'list_item_end') {
  12401. body += this.token.type === 'text'
  12402. ? this.parseText()
  12403. : this.tok();
  12404. }
  12405. return this.renderer.listitem(body);
  12406. }
  12407. case 'loose_item_start': {
  12408. var body = '';
  12409. while (this.next().type !== 'list_item_end') {
  12410. body += this.tok();
  12411. }
  12412. return this.renderer.listitem(body);
  12413. }
  12414. case 'html': {
  12415. var html = !this.token.pre && !this.options.pedantic
  12416. ? this.inline.output(this.token.text)
  12417. : this.token.text;
  12418. return this.renderer.html(html);
  12419. }
  12420. case 'paragraph': {
  12421. return this.renderer.paragraph(this.inline.output(this.token.text));
  12422. }
  12423. case 'text': {
  12424. return this.renderer.paragraph(this.parseText());
  12425. }
  12426. }
  12427. };
  12428. /**
  12429. * Helpers
  12430. */
  12431. function escape(html, encode) {
  12432. return html
  12433. .replace(!encode ? /&(?!#?\w+;)/g : /&/g, '&amp;')
  12434. .replace(/</g, '&lt;')
  12435. .replace(/>/g, '&gt;')
  12436. .replace(/"/g, '&quot;')
  12437. .replace(/'/g, '&#39;');
  12438. }
  12439. function unescape(html) {
  12440. return html.replace(/&([#\w]+);/g, function(_, n) {
  12441. n = n.toLowerCase();
  12442. if (n === 'colon') return ':';
  12443. if (n.charAt(0) === '#') {
  12444. return n.charAt(1) === 'x'
  12445. ? String.fromCharCode(parseInt(n.substring(2), 16))
  12446. : String.fromCharCode(+n.substring(1));
  12447. }
  12448. return '';
  12449. });
  12450. }
  12451. function replace(regex, opt) {
  12452. regex = regex.source;
  12453. opt = opt || '';
  12454. return function self(name, val) {
  12455. if (!name) return new RegExp(regex, opt);
  12456. val = val.source || val;
  12457. val = val.replace(/(^|[^\[])\^/g, '$1');
  12458. regex = regex.replace(name, val);
  12459. return self;
  12460. };
  12461. }
  12462. function noop() {}
  12463. noop.exec = noop;
  12464. function merge(obj) {
  12465. var i = 1
  12466. , target
  12467. , key;
  12468. for (; i < arguments.length; i++) {
  12469. target = arguments[i];
  12470. for (key in target) {
  12471. if (Object.prototype.hasOwnProperty.call(target, key)) {
  12472. obj[key] = target[key];
  12473. }
  12474. }
  12475. }
  12476. return obj;
  12477. }
  12478. /**
  12479. * Marked
  12480. */
  12481. function marked(src, opt, callback) {
  12482. if (callback || typeof opt === 'function') {
  12483. if (!callback) {
  12484. callback = opt;
  12485. opt = null;
  12486. }
  12487. opt = merge({}, marked.defaults, opt || {});
  12488. var highlight = opt.highlight
  12489. , tokens
  12490. , pending
  12491. , i = 0;
  12492. try {
  12493. tokens = Lexer.lex(src, opt)
  12494. } catch (e) {
  12495. return callback(e);
  12496. }
  12497. pending = tokens.length;
  12498. var done = function(err) {
  12499. if (err) {
  12500. opt.highlight = highlight;
  12501. return callback(err);
  12502. }
  12503. var out;
  12504. try {
  12505. out = Parser.parse(tokens, opt);
  12506. } catch (e) {
  12507. err = e;
  12508. }
  12509. opt.highlight = highlight;
  12510. return err
  12511. ? callback(err)
  12512. : callback(null, out);
  12513. };
  12514. if (!highlight || highlight.length < 3) {
  12515. return done();
  12516. }
  12517. delete opt.highlight;
  12518. if (!pending) return done();
  12519. for (; i < tokens.length; i++) {
  12520. (function(token) {
  12521. if (token.type !== 'code') {
  12522. return --pending || done();
  12523. }
  12524. return highlight(token.text, token.lang, function(err, code) {
  12525. if (err) return done(err);
  12526. if (code == null || code === token.text) {
  12527. return --pending || done();
  12528. }
  12529. token.text = code;
  12530. token.escaped = true;
  12531. --pending || done();
  12532. });
  12533. })(tokens[i]);
  12534. }
  12535. return;
  12536. }
  12537. try {
  12538. if (opt) opt = merge({}, marked.defaults, opt);
  12539. return Parser.parse(Lexer.lex(src, opt), opt);
  12540. } catch (e) {
  12541. e.message += '\nPlease report this to https://github.com/chjj/marked.';
  12542. if ((opt || marked.defaults).silent) {
  12543. return '<p>An error occured:</p><pre>'
  12544. + escape(e.message + '', true)
  12545. + '</pre>';
  12546. }
  12547. throw e;
  12548. }
  12549. }
  12550. /**
  12551. * Options
  12552. */
  12553. marked.options =
  12554. marked.setOptions = function(opt) {
  12555. merge(marked.defaults, opt);
  12556. return marked;
  12557. };
  12558. marked.defaults = {
  12559. gfm: true,
  12560. tables: true,
  12561. breaks: false,
  12562. pedantic: false,
  12563. sanitize: false,
  12564. sanitizer: null,
  12565. mangle: true,
  12566. smartLists: false,
  12567. silent: false,
  12568. highlight: null,
  12569. langPrefix: 'lang-',
  12570. smartypants: false,
  12571. headerPrefix: '',
  12572. renderer: new Renderer,
  12573. xhtml: false
  12574. };
  12575. /**
  12576. * Expose
  12577. */
  12578. marked.Parser = Parser;
  12579. marked.parser = Parser.parse;
  12580. marked.Renderer = Renderer;
  12581. marked.Lexer = Lexer;
  12582. marked.lexer = Lexer.lex;
  12583. marked.InlineLexer = InlineLexer;
  12584. marked.inlineLexer = InlineLexer.output;
  12585. marked.parse = marked;
  12586. if (typeof module !== 'undefined' && typeof exports === 'object') {
  12587. module.exports = marked;
  12588. } else if (typeof define === 'function' && define.amd) {
  12589. define(function() { return marked; });
  12590. } else {
  12591. this.marked = marked;
  12592. }
  12593. }).call(function() {
  12594. return this || (typeof window !== 'undefined' ? window : global);
  12595. }());
  12596. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  12597. },{}],18:[function(require,module,exports){
  12598. (function (Buffer,__dirname){
  12599. 'use strict';
  12600. /**
  12601. * Typo is a JavaScript implementation of a spellchecker using hunspell-style
  12602. * dictionaries.
  12603. */
  12604. /**
  12605. * Typo constructor.
  12606. *
  12607. * @param {String} [dictionary] The locale code of the dictionary being used. e.g.,
  12608. * "en_US". This is only used to auto-load dictionaries.
  12609. * @param {String} [affData] The data from the dictionary's .aff file. If omitted
  12610. * and Typo.js is being used in a Chrome extension, the .aff
  12611. * file will be loaded automatically from
  12612. * lib/typo/dictionaries/[dictionary]/[dictionary].aff
  12613. * In other environments, it will be loaded from
  12614. * [settings.dictionaryPath]/dictionaries/[dictionary]/[dictionary].aff
  12615. * @param {String} [wordsData] The data from the dictionary's .dic file. If omitted
  12616. * and Typo.js is being used in a Chrome extension, the .dic
  12617. * file will be loaded automatically from
  12618. * lib/typo/dictionaries/[dictionary]/[dictionary].dic
  12619. * In other environments, it will be loaded from
  12620. * [settings.dictionaryPath]/dictionaries/[dictionary]/[dictionary].dic
  12621. * @param {Object} [settings] Constructor settings. Available properties are:
  12622. * {String} [dictionaryPath]: path to load dictionary from in non-chrome
  12623. * environment.
  12624. * {Object} [flags]: flag information.
  12625. *
  12626. *
  12627. * @returns {Typo} A Typo object.
  12628. */
  12629. var Typo = function (dictionary, affData, wordsData, settings) {
  12630. settings = settings || {};
  12631. this.dictionary = null;
  12632. this.rules = {};
  12633. this.dictionaryTable = {};
  12634. this.compoundRules = [];
  12635. this.compoundRuleCodes = {};
  12636. this.replacementTable = [];
  12637. this.flags = settings.flags || {};
  12638. if (dictionary) {
  12639. this.dictionary = dictionary;
  12640. if (typeof window !== 'undefined' && 'chrome' in window && 'extension' in window.chrome && 'getURL' in window.chrome.extension) {
  12641. if (!affData) affData = this._readFile(chrome.extension.getURL("lib/typo/dictionaries/" + dictionary + "/" + dictionary + ".aff"));
  12642. if (!wordsData) wordsData = this._readFile(chrome.extension.getURL("lib/typo/dictionaries/" + dictionary + "/" + dictionary + ".dic"));
  12643. } else {
  12644. if (settings.dictionaryPath) {
  12645. var path = settings.dictionaryPath;
  12646. }
  12647. else if (typeof __dirname !== 'undefined') {
  12648. var path = __dirname + '/dictionaries';
  12649. }
  12650. else {
  12651. var path = './dictionaries';
  12652. }
  12653. if (!affData) affData = this._readFile(path + "/" + dictionary + "/" + dictionary + ".aff");
  12654. if (!wordsData) wordsData = this._readFile(path + "/" + dictionary + "/" + dictionary + ".dic");
  12655. }
  12656. this.rules = this._parseAFF(affData);
  12657. // Save the rule codes that are used in compound rules.
  12658. this.compoundRuleCodes = {};
  12659. for (var i = 0, _len = this.compoundRules.length; i < _len; i++) {
  12660. var rule = this.compoundRules[i];
  12661. for (var j = 0, _jlen = rule.length; j < _jlen; j++) {
  12662. this.compoundRuleCodes[rule[j]] = [];
  12663. }
  12664. }
  12665. // If we add this ONLYINCOMPOUND flag to this.compoundRuleCodes, then _parseDIC
  12666. // will do the work of saving the list of words that are compound-only.
  12667. if ("ONLYINCOMPOUND" in this.flags) {
  12668. this.compoundRuleCodes[this.flags.ONLYINCOMPOUND] = [];
  12669. }
  12670. this.dictionaryTable = this._parseDIC(wordsData);
  12671. // Get rid of any codes from the compound rule codes that are never used
  12672. // (or that were special regex characters). Not especially necessary...
  12673. for (var i in this.compoundRuleCodes) {
  12674. if (this.compoundRuleCodes[i].length == 0) {
  12675. delete this.compoundRuleCodes[i];
  12676. }
  12677. }
  12678. // Build the full regular expressions for each compound rule.
  12679. // I have a feeling (but no confirmation yet) that this method of
  12680. // testing for compound words is probably slow.
  12681. for (var i = 0, _len = this.compoundRules.length; i < _len; i++) {
  12682. var ruleText = this.compoundRules[i];
  12683. var expressionText = "";
  12684. for (var j = 0, _jlen = ruleText.length; j < _jlen; j++) {
  12685. var character = ruleText[j];
  12686. if (character in this.compoundRuleCodes) {
  12687. expressionText += "(" + this.compoundRuleCodes[character].join("|") + ")";
  12688. }
  12689. else {
  12690. expressionText += character;
  12691. }
  12692. }
  12693. this.compoundRules[i] = new RegExp(expressionText, "i");
  12694. }
  12695. }
  12696. return this;
  12697. };
  12698. Typo.prototype = {
  12699. /**
  12700. * Loads a Typo instance from a hash of all of the Typo properties.
  12701. *
  12702. * @param object obj A hash of Typo properties, probably gotten from a JSON.parse(JSON.stringify(typo_instance)).
  12703. */
  12704. load : function (obj) {
  12705. for (var i in obj) {
  12706. this[i] = obj[i];
  12707. }
  12708. return this;
  12709. },
  12710. /**
  12711. * Read the contents of a file.
  12712. *
  12713. * @param {String} path The path (relative) to the file.
  12714. * @param {String} [charset="ISO8859-1"] The expected charset of the file
  12715. * @returns string The file data.
  12716. */
  12717. _readFile : function (path, charset) {
  12718. if (!charset) charset = "utf8";
  12719. if (typeof XMLHttpRequest !== 'undefined') {
  12720. var req = new XMLHttpRequest();
  12721. req.open("GET", path, false);
  12722. if (req.overrideMimeType)
  12723. req.overrideMimeType("text/plain; charset=" + charset);
  12724. req.send(null);
  12725. return req.responseText;
  12726. }
  12727. else if (typeof require !== 'undefined') {
  12728. // Node.js
  12729. var fs = require("fs");
  12730. try {
  12731. if (fs.existsSync(path)) {
  12732. var stats = fs.statSync(path);
  12733. var fileDescriptor = fs.openSync(path, 'r');
  12734. var buffer = new Buffer(stats.size);
  12735. fs.readSync(fileDescriptor, buffer, 0, buffer.length, null);
  12736. return buffer.toString(charset, 0, buffer.length);
  12737. }
  12738. else {
  12739. console.log("Path " + path + " does not exist.");
  12740. }
  12741. } catch (e) {
  12742. console.log(e);
  12743. return '';
  12744. }
  12745. }
  12746. },
  12747. /**
  12748. * Parse the rules out from a .aff file.
  12749. *
  12750. * @param {String} data The contents of the affix file.
  12751. * @returns object The rules from the file.
  12752. */
  12753. _parseAFF : function (data) {
  12754. var rules = {};
  12755. // Remove comment lines
  12756. data = this._removeAffixComments(data);
  12757. var lines = data.split("\n");
  12758. for (var i = 0, _len = lines.length; i < _len; i++) {
  12759. var line = lines[i];
  12760. var definitionParts = line.split(/\s+/);
  12761. var ruleType = definitionParts[0];
  12762. if (ruleType == "PFX" || ruleType == "SFX") {
  12763. var ruleCode = definitionParts[1];
  12764. var combineable = definitionParts[2];
  12765. var numEntries = parseInt(definitionParts[3], 10);
  12766. var entries = [];
  12767. for (var j = i + 1, _jlen = i + 1 + numEntries; j < _jlen; j++) {
  12768. var line = lines[j];
  12769. var lineParts = line.split(/\s+/);
  12770. var charactersToRemove = lineParts[2];
  12771. var additionParts = lineParts[3].split("/");
  12772. var charactersToAdd = additionParts[0];
  12773. if (charactersToAdd === "0") charactersToAdd = "";
  12774. var continuationClasses = this.parseRuleCodes(additionParts[1]);
  12775. var regexToMatch = lineParts[4];
  12776. var entry = {};
  12777. entry.add = charactersToAdd;
  12778. if (continuationClasses.length > 0) entry.continuationClasses = continuationClasses;
  12779. if (regexToMatch !== ".") {
  12780. if (ruleType === "SFX") {
  12781. entry.match = new RegExp(regexToMatch + "$");
  12782. }
  12783. else {
  12784. entry.match = new RegExp("^" + regexToMatch);
  12785. }
  12786. }
  12787. if (charactersToRemove != "0") {
  12788. if (ruleType === "SFX") {
  12789. entry.remove = new RegExp(charactersToRemove + "$");
  12790. }
  12791. else {
  12792. entry.remove = charactersToRemove;
  12793. }
  12794. }
  12795. entries.push(entry);
  12796. }
  12797. rules[ruleCode] = { "type" : ruleType, "combineable" : (combineable == "Y"), "entries" : entries };
  12798. i += numEntries;
  12799. }
  12800. else if (ruleType === "COMPOUNDRULE") {
  12801. var numEntries = parseInt(definitionParts[1], 10);
  12802. for (var j = i + 1, _jlen = i + 1 + numEntries; j < _jlen; j++) {
  12803. var line = lines[j];
  12804. var lineParts = line.split(/\s+/);
  12805. this.compoundRules.push(lineParts[1]);
  12806. }
  12807. i += numEntries;
  12808. }
  12809. else if (ruleType === "REP") {
  12810. var lineParts = line.split(/\s+/);
  12811. if (lineParts.length === 3) {
  12812. this.replacementTable.push([ lineParts[1], lineParts[2] ]);
  12813. }
  12814. }
  12815. else {
  12816. // ONLYINCOMPOUND
  12817. // COMPOUNDMIN
  12818. // FLAG
  12819. // KEEPCASE
  12820. // NEEDAFFIX
  12821. this.flags[ruleType] = definitionParts[1];
  12822. }
  12823. }
  12824. return rules;
  12825. },
  12826. /**
  12827. * Removes comment lines and then cleans up blank lines and trailing whitespace.
  12828. *
  12829. * @param {String} data The data from an affix file.
  12830. * @return {String} The cleaned-up data.
  12831. */
  12832. _removeAffixComments : function (data) {
  12833. // Remove comments
  12834. data = data.replace(/#.*$/mg, "");
  12835. // Trim each line
  12836. data = data.replace(/^\s\s*/m, '').replace(/\s\s*$/m, '');
  12837. // Remove blank lines.
  12838. data = data.replace(/\n{2,}/g, "\n");
  12839. // Trim the entire string
  12840. data = data.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
  12841. return data;
  12842. },
  12843. /**
  12844. * Parses the words out from the .dic file.
  12845. *
  12846. * @param {String} data The data from the dictionary file.
  12847. * @returns object The lookup table containing all of the words and
  12848. * word forms from the dictionary.
  12849. */
  12850. _parseDIC : function (data) {
  12851. data = this._removeDicComments(data);
  12852. var lines = data.split("\n");
  12853. var dictionaryTable = {};
  12854. function addWord(word, rules) {
  12855. // Some dictionaries will list the same word multiple times with different rule sets.
  12856. if (!(word in dictionaryTable) || typeof dictionaryTable[word] != 'object') {
  12857. dictionaryTable[word] = [];
  12858. }
  12859. dictionaryTable[word].push(rules);
  12860. }
  12861. // The first line is the number of words in the dictionary.
  12862. for (var i = 1, _len = lines.length; i < _len; i++) {
  12863. var line = lines[i];
  12864. var parts = line.split("/", 2);
  12865. var word = parts[0];
  12866. // Now for each affix rule, generate that form of the word.
  12867. if (parts.length > 1) {
  12868. var ruleCodesArray = this.parseRuleCodes(parts[1]);
  12869. // Save the ruleCodes for compound word situations.
  12870. if (!("NEEDAFFIX" in this.flags) || ruleCodesArray.indexOf(this.flags.NEEDAFFIX) == -1) {
  12871. addWord(word, ruleCodesArray);
  12872. }
  12873. for (var j = 0, _jlen = ruleCodesArray.length; j < _jlen; j++) {
  12874. var code = ruleCodesArray[j];
  12875. var rule = this.rules[code];
  12876. if (rule) {
  12877. var newWords = this._applyRule(word, rule);
  12878. for (var ii = 0, _iilen = newWords.length; ii < _iilen; ii++) {
  12879. var newWord = newWords[ii];
  12880. addWord(newWord, []);
  12881. if (rule.combineable) {
  12882. for (var k = j + 1; k < _jlen; k++) {
  12883. var combineCode = ruleCodesArray[k];
  12884. var combineRule = this.rules[combineCode];
  12885. if (combineRule) {
  12886. if (combineRule.combineable && (rule.type != combineRule.type)) {
  12887. var otherNewWords = this._applyRule(newWord, combineRule);
  12888. for (var iii = 0, _iiilen = otherNewWords.length; iii < _iiilen; iii++) {
  12889. var otherNewWord = otherNewWords[iii];
  12890. addWord(otherNewWord, []);
  12891. }
  12892. }
  12893. }
  12894. }
  12895. }
  12896. }
  12897. }
  12898. if (code in this.compoundRuleCodes) {
  12899. this.compoundRuleCodes[code].push(word);
  12900. }
  12901. }
  12902. }
  12903. else {
  12904. addWord(word.trim(), []);
  12905. }
  12906. }
  12907. return dictionaryTable;
  12908. },
  12909. /**
  12910. * Removes comment lines and then cleans up blank lines and trailing whitespace.
  12911. *
  12912. * @param {String} data The data from a .dic file.
  12913. * @return {String} The cleaned-up data.
  12914. */
  12915. _removeDicComments : function (data) {
  12916. // I can't find any official documentation on it, but at least the de_DE
  12917. // dictionary uses tab-indented lines as comments.
  12918. // Remove comments
  12919. data = data.replace(/^\t.*$/mg, "");
  12920. return data;
  12921. },
  12922. parseRuleCodes : function (textCodes) {
  12923. if (!textCodes) {
  12924. return [];
  12925. }
  12926. else if (!("FLAG" in this.flags)) {
  12927. return textCodes.split("");
  12928. }
  12929. else if (this.flags.FLAG === "long") {
  12930. var flags = [];
  12931. for (var i = 0, _len = textCodes.length; i < _len; i += 2) {
  12932. flags.push(textCodes.substr(i, 2));
  12933. }
  12934. return flags;
  12935. }
  12936. else if (this.flags.FLAG === "num") {
  12937. return textCode.split(",");
  12938. }
  12939. },
  12940. /**
  12941. * Applies an affix rule to a word.
  12942. *
  12943. * @param {String} word The base word.
  12944. * @param {Object} rule The affix rule.
  12945. * @returns {String[]} The new words generated by the rule.
  12946. */
  12947. _applyRule : function (word, rule) {
  12948. var entries = rule.entries;
  12949. var newWords = [];
  12950. for (var i = 0, _len = entries.length; i < _len; i++) {
  12951. var entry = entries[i];
  12952. if (!entry.match || word.match(entry.match)) {
  12953. var newWord = word;
  12954. if (entry.remove) {
  12955. newWord = newWord.replace(entry.remove, "");
  12956. }
  12957. if (rule.type === "SFX") {
  12958. newWord = newWord + entry.add;
  12959. }
  12960. else {
  12961. newWord = entry.add + newWord;
  12962. }
  12963. newWords.push(newWord);
  12964. if ("continuationClasses" in entry) {
  12965. for (var j = 0, _jlen = entry.continuationClasses.length; j < _jlen; j++) {
  12966. var continuationRule = this.rules[entry.continuationClasses[j]];
  12967. if (continuationRule) {
  12968. newWords = newWords.concat(this._applyRule(newWord, continuationRule));
  12969. }
  12970. /*
  12971. else {
  12972. // This shouldn't happen, but it does, at least in the de_DE dictionary.
  12973. // I think the author mistakenly supplied lower-case rule codes instead
  12974. // of upper-case.
  12975. }
  12976. */
  12977. }
  12978. }
  12979. }
  12980. }
  12981. return newWords;
  12982. },
  12983. /**
  12984. * Checks whether a word or a capitalization variant exists in the current dictionary.
  12985. * The word is trimmed and several variations of capitalizations are checked.
  12986. * If you want to check a word without any changes made to it, call checkExact()
  12987. *
  12988. * @see http://blog.stevenlevithan.com/archives/faster-trim-javascript re:trimming function
  12989. *
  12990. * @param {String} aWord The word to check.
  12991. * @returns {Boolean}
  12992. */
  12993. check : function (aWord) {
  12994. // Remove leading and trailing whitespace
  12995. var trimmedWord = aWord.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
  12996. if (this.checkExact(trimmedWord)) {
  12997. return true;
  12998. }
  12999. // The exact word is not in the dictionary.
  13000. if (trimmedWord.toUpperCase() === trimmedWord) {
  13001. // The word was supplied in all uppercase.
  13002. // Check for a capitalized form of the word.
  13003. var capitalizedWord = trimmedWord[0] + trimmedWord.substring(1).toLowerCase();
  13004. if (this.hasFlag(capitalizedWord, "KEEPCASE")) {
  13005. // Capitalization variants are not allowed for this word.
  13006. return false;
  13007. }
  13008. if (this.checkExact(capitalizedWord)) {
  13009. return true;
  13010. }
  13011. }
  13012. var lowercaseWord = trimmedWord.toLowerCase();
  13013. if (lowercaseWord !== trimmedWord) {
  13014. if (this.hasFlag(lowercaseWord, "KEEPCASE")) {
  13015. // Capitalization variants are not allowed for this word.
  13016. return false;
  13017. }
  13018. // Check for a lowercase form
  13019. if (this.checkExact(lowercaseWord)) {
  13020. return true;
  13021. }
  13022. }
  13023. return false;
  13024. },
  13025. /**
  13026. * Checks whether a word exists in the current dictionary.
  13027. *
  13028. * @param {String} word The word to check.
  13029. * @returns {Boolean}
  13030. */
  13031. checkExact : function (word) {
  13032. var ruleCodes = this.dictionaryTable[word];
  13033. if (typeof ruleCodes === 'undefined') {
  13034. // Check if this might be a compound word.
  13035. if ("COMPOUNDMIN" in this.flags && word.length >= this.flags.COMPOUNDMIN) {
  13036. for (var i = 0, _len = this.compoundRules.length; i < _len; i++) {
  13037. if (word.match(this.compoundRules[i])) {
  13038. return true;
  13039. }
  13040. }
  13041. }
  13042. return false;
  13043. }
  13044. else if (typeof ruleCodes === 'object') { // this.dictionary['hasOwnProperty'] will be a function.
  13045. for (var i = 0, _len = ruleCodes.length; i < _len; i++) {
  13046. if (!this.hasFlag(word, "ONLYINCOMPOUND", ruleCodes[i])) {
  13047. return true;
  13048. }
  13049. }
  13050. return false;
  13051. }
  13052. },
  13053. /**
  13054. * Looks up whether a given word is flagged with a given flag.
  13055. *
  13056. * @param {String} word The word in question.
  13057. * @param {String} flag The flag in question.
  13058. * @return {Boolean}
  13059. */
  13060. hasFlag : function (word, flag, wordFlags) {
  13061. if (flag in this.flags) {
  13062. if (typeof wordFlags === 'undefined') {
  13063. var wordFlags = Array.prototype.concat.apply([], this.dictionaryTable[word]);
  13064. }
  13065. if (wordFlags && wordFlags.indexOf(this.flags[flag]) !== -1) {
  13066. return true;
  13067. }
  13068. }
  13069. return false;
  13070. },
  13071. /**
  13072. * Returns a list of suggestions for a misspelled word.
  13073. *
  13074. * @see http://www.norvig.com/spell-correct.html for the basis of this suggestor.
  13075. * This suggestor is primitive, but it works.
  13076. *
  13077. * @param {String} word The misspelling.
  13078. * @param {Number} [limit=5] The maximum number of suggestions to return.
  13079. * @returns {String[]} The array of suggestions.
  13080. */
  13081. alphabet : "",
  13082. suggest : function (word, limit) {
  13083. if (!limit) limit = 5;
  13084. if (this.check(word)) return [];
  13085. // Check the replacement table.
  13086. for (var i = 0, _len = this.replacementTable.length; i < _len; i++) {
  13087. var replacementEntry = this.replacementTable[i];
  13088. if (word.indexOf(replacementEntry[0]) !== -1) {
  13089. var correctedWord = word.replace(replacementEntry[0], replacementEntry[1]);
  13090. if (this.check(correctedWord)) {
  13091. return [ correctedWord ];
  13092. }
  13093. }
  13094. }
  13095. var self = this;
  13096. self.alphabet = "abcdefghijklmnopqrstuvwxyz";
  13097. /*
  13098. if (!self.alphabet) {
  13099. // Use the alphabet as implicitly defined by the words in the dictionary.
  13100. var alphaHash = {};
  13101. for (var i in self.dictionaryTable) {
  13102. for (var j = 0, _len = i.length; j < _len; j++) {
  13103. alphaHash[i[j]] = true;
  13104. }
  13105. }
  13106. for (var i in alphaHash) {
  13107. self.alphabet += i;
  13108. }
  13109. var alphaArray = self.alphabet.split("");
  13110. alphaArray.sort();
  13111. self.alphabet = alphaArray.join("");
  13112. }
  13113. */
  13114. function edits1(words) {
  13115. var rv = [];
  13116. for (var ii = 0, _iilen = words.length; ii < _iilen; ii++) {
  13117. var word = words[ii];
  13118. var splits = [];
  13119. for (var i = 0, _len = word.length + 1; i < _len; i++) {
  13120. splits.push([ word.substring(0, i), word.substring(i, word.length) ]);
  13121. }
  13122. var deletes = [];
  13123. for (var i = 0, _len = splits.length; i < _len; i++) {
  13124. var s = splits[i];
  13125. if (s[1]) {
  13126. deletes.push(s[0] + s[1].substring(1));
  13127. }
  13128. }
  13129. var transposes = [];
  13130. for (var i = 0, _len = splits.length; i < _len; i++) {
  13131. var s = splits[i];
  13132. if (s[1].length > 1) {
  13133. transposes.push(s[0] + s[1][1] + s[1][0] + s[1].substring(2));
  13134. }
  13135. }
  13136. var replaces = [];
  13137. for (var i = 0, _len = splits.length; i < _len; i++) {
  13138. var s = splits[i];
  13139. if (s[1]) {
  13140. for (var j = 0, _jlen = self.alphabet.length; j < _jlen; j++) {
  13141. replaces.push(s[0] + self.alphabet[j] + s[1].substring(1));
  13142. }
  13143. }
  13144. }
  13145. var inserts = [];
  13146. for (var i = 0, _len = splits.length; i < _len; i++) {
  13147. var s = splits[i];
  13148. if (s[1]) {
  13149. for (var j = 0, _jlen = self.alphabet.length; j < _jlen; j++) {
  13150. replaces.push(s[0] + self.alphabet[j] + s[1]);
  13151. }
  13152. }
  13153. }
  13154. rv = rv.concat(deletes);
  13155. rv = rv.concat(transposes);
  13156. rv = rv.concat(replaces);
  13157. rv = rv.concat(inserts);
  13158. }
  13159. return rv;
  13160. }
  13161. function known(words) {
  13162. var rv = [];
  13163. for (var i = 0; i < words.length; i++) {
  13164. if (self.check(words[i])) {
  13165. rv.push(words[i]);
  13166. }
  13167. }
  13168. return rv;
  13169. }
  13170. function correct(word) {
  13171. // Get the edit-distance-1 and edit-distance-2 forms of this word.
  13172. var ed1 = edits1([word]);
  13173. var ed2 = edits1(ed1);
  13174. var corrections = known(ed1).concat(known(ed2));
  13175. // Sort the edits based on how many different ways they were created.
  13176. var weighted_corrections = {};
  13177. for (var i = 0, _len = corrections.length; i < _len; i++) {
  13178. if (!(corrections[i] in weighted_corrections)) {
  13179. weighted_corrections[corrections[i]] = 1;
  13180. }
  13181. else {
  13182. weighted_corrections[corrections[i]] += 1;
  13183. }
  13184. }
  13185. var sorted_corrections = [];
  13186. for (var i in weighted_corrections) {
  13187. sorted_corrections.push([ i, weighted_corrections[i] ]);
  13188. }
  13189. function sorter(a, b) {
  13190. if (a[1] < b[1]) {
  13191. return -1;
  13192. }
  13193. return 1;
  13194. }
  13195. sorted_corrections.sort(sorter).reverse();
  13196. var rv = [];
  13197. for (var i = 0, _len = Math.min(limit, sorted_corrections.length); i < _len; i++) {
  13198. if (!self.hasFlag(sorted_corrections[i][0], "NOSUGGEST")) {
  13199. rv.push(sorted_corrections[i][0]);
  13200. }
  13201. }
  13202. return rv;
  13203. }
  13204. return correct(word);
  13205. }
  13206. };
  13207. // Support for use as a node.js module.
  13208. if (typeof module !== 'undefined') {
  13209. module.exports = Typo;
  13210. }
  13211. }).call(this,require("buffer").Buffer,"/node_modules/typo-js")
  13212. },{"buffer":3,"fs":2}],19:[function(require,module,exports){
  13213. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  13214. // Distributed under an MIT license: http://codemirror.net/LICENSE
  13215. var CodeMirror = require("codemirror");
  13216. CodeMirror.commands.tabAndIndentMarkdownList = function (cm) {
  13217. var ranges = cm.listSelections();
  13218. var pos = ranges[0].head;
  13219. var eolState = cm.getStateAfter(pos.line);
  13220. var inList = eolState.list !== false;
  13221. if (inList) {
  13222. cm.execCommand("indentMore");
  13223. return;
  13224. }
  13225. if (cm.options.indentWithTabs) {
  13226. cm.execCommand("insertTab");
  13227. }
  13228. else {
  13229. var spaces = Array(cm.options.tabSize + 1).join(" ");
  13230. cm.replaceSelection(spaces);
  13231. }
  13232. };
  13233. CodeMirror.commands.shiftTabAndUnindentMarkdownList = function (cm) {
  13234. var ranges = cm.listSelections();
  13235. var pos = ranges[0].head;
  13236. var eolState = cm.getStateAfter(pos.line);
  13237. var inList = eolState.list !== false;
  13238. if (inList) {
  13239. cm.execCommand("indentLess");
  13240. return;
  13241. }
  13242. if (cm.options.indentWithTabs) {
  13243. cm.execCommand("insertTab");
  13244. }
  13245. else {
  13246. var spaces = Array(cm.options.tabSize + 1).join(" ");
  13247. cm.replaceSelection(spaces);
  13248. }
  13249. };
  13250. },{"codemirror":10}],20:[function(require,module,exports){
  13251. /*global require,module*/
  13252. "use strict";
  13253. var CodeMirror = require("codemirror");
  13254. require("codemirror/addon/edit/continuelist.js");
  13255. require("./codemirror/tablist");
  13256. require("codemirror/addon/display/fullscreen.js");
  13257. require("codemirror/mode/markdown/markdown.js");
  13258. require("codemirror/addon/mode/overlay.js");
  13259. require("codemirror/addon/display/placeholder.js");
  13260. require("codemirror/addon/selection/mark-selection.js");
  13261. require("codemirror/mode/gfm/gfm.js");
  13262. require("codemirror/mode/xml/xml.js");
  13263. var CodeMirrorSpellChecker = require("codemirror-spell-checker");
  13264. var marked = require("marked");
  13265. // Some variables
  13266. var isMac = /Mac/.test(navigator.platform);
  13267. // Mapping of actions that can be bound to keyboard shortcuts or toolbar buttons
  13268. var bindings = {
  13269. "toggleBold": toggleBold,
  13270. "toggleItalic": toggleItalic,
  13271. "drawLink": drawLink,
  13272. "toggleHeadingSmaller": toggleHeadingSmaller,
  13273. "toggleHeadingBigger": toggleHeadingBigger,
  13274. "drawImage": drawImage,
  13275. "toggleBlockquote": toggleBlockquote,
  13276. "toggleOrderedList": toggleOrderedList,
  13277. "toggleUnorderedList": toggleUnorderedList,
  13278. "toggleCodeBlock": toggleCodeBlock,
  13279. "togglePreview": togglePreview,
  13280. "toggleStrikethrough": toggleStrikethrough,
  13281. "toggleHeading1": toggleHeading1,
  13282. "toggleHeading2": toggleHeading2,
  13283. "toggleHeading3": toggleHeading3,
  13284. "cleanBlock": cleanBlock,
  13285. "drawTable": drawTable,
  13286. "drawHorizontalRule": drawHorizontalRule,
  13287. "undo": undo,
  13288. "redo": redo,
  13289. "toggleSideBySide": toggleSideBySide,
  13290. "toggleFullScreen": toggleFullScreen
  13291. };
  13292. var shortcuts = {
  13293. "toggleBold": "Cmd-B",
  13294. "toggleItalic": "Cmd-I",
  13295. "drawLink": "Cmd-K",
  13296. "toggleHeadingSmaller": "Cmd-H",
  13297. "toggleHeadingBigger": "Shift-Cmd-H",
  13298. "cleanBlock": "Cmd-E",
  13299. "drawImage": "Cmd-Alt-I",
  13300. "toggleBlockquote": "Cmd-'",
  13301. "toggleOrderedList": "Cmd-Alt-L",
  13302. "toggleUnorderedList": "Cmd-L",
  13303. "toggleCodeBlock": "Cmd-Alt-C",
  13304. "togglePreview": "Cmd-P",
  13305. "toggleSideBySide": "F9",
  13306. "toggleFullScreen": "F11"
  13307. };
  13308. var getBindingName = function(f) {
  13309. for(var key in bindings) {
  13310. if(bindings[key] === f) {
  13311. return key;
  13312. }
  13313. }
  13314. return null;
  13315. };
  13316. var isMobile = function() {
  13317. var check = false;
  13318. (function(a) {
  13319. 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;
  13320. })(navigator.userAgent || navigator.vendor || window.opera);
  13321. return check;
  13322. };
  13323. /**
  13324. * Fix shortcut. Mac use Command, others use Ctrl.
  13325. */
  13326. function fixShortcut(name) {
  13327. if(isMac) {
  13328. name = name.replace("Ctrl", "Cmd");
  13329. } else {
  13330. name = name.replace("Cmd", "Ctrl");
  13331. }
  13332. return name;
  13333. }
  13334. /**
  13335. * Create icon element for toolbar.
  13336. */
  13337. function createIcon(options, enableTooltips, shortcuts) {
  13338. options = options || {};
  13339. var el = document.createElement("a");
  13340. enableTooltips = (enableTooltips == undefined) ? true : enableTooltips;
  13341. if(options.title && enableTooltips) {
  13342. el.title = createTootlip(options.title, options.action, shortcuts);
  13343. if(isMac) {
  13344. el.title = el.title.replace("Ctrl", "⌘");
  13345. el.title = el.title.replace("Alt", "⌥");
  13346. }
  13347. }
  13348. el.tabIndex = -1;
  13349. el.className = options.className;
  13350. return el;
  13351. }
  13352. function createSep() {
  13353. var el = document.createElement("i");
  13354. el.className = "separator";
  13355. el.innerHTML = "|";
  13356. return el;
  13357. }
  13358. function createTootlip(title, action, shortcuts) {
  13359. var actionName;
  13360. var tooltip = title;
  13361. if(action) {
  13362. actionName = getBindingName(action);
  13363. if(shortcuts[actionName]) {
  13364. tooltip += " (" + fixShortcut(shortcuts[actionName]) + ")";
  13365. }
  13366. }
  13367. return tooltip;
  13368. }
  13369. /**
  13370. * The state of CodeMirror at the given position.
  13371. */
  13372. function getState(cm, pos) {
  13373. pos = pos || cm.getCursor("start");
  13374. var stat = cm.getTokenAt(pos);
  13375. if(!stat.type) return {};
  13376. var types = stat.type.split(" ");
  13377. var ret = {},
  13378. data, text;
  13379. for(var i = 0; i < types.length; i++) {
  13380. data = types[i];
  13381. if(data === "strong") {
  13382. ret.bold = true;
  13383. } else if(data === "variable-2") {
  13384. text = cm.getLine(pos.line);
  13385. if(/^\s*\d+\.\s/.test(text)) {
  13386. ret["ordered-list"] = true;
  13387. } else {
  13388. ret["unordered-list"] = true;
  13389. }
  13390. } else if(data === "atom") {
  13391. ret.quote = true;
  13392. } else if(data === "em") {
  13393. ret.italic = true;
  13394. } else if(data === "quote") {
  13395. ret.quote = true;
  13396. } else if(data === "strikethrough") {
  13397. ret.strikethrough = true;
  13398. } else if(data === "comment") {
  13399. ret.code = true;
  13400. } else if(data === "link") {
  13401. ret.link = true;
  13402. } else if(data === "tag") {
  13403. ret.image = true;
  13404. } else if(data.match(/^header(\-[1-6])?$/)) {
  13405. ret[data.replace("header", "heading")] = true;
  13406. }
  13407. }
  13408. return ret;
  13409. }
  13410. // Saved overflow setting
  13411. var saved_overflow = "";
  13412. /**
  13413. * Toggle full screen of the editor.
  13414. */
  13415. function toggleFullScreen(editor) {
  13416. // Set fullscreen
  13417. var cm = editor.codemirror;
  13418. cm.setOption("fullScreen", !cm.getOption("fullScreen"));
  13419. // Prevent scrolling on body during fullscreen active
  13420. if(cm.getOption("fullScreen")) {
  13421. saved_overflow = document.body.style.overflow;
  13422. document.body.style.overflow = "hidden";
  13423. } else {
  13424. document.body.style.overflow = saved_overflow;
  13425. }
  13426. // Update toolbar class
  13427. var wrap = cm.getWrapperElement();
  13428. if(!/fullscreen/.test(wrap.previousSibling.className)) {
  13429. wrap.previousSibling.className += " fullscreen";
  13430. } else {
  13431. wrap.previousSibling.className = wrap.previousSibling.className.replace(/\s*fullscreen\b/, "");
  13432. }
  13433. // Update toolbar button
  13434. var toolbarButton = editor.toolbarElements.fullscreen;
  13435. if(!/active/.test(toolbarButton.className)) {
  13436. toolbarButton.className += " active";
  13437. } else {
  13438. toolbarButton.className = toolbarButton.className.replace(/\s*active\s*/g, "");
  13439. }
  13440. // Hide side by side if needed
  13441. var sidebyside = cm.getWrapperElement().nextSibling;
  13442. if(/editor-preview-active-side/.test(sidebyside.className))
  13443. toggleSideBySide(editor);
  13444. }
  13445. /**
  13446. * Action for toggling bold.
  13447. */
  13448. function toggleBold(editor) {
  13449. _toggleBlock(editor, "bold", editor.options.blockStyles.bold);
  13450. }
  13451. /**
  13452. * Action for toggling italic.
  13453. */
  13454. function toggleItalic(editor) {
  13455. _toggleBlock(editor, "italic", editor.options.blockStyles.italic);
  13456. }
  13457. /**
  13458. * Action for toggling strikethrough.
  13459. */
  13460. function toggleStrikethrough(editor) {
  13461. _toggleBlock(editor, "strikethrough", "~~");
  13462. }
  13463. /**
  13464. * Action for toggling code block.
  13465. */
  13466. function toggleCodeBlock(editor) {
  13467. var fenceCharsToInsert = editor.options.blockStyles.code;
  13468. function fencing_line(line) {
  13469. /* return true, if this is a ``` or ~~~ line */
  13470. if(typeof line !== "object") {
  13471. throw "fencing_line() takes a 'line' object (not a line number, or line text). Got: " + typeof line + ": " + line;
  13472. }
  13473. return line.styles && line.styles[2] && line.styles[2].indexOf("formatting-code-block") !== -1;
  13474. }
  13475. function token_state(token) {
  13476. // base goes an extra level deep when mode backdrops are used, e.g. spellchecker on
  13477. return token.state.base.base || token.state.base;
  13478. }
  13479. function code_type(cm, line_num, line, firstTok, lastTok) {
  13480. /*
  13481. * Return "single", "indented", "fenced" or false
  13482. *
  13483. * cm and line_num are required. Others are optional for efficiency
  13484. * To check in the middle of a line, pass in firstTok yourself.
  13485. */
  13486. line = line || cm.getLineHandle(line_num);
  13487. firstTok = firstTok || cm.getTokenAt({
  13488. line: line_num,
  13489. ch: 1
  13490. });
  13491. lastTok = lastTok || (!!line.text && cm.getTokenAt({
  13492. line: line_num,
  13493. ch: line.text.length - 1
  13494. }));
  13495. var types = firstTok.type ? firstTok.type.split(" ") : [];
  13496. if(lastTok && token_state(lastTok).indentedCode) {
  13497. // have to check last char, since first chars of first line aren"t marked as indented
  13498. return "indented";
  13499. } else if(types.indexOf("comment") === -1) {
  13500. // has to be after "indented" check, since first chars of first indented line aren"t marked as such
  13501. return false;
  13502. } else if(token_state(firstTok).fencedChars || token_state(lastTok).fencedChars || fencing_line(line)) {
  13503. return "fenced";
  13504. } else {
  13505. return "single";
  13506. }
  13507. }
  13508. function insertFencingAtSelection(cm, cur_start, cur_end, fenceCharsToInsert) {
  13509. var start_line_sel = cur_start.line + 1,
  13510. end_line_sel = cur_end.line + 1,
  13511. sel_multi = cur_start.line !== cur_end.line,
  13512. repl_start = fenceCharsToInsert + "\n",
  13513. repl_end = "\n" + fenceCharsToInsert;
  13514. if(sel_multi) {
  13515. end_line_sel++;
  13516. }
  13517. // handle last char including \n or not
  13518. if(sel_multi && cur_end.ch === 0) {
  13519. repl_end = fenceCharsToInsert + "\n";
  13520. end_line_sel--;
  13521. }
  13522. _replaceSelection(cm, false, [repl_start, repl_end]);
  13523. cm.setSelection({
  13524. line: start_line_sel,
  13525. ch: 0
  13526. }, {
  13527. line: end_line_sel,
  13528. ch: 0
  13529. });
  13530. }
  13531. var cm = editor.codemirror,
  13532. cur_start = cm.getCursor("start"),
  13533. cur_end = cm.getCursor("end"),
  13534. tok = cm.getTokenAt({
  13535. line: cur_start.line,
  13536. ch: cur_start.ch || 1
  13537. }), // avoid ch 0 which is a cursor pos but not token
  13538. line = cm.getLineHandle(cur_start.line),
  13539. is_code = code_type(cm, cur_start.line, line, tok);
  13540. var block_start, block_end, lineCount;
  13541. if(is_code === "single") {
  13542. // similar to some SimpleMDE _toggleBlock logic
  13543. var start = line.text.slice(0, cur_start.ch).replace("`", ""),
  13544. end = line.text.slice(cur_start.ch).replace("`", "");
  13545. cm.replaceRange(start + end, {
  13546. line: cur_start.line,
  13547. ch: 0
  13548. }, {
  13549. line: cur_start.line,
  13550. ch: 99999999999999
  13551. });
  13552. cur_start.ch--;
  13553. if(cur_start !== cur_end) {
  13554. cur_end.ch--;
  13555. }
  13556. cm.setSelection(cur_start, cur_end);
  13557. cm.focus();
  13558. } else if(is_code === "fenced") {
  13559. if(cur_start.line !== cur_end.line || cur_start.ch !== cur_end.ch) {
  13560. // use selection
  13561. // find the fenced line so we know what type it is (tilde, backticks, number of them)
  13562. for(block_start = cur_start.line; block_start >= 0; block_start--) {
  13563. line = cm.getLineHandle(block_start);
  13564. if(fencing_line(line)) {
  13565. break;
  13566. }
  13567. }
  13568. var fencedTok = cm.getTokenAt({
  13569. line: block_start,
  13570. ch: 1
  13571. });
  13572. var fence_chars = token_state(fencedTok).fencedChars;
  13573. var start_text, start_line;
  13574. var end_text, end_line;
  13575. // check for selection going up against fenced lines, in which case we don't want to add more fencing
  13576. if(fencing_line(cm.getLineHandle(cur_start.line))) {
  13577. start_text = "";
  13578. start_line = cur_start.line;
  13579. } else if(fencing_line(cm.getLineHandle(cur_start.line - 1))) {
  13580. start_text = "";
  13581. start_line = cur_start.line - 1;
  13582. } else {
  13583. start_text = fence_chars + "\n";
  13584. start_line = cur_start.line;
  13585. }
  13586. if(fencing_line(cm.getLineHandle(cur_end.line))) {
  13587. end_text = "";
  13588. end_line = cur_end.line;
  13589. if(cur_end.ch === 0) {
  13590. end_line += 1;
  13591. }
  13592. } else if(cur_end.ch !== 0 && fencing_line(cm.getLineHandle(cur_end.line + 1))) {
  13593. end_text = "";
  13594. end_line = cur_end.line + 1;
  13595. } else {
  13596. end_text = fence_chars + "\n";
  13597. end_line = cur_end.line + 1;
  13598. }
  13599. if(cur_end.ch === 0) {
  13600. // full last line selected, putting cursor at beginning of next
  13601. end_line -= 1;
  13602. }
  13603. cm.operation(function() {
  13604. // end line first, so that line numbers don't change
  13605. cm.replaceRange(end_text, {
  13606. line: end_line,
  13607. ch: 0
  13608. }, {
  13609. line: end_line + (end_text ? 0 : 1),
  13610. ch: 0
  13611. });
  13612. cm.replaceRange(start_text, {
  13613. line: start_line,
  13614. ch: 0
  13615. }, {
  13616. line: start_line + (start_text ? 0 : 1),
  13617. ch: 0
  13618. });
  13619. });
  13620. cm.setSelection({
  13621. line: start_line + (start_text ? 1 : 0),
  13622. ch: 0
  13623. }, {
  13624. line: end_line + (start_text ? 1 : -1),
  13625. ch: 0
  13626. });
  13627. cm.focus();
  13628. } else {
  13629. // no selection, search for ends of this fenced block
  13630. var search_from = cur_start.line;
  13631. if(fencing_line(cm.getLineHandle(cur_start.line))) { // gets a little tricky if cursor is right on a fenced line
  13632. if(code_type(cm, cur_start.line + 1) === "fenced") {
  13633. block_start = cur_start.line;
  13634. search_from = cur_start.line + 1; // for searching for "end"
  13635. } else {
  13636. block_end = cur_start.line;
  13637. search_from = cur_start.line - 1; // for searching for "start"
  13638. }
  13639. }
  13640. if(block_start === undefined) {
  13641. for(block_start = search_from; block_start >= 0; block_start--) {
  13642. line = cm.getLineHandle(block_start);
  13643. if(fencing_line(line)) {
  13644. break;
  13645. }
  13646. }
  13647. }
  13648. if(block_end === undefined) {
  13649. lineCount = cm.lineCount();
  13650. for(block_end = search_from; block_end < lineCount; block_end++) {
  13651. line = cm.getLineHandle(block_end);
  13652. if(fencing_line(line)) {
  13653. break;
  13654. }
  13655. }
  13656. }
  13657. cm.operation(function() {
  13658. cm.replaceRange("", {
  13659. line: block_start,
  13660. ch: 0
  13661. }, {
  13662. line: block_start + 1,
  13663. ch: 0
  13664. });
  13665. cm.replaceRange("", {
  13666. line: block_end - 1,
  13667. ch: 0
  13668. }, {
  13669. line: block_end,
  13670. ch: 0
  13671. });
  13672. });
  13673. cm.focus();
  13674. }
  13675. } else if(is_code === "indented") {
  13676. if(cur_start.line !== cur_end.line || cur_start.ch !== cur_end.ch) {
  13677. // use selection
  13678. block_start = cur_start.line;
  13679. block_end = cur_end.line;
  13680. if(cur_end.ch === 0) {
  13681. block_end--;
  13682. }
  13683. } else {
  13684. // no selection, search for ends of this indented block
  13685. for(block_start = cur_start.line; block_start >= 0; block_start--) {
  13686. line = cm.getLineHandle(block_start);
  13687. if(line.text.match(/^\s*$/)) {
  13688. // empty or all whitespace - keep going
  13689. continue;
  13690. } else {
  13691. if(code_type(cm, block_start, line) !== "indented") {
  13692. block_start += 1;
  13693. break;
  13694. }
  13695. }
  13696. }
  13697. lineCount = cm.lineCount();
  13698. for(block_end = cur_start.line; block_end < lineCount; block_end++) {
  13699. line = cm.getLineHandle(block_end);
  13700. if(line.text.match(/^\s*$/)) {
  13701. // empty or all whitespace - keep going
  13702. continue;
  13703. } else {
  13704. if(code_type(cm, block_end, line) !== "indented") {
  13705. block_end -= 1;
  13706. break;
  13707. }
  13708. }
  13709. }
  13710. }
  13711. // if we are going to un-indent based on a selected set of lines, and the next line is indented too, we need to
  13712. // insert a blank line so that the next line(s) continue to be indented code
  13713. var next_line = cm.getLineHandle(block_end + 1),
  13714. next_line_last_tok = next_line && cm.getTokenAt({
  13715. line: block_end + 1,
  13716. ch: next_line.text.length - 1
  13717. }),
  13718. next_line_indented = next_line_last_tok && token_state(next_line_last_tok).indentedCode;
  13719. if(next_line_indented) {
  13720. cm.replaceRange("\n", {
  13721. line: block_end + 1,
  13722. ch: 0
  13723. });
  13724. }
  13725. for(var i = block_start; i <= block_end; i++) {
  13726. cm.indentLine(i, "subtract"); // TODO: this doesn't get tracked in the history, so can't be undone :(
  13727. }
  13728. cm.focus();
  13729. } else {
  13730. // insert code formatting
  13731. var no_sel_and_starting_of_line = (cur_start.line === cur_end.line && cur_start.ch === cur_end.ch && cur_start.ch === 0);
  13732. var sel_multi = cur_start.line !== cur_end.line;
  13733. if(no_sel_and_starting_of_line || sel_multi) {
  13734. insertFencingAtSelection(cm, cur_start, cur_end, fenceCharsToInsert);
  13735. } else {
  13736. _replaceSelection(cm, false, ["`", "`"]);
  13737. }
  13738. }
  13739. }
  13740. /**
  13741. * Action for toggling blockquote.
  13742. */
  13743. function toggleBlockquote(editor) {
  13744. var cm = editor.codemirror;
  13745. _toggleLine(cm, "quote");
  13746. }
  13747. /**
  13748. * Action for toggling heading size: normal -> h1 -> h2 -> h3 -> h4 -> h5 -> h6 -> normal
  13749. */
  13750. function toggleHeadingSmaller(editor) {
  13751. var cm = editor.codemirror;
  13752. _toggleHeading(cm, "smaller");
  13753. }
  13754. /**
  13755. * Action for toggling heading size: normal -> h6 -> h5 -> h4 -> h3 -> h2 -> h1 -> normal
  13756. */
  13757. function toggleHeadingBigger(editor) {
  13758. var cm = editor.codemirror;
  13759. _toggleHeading(cm, "bigger");
  13760. }
  13761. /**
  13762. * Action for toggling heading size 1
  13763. */
  13764. function toggleHeading1(editor) {
  13765. var cm = editor.codemirror;
  13766. _toggleHeading(cm, undefined, 1);
  13767. }
  13768. /**
  13769. * Action for toggling heading size 2
  13770. */
  13771. function toggleHeading2(editor) {
  13772. var cm = editor.codemirror;
  13773. _toggleHeading(cm, undefined, 2);
  13774. }
  13775. /**
  13776. * Action for toggling heading size 3
  13777. */
  13778. function toggleHeading3(editor) {
  13779. var cm = editor.codemirror;
  13780. _toggleHeading(cm, undefined, 3);
  13781. }
  13782. /**
  13783. * Action for toggling ul.
  13784. */
  13785. function toggleUnorderedList(editor) {
  13786. var cm = editor.codemirror;
  13787. _toggleLine(cm, "unordered-list");
  13788. }
  13789. /**
  13790. * Action for toggling ol.
  13791. */
  13792. function toggleOrderedList(editor) {
  13793. var cm = editor.codemirror;
  13794. _toggleLine(cm, "ordered-list");
  13795. }
  13796. /**
  13797. * Action for clean block (remove headline, list, blockquote code, markers)
  13798. */
  13799. function cleanBlock(editor) {
  13800. var cm = editor.codemirror;
  13801. _cleanBlock(cm);
  13802. }
  13803. /**
  13804. * Action for drawing a link.
  13805. */
  13806. function drawLink(editor) {
  13807. var cm = editor.codemirror;
  13808. var stat = getState(cm);
  13809. var options = editor.options;
  13810. var url = "http://";
  13811. if(options.promptURLs) {
  13812. url = prompt(options.promptTexts.link);
  13813. if(!url) {
  13814. return false;
  13815. }
  13816. }
  13817. _replaceSelection(cm, stat.link, options.insertTexts.link, url);
  13818. }
  13819. /**
  13820. * Action for drawing an img.
  13821. */
  13822. function drawImage(editor) {
  13823. var cm = editor.codemirror;
  13824. var stat = getState(cm);
  13825. var options = editor.options;
  13826. var url = "http://";
  13827. if(options.promptURLs) {
  13828. url = prompt(options.promptTexts.image);
  13829. if(!url) {
  13830. return false;
  13831. }
  13832. }
  13833. _replaceSelection(cm, stat.image, options.insertTexts.image, url);
  13834. }
  13835. /**
  13836. * Action for drawing a table.
  13837. */
  13838. function drawTable(editor) {
  13839. var cm = editor.codemirror;
  13840. var stat = getState(cm);
  13841. var options = editor.options;
  13842. _replaceSelection(cm, stat.table, options.insertTexts.table);
  13843. }
  13844. /**
  13845. * Action for drawing a horizontal rule.
  13846. */
  13847. function drawHorizontalRule(editor) {
  13848. var cm = editor.codemirror;
  13849. var stat = getState(cm);
  13850. var options = editor.options;
  13851. _replaceSelection(cm, stat.image, options.insertTexts.horizontalRule);
  13852. }
  13853. /**
  13854. * Undo action.
  13855. */
  13856. function undo(editor) {
  13857. var cm = editor.codemirror;
  13858. cm.undo();
  13859. cm.focus();
  13860. }
  13861. /**
  13862. * Redo action.
  13863. */
  13864. function redo(editor) {
  13865. var cm = editor.codemirror;
  13866. cm.redo();
  13867. cm.focus();
  13868. }
  13869. /**
  13870. * Toggle side by side preview
  13871. */
  13872. function toggleSideBySide(editor) {
  13873. var cm = editor.codemirror;
  13874. var wrapper = cm.getWrapperElement();
  13875. var preview = wrapper.nextSibling;
  13876. var toolbarButton = editor.toolbarElements["side-by-side"];
  13877. var useSideBySideListener = false;
  13878. if(/editor-preview-active-side/.test(preview.className)) {
  13879. preview.className = preview.className.replace(
  13880. /\s*editor-preview-active-side\s*/g, ""
  13881. );
  13882. toolbarButton.className = toolbarButton.className.replace(/\s*active\s*/g, "");
  13883. wrapper.className = wrapper.className.replace(/\s*CodeMirror-sided\s*/g, " ");
  13884. } else {
  13885. // When the preview button is clicked for the first time,
  13886. // give some time for the transition from editor.css to fire and the view to slide from right to left,
  13887. // instead of just appearing.
  13888. setTimeout(function() {
  13889. if(!cm.getOption("fullScreen"))
  13890. toggleFullScreen(editor);
  13891. preview.className += " editor-preview-active-side";
  13892. }, 1);
  13893. toolbarButton.className += " active";
  13894. wrapper.className += " CodeMirror-sided";
  13895. useSideBySideListener = true;
  13896. }
  13897. // Hide normal preview if active
  13898. var previewNormal = wrapper.lastChild;
  13899. if(/editor-preview-active/.test(previewNormal.className)) {
  13900. previewNormal.className = previewNormal.className.replace(
  13901. /\s*editor-preview-active\s*/g, ""
  13902. );
  13903. var toolbar = editor.toolbarElements.preview;
  13904. var toolbar_div = wrapper.previousSibling;
  13905. toolbar.className = toolbar.className.replace(/\s*active\s*/g, "");
  13906. toolbar_div.className = toolbar_div.className.replace(/\s*disabled-for-preview*/g, "");
  13907. }
  13908. var sideBySideRenderingFunction = function() {
  13909. preview.innerHTML = editor.options.previewRender(editor.value(), preview);
  13910. };
  13911. if(!cm.sideBySideRenderingFunction) {
  13912. cm.sideBySideRenderingFunction = sideBySideRenderingFunction;
  13913. }
  13914. if(useSideBySideListener) {
  13915. preview.innerHTML = editor.options.previewRender(editor.value(), preview);
  13916. cm.on("update", cm.sideBySideRenderingFunction);
  13917. } else {
  13918. cm.off("update", cm.sideBySideRenderingFunction);
  13919. }
  13920. // Refresh to fix selection being off (#309)
  13921. cm.refresh();
  13922. }
  13923. /**
  13924. * Preview action.
  13925. */
  13926. function togglePreview(editor) {
  13927. var cm = editor.codemirror;
  13928. var wrapper = cm.getWrapperElement();
  13929. var toolbar_div = wrapper.previousSibling;
  13930. var toolbar = editor.options.toolbar ? editor.toolbarElements.preview : false;
  13931. var preview = wrapper.lastChild;
  13932. if(!preview || !/editor-preview/.test(preview.className)) {
  13933. preview = document.createElement("div");
  13934. preview.className = "editor-preview";
  13935. wrapper.appendChild(preview);
  13936. }
  13937. if(/editor-preview-active/.test(preview.className)) {
  13938. preview.className = preview.className.replace(
  13939. /\s*editor-preview-active\s*/g, ""
  13940. );
  13941. if(toolbar) {
  13942. toolbar.className = toolbar.className.replace(/\s*active\s*/g, "");
  13943. toolbar_div.className = toolbar_div.className.replace(/\s*disabled-for-preview*/g, "");
  13944. }
  13945. } else {
  13946. // When the preview button is clicked for the first time,
  13947. // give some time for the transition from editor.css to fire and the view to slide from right to left,
  13948. // instead of just appearing.
  13949. setTimeout(function() {
  13950. preview.className += " editor-preview-active";
  13951. }, 1);
  13952. if(toolbar) {
  13953. toolbar.className += " active";
  13954. toolbar_div.className += " disabled-for-preview";
  13955. }
  13956. }
  13957. preview.innerHTML = editor.options.previewRender(editor.value(), preview);
  13958. // Turn off side by side if needed
  13959. var sidebyside = cm.getWrapperElement().nextSibling;
  13960. if(/editor-preview-active-side/.test(sidebyside.className))
  13961. toggleSideBySide(editor);
  13962. }
  13963. function _replaceSelection(cm, active, startEnd, url) {
  13964. if(/editor-preview-active/.test(cm.getWrapperElement().lastChild.className))
  13965. return;
  13966. var text;
  13967. var start = startEnd[0];
  13968. var end = startEnd[1];
  13969. var startPoint = cm.getCursor("start");
  13970. var endPoint = cm.getCursor("end");
  13971. if(url) {
  13972. end = end.replace("#url#", url);
  13973. }
  13974. if(active) {
  13975. text = cm.getLine(startPoint.line);
  13976. start = text.slice(0, startPoint.ch);
  13977. end = text.slice(startPoint.ch);
  13978. cm.replaceRange(start + end, {
  13979. line: startPoint.line,
  13980. ch: 0
  13981. });
  13982. } else {
  13983. text = cm.getSelection();
  13984. cm.replaceSelection(start + text + end);
  13985. startPoint.ch += start.length;
  13986. if(startPoint !== endPoint) {
  13987. endPoint.ch += start.length;
  13988. }
  13989. }
  13990. cm.setSelection(startPoint, endPoint);
  13991. cm.focus();
  13992. }
  13993. function _toggleHeading(cm, direction, size) {
  13994. if(/editor-preview-active/.test(cm.getWrapperElement().lastChild.className))
  13995. return;
  13996. var startPoint = cm.getCursor("start");
  13997. var endPoint = cm.getCursor("end");
  13998. for(var i = startPoint.line; i <= endPoint.line; i++) {
  13999. (function(i) {
  14000. var text = cm.getLine(i);
  14001. var currHeadingLevel = text.search(/[^#]/);
  14002. if(direction !== undefined) {
  14003. if(currHeadingLevel <= 0) {
  14004. if(direction == "bigger") {
  14005. text = "###### " + text;
  14006. } else {
  14007. text = "# " + text;
  14008. }
  14009. } else if(currHeadingLevel == 6 && direction == "smaller") {
  14010. text = text.substr(7);
  14011. } else if(currHeadingLevel == 1 && direction == "bigger") {
  14012. text = text.substr(2);
  14013. } else {
  14014. if(direction == "bigger") {
  14015. text = text.substr(1);
  14016. } else {
  14017. text = "#" + text;
  14018. }
  14019. }
  14020. } else {
  14021. if(size == 1) {
  14022. if(currHeadingLevel <= 0) {
  14023. text = "# " + text;
  14024. } else if(currHeadingLevel == size) {
  14025. text = text.substr(currHeadingLevel + 1);
  14026. } else {
  14027. text = "# " + text.substr(currHeadingLevel + 1);
  14028. }
  14029. } else if(size == 2) {
  14030. if(currHeadingLevel <= 0) {
  14031. text = "## " + text;
  14032. } else if(currHeadingLevel == size) {
  14033. text = text.substr(currHeadingLevel + 1);
  14034. } else {
  14035. text = "## " + text.substr(currHeadingLevel + 1);
  14036. }
  14037. } else {
  14038. if(currHeadingLevel <= 0) {
  14039. text = "### " + text;
  14040. } else if(currHeadingLevel == size) {
  14041. text = text.substr(currHeadingLevel + 1);
  14042. } else {
  14043. text = "### " + text.substr(currHeadingLevel + 1);
  14044. }
  14045. }
  14046. }
  14047. cm.replaceRange(text, {
  14048. line: i,
  14049. ch: 0
  14050. }, {
  14051. line: i,
  14052. ch: 99999999999999
  14053. });
  14054. })(i);
  14055. }
  14056. cm.focus();
  14057. }
  14058. function _toggleLine(cm, name) {
  14059. if(/editor-preview-active/.test(cm.getWrapperElement().lastChild.className))
  14060. return;
  14061. var stat = getState(cm);
  14062. var startPoint = cm.getCursor("start");
  14063. var endPoint = cm.getCursor("end");
  14064. var repl = {
  14065. "quote": /^(\s*)\>\s+/,
  14066. "unordered-list": /^(\s*)(\*|\-|\+)\s+/,
  14067. "ordered-list": /^(\s*)\d+\.\s+/
  14068. };
  14069. var map = {
  14070. "quote": "> ",
  14071. "unordered-list": "* ",
  14072. "ordered-list": "1. "
  14073. };
  14074. for(var i = startPoint.line; i <= endPoint.line; i++) {
  14075. (function(i) {
  14076. var text = cm.getLine(i);
  14077. if(stat[name]) {
  14078. text = text.replace(repl[name], "$1");
  14079. } else {
  14080. text = map[name] + text;
  14081. }
  14082. cm.replaceRange(text, {
  14083. line: i,
  14084. ch: 0
  14085. }, {
  14086. line: i,
  14087. ch: 99999999999999
  14088. });
  14089. })(i);
  14090. }
  14091. cm.focus();
  14092. }
  14093. function _toggleBlock(editor, type, start_chars, end_chars) {
  14094. if(/editor-preview-active/.test(editor.codemirror.getWrapperElement().lastChild.className))
  14095. return;
  14096. end_chars = (typeof end_chars === "undefined") ? start_chars : end_chars;
  14097. var cm = editor.codemirror;
  14098. var stat = getState(cm);
  14099. var text;
  14100. var start = start_chars;
  14101. var end = end_chars;
  14102. var startPoint = cm.getCursor("start");
  14103. var endPoint = cm.getCursor("end");
  14104. if(stat[type]) {
  14105. text = cm.getLine(startPoint.line);
  14106. start = text.slice(0, startPoint.ch);
  14107. end = text.slice(startPoint.ch);
  14108. if(type == "bold") {
  14109. start = start.replace(/(\*\*|__)(?![\s\S]*(\*\*|__))/, "");
  14110. end = end.replace(/(\*\*|__)/, "");
  14111. } else if(type == "italic") {
  14112. start = start.replace(/(\*|_)(?![\s\S]*(\*|_))/, "");
  14113. end = end.replace(/(\*|_)/, "");
  14114. } else if(type == "strikethrough") {
  14115. start = start.replace(/(\*\*|~~)(?![\s\S]*(\*\*|~~))/, "");
  14116. end = end.replace(/(\*\*|~~)/, "");
  14117. }
  14118. cm.replaceRange(start + end, {
  14119. line: startPoint.line,
  14120. ch: 0
  14121. }, {
  14122. line: startPoint.line,
  14123. ch: 99999999999999
  14124. });
  14125. if(type == "bold" || type == "strikethrough") {
  14126. startPoint.ch -= 2;
  14127. if(startPoint !== endPoint) {
  14128. endPoint.ch -= 2;
  14129. }
  14130. } else if(type == "italic") {
  14131. startPoint.ch -= 1;
  14132. if(startPoint !== endPoint) {
  14133. endPoint.ch -= 1;
  14134. }
  14135. }
  14136. } else {
  14137. text = cm.getSelection();
  14138. if(type == "bold") {
  14139. text = text.split("**").join("");
  14140. text = text.split("__").join("");
  14141. } else if(type == "italic") {
  14142. text = text.split("*").join("");
  14143. text = text.split("_").join("");
  14144. } else if(type == "strikethrough") {
  14145. text = text.split("~~").join("");
  14146. }
  14147. cm.replaceSelection(start + text + end);
  14148. startPoint.ch += start_chars.length;
  14149. endPoint.ch = startPoint.ch + text.length;
  14150. }
  14151. cm.setSelection(startPoint, endPoint);
  14152. cm.focus();
  14153. }
  14154. function _cleanBlock(cm) {
  14155. if(/editor-preview-active/.test(cm.getWrapperElement().lastChild.className))
  14156. return;
  14157. var startPoint = cm.getCursor("start");
  14158. var endPoint = cm.getCursor("end");
  14159. var text;
  14160. for(var line = startPoint.line; line <= endPoint.line; line++) {
  14161. text = cm.getLine(line);
  14162. text = text.replace(/^[ ]*([# ]+|\*|\-|[> ]+|[0-9]+(.|\)))[ ]*/, "");
  14163. cm.replaceRange(text, {
  14164. line: line,
  14165. ch: 0
  14166. }, {
  14167. line: line,
  14168. ch: 99999999999999
  14169. });
  14170. }
  14171. }
  14172. // Merge the properties of one object into another.
  14173. function _mergeProperties(target, source) {
  14174. for(var property in source) {
  14175. if(source.hasOwnProperty(property)) {
  14176. if(source[property] instanceof Array) {
  14177. target[property] = source[property].concat(target[property] instanceof Array ? target[property] : []);
  14178. } else if(
  14179. source[property] !== null &&
  14180. typeof source[property] === "object" &&
  14181. source[property].constructor === Object
  14182. ) {
  14183. target[property] = _mergeProperties(target[property] || {}, source[property]);
  14184. } else {
  14185. target[property] = source[property];
  14186. }
  14187. }
  14188. }
  14189. return target;
  14190. }
  14191. // Merge an arbitrary number of objects into one.
  14192. function extend(target) {
  14193. for(var i = 1; i < arguments.length; i++) {
  14194. target = _mergeProperties(target, arguments[i]);
  14195. }
  14196. return target;
  14197. }
  14198. /* The right word count in respect for CJK. */
  14199. function wordCount(data) {
  14200. var pattern = /[a-zA-Z0-9_\u0392-\u03c9\u0410-\u04F9]+|[\u4E00-\u9FFF\u3400-\u4dbf\uf900-\ufaff\u3040-\u309f\uac00-\ud7af]+/g;
  14201. var m = data.match(pattern);
  14202. var count = 0;
  14203. if(m === null) return count;
  14204. for(var i = 0; i < m.length; i++) {
  14205. if(m[i].charCodeAt(0) >= 0x4E00) {
  14206. count += m[i].length;
  14207. } else {
  14208. count += 1;
  14209. }
  14210. }
  14211. return count;
  14212. }
  14213. var toolbarBuiltInButtons = {
  14214. "bold": {
  14215. name: "bold",
  14216. action: toggleBold,
  14217. className: "fa fa-bold",
  14218. title: "Bold",
  14219. default: true
  14220. },
  14221. "italic": {
  14222. name: "italic",
  14223. action: toggleItalic,
  14224. className: "fa fa-italic",
  14225. title: "Italic",
  14226. default: true
  14227. },
  14228. "strikethrough": {
  14229. name: "strikethrough",
  14230. action: toggleStrikethrough,
  14231. className: "fa fa-strikethrough",
  14232. title: "Strikethrough"
  14233. },
  14234. "heading": {
  14235. name: "heading",
  14236. action: toggleHeadingSmaller,
  14237. className: "fa fa-header",
  14238. title: "Heading",
  14239. default: true
  14240. },
  14241. "heading-smaller": {
  14242. name: "heading-smaller",
  14243. action: toggleHeadingSmaller,
  14244. className: "fa fa-header fa-header-x fa-header-smaller",
  14245. title: "Smaller Heading"
  14246. },
  14247. "heading-bigger": {
  14248. name: "heading-bigger",
  14249. action: toggleHeadingBigger,
  14250. className: "fa fa-header fa-header-x fa-header-bigger",
  14251. title: "Bigger Heading"
  14252. },
  14253. "heading-1": {
  14254. name: "heading-1",
  14255. action: toggleHeading1,
  14256. className: "fa fa-header fa-header-x fa-header-1",
  14257. title: "Big Heading"
  14258. },
  14259. "heading-2": {
  14260. name: "heading-2",
  14261. action: toggleHeading2,
  14262. className: "fa fa-header fa-header-x fa-header-2",
  14263. title: "Medium Heading"
  14264. },
  14265. "heading-3": {
  14266. name: "heading-3",
  14267. action: toggleHeading3,
  14268. className: "fa fa-header fa-header-x fa-header-3",
  14269. title: "Small Heading"
  14270. },
  14271. "separator-1": {
  14272. name: "separator-1"
  14273. },
  14274. "code": {
  14275. name: "code",
  14276. action: toggleCodeBlock,
  14277. className: "fa fa-code",
  14278. title: "Code"
  14279. },
  14280. "quote": {
  14281. name: "quote",
  14282. action: toggleBlockquote,
  14283. className: "fa fa-quote-left",
  14284. title: "Quote",
  14285. default: true
  14286. },
  14287. "unordered-list": {
  14288. name: "unordered-list",
  14289. action: toggleUnorderedList,
  14290. className: "fa fa-list-ul",
  14291. title: "Generic List",
  14292. default: true
  14293. },
  14294. "ordered-list": {
  14295. name: "ordered-list",
  14296. action: toggleOrderedList,
  14297. className: "fa fa-list-ol",
  14298. title: "Numbered List",
  14299. default: true
  14300. },
  14301. "clean-block": {
  14302. name: "clean-block",
  14303. action: cleanBlock,
  14304. className: "fa fa-eraser fa-clean-block",
  14305. title: "Clean block"
  14306. },
  14307. "separator-2": {
  14308. name: "separator-2"
  14309. },
  14310. "link": {
  14311. name: "link",
  14312. action: drawLink,
  14313. className: "fa fa-link",
  14314. title: "Create Link",
  14315. default: true
  14316. },
  14317. "image": {
  14318. name: "image",
  14319. action: drawImage,
  14320. className: "fa fa-picture-o",
  14321. title: "Insert Image",
  14322. default: true
  14323. },
  14324. "table": {
  14325. name: "table",
  14326. action: drawTable,
  14327. className: "fa fa-table",
  14328. title: "Insert Table"
  14329. },
  14330. "horizontal-rule": {
  14331. name: "horizontal-rule",
  14332. action: drawHorizontalRule,
  14333. className: "fa fa-minus",
  14334. title: "Insert Horizontal Line"
  14335. },
  14336. "separator-3": {
  14337. name: "separator-3"
  14338. },
  14339. "preview": {
  14340. name: "preview",
  14341. action: togglePreview,
  14342. className: "fa fa-eye no-disable",
  14343. title: "Toggle Preview",
  14344. default: true
  14345. },
  14346. "side-by-side": {
  14347. name: "side-by-side",
  14348. action: toggleSideBySide,
  14349. className: "fa fa-columns no-disable no-mobile",
  14350. title: "Toggle Side by Side",
  14351. default: true
  14352. },
  14353. "fullscreen": {
  14354. name: "fullscreen",
  14355. action: toggleFullScreen,
  14356. className: "fa fa-arrows-alt no-disable no-mobile",
  14357. title: "Toggle Fullscreen",
  14358. default: true
  14359. },
  14360. "separator-4": {
  14361. name: "separator-4"
  14362. },
  14363. "guide": {
  14364. name: "guide",
  14365. action: "https://simplemde.com/markdown-guide",
  14366. className: "fa fa-question-circle",
  14367. title: "Markdown Guide",
  14368. default: true
  14369. },
  14370. "separator-5": {
  14371. name: "separator-5"
  14372. },
  14373. "undo": {
  14374. name: "undo",
  14375. action: undo,
  14376. className: "fa fa-undo no-disable",
  14377. title: "Undo"
  14378. },
  14379. "redo": {
  14380. name: "redo",
  14381. action: redo,
  14382. className: "fa fa-repeat no-disable",
  14383. title: "Redo"
  14384. }
  14385. };
  14386. var insertTexts = {
  14387. link: ["[", "](#url#)"],
  14388. image: ["![](", "#url#)"],
  14389. table: ["", "\n\n| Column 1 | Column 2 | Column 3 |\n| -------- | -------- | -------- |\n| Text | Text | Text |\n\n"],
  14390. horizontalRule: ["", "\n\n-----\n\n"]
  14391. };
  14392. var promptTexts = {
  14393. link: "URL for the link:",
  14394. image: "URL of the image:"
  14395. };
  14396. var blockStyles = {
  14397. "bold": "**",
  14398. "code": "```",
  14399. "italic": "*"
  14400. };
  14401. /**
  14402. * Interface of SimpleMDE.
  14403. */
  14404. function SimpleMDE(options) {
  14405. // Handle options parameter
  14406. options = options || {};
  14407. // Used later to refer to it"s parent
  14408. options.parent = this;
  14409. // Check if Font Awesome needs to be auto downloaded
  14410. var autoDownloadFA = true;
  14411. if(options.autoDownloadFontAwesome === false) {
  14412. autoDownloadFA = false;
  14413. }
  14414. if(options.autoDownloadFontAwesome !== true) {
  14415. var styleSheets = document.styleSheets;
  14416. for(var i = 0; i < styleSheets.length; i++) {
  14417. if(!styleSheets[i].href)
  14418. continue;
  14419. if(styleSheets[i].href.indexOf("//maxcdn.bootstrapcdn.com/font-awesome/") > -1) {
  14420. autoDownloadFA = false;
  14421. }
  14422. }
  14423. }
  14424. if(autoDownloadFA) {
  14425. var link = document.createElement("link");
  14426. link.rel = "stylesheet";
  14427. link.href = "https://maxcdn.bootstrapcdn.com/font-awesome/latest/css/font-awesome.min.css";
  14428. document.getElementsByTagName("head")[0].appendChild(link);
  14429. }
  14430. // Find the textarea to use
  14431. if(options.element) {
  14432. this.element = options.element;
  14433. } else if(options.element === null) {
  14434. // This means that the element option was specified, but no element was found
  14435. console.log("SimpleMDE: Error. No element was found.");
  14436. return;
  14437. }
  14438. // Handle toolbar
  14439. if(options.toolbar === undefined) {
  14440. // Initialize
  14441. options.toolbar = [];
  14442. // Loop over the built in buttons, to get the preferred order
  14443. for(var key in toolbarBuiltInButtons) {
  14444. if(toolbarBuiltInButtons.hasOwnProperty(key)) {
  14445. if(key.indexOf("separator-") != -1) {
  14446. options.toolbar.push("|");
  14447. }
  14448. if(toolbarBuiltInButtons[key].default === true || (options.showIcons && options.showIcons.constructor === Array && options.showIcons.indexOf(key) != -1)) {
  14449. options.toolbar.push(key);
  14450. }
  14451. }
  14452. }
  14453. }
  14454. // Handle status bar
  14455. if(!options.hasOwnProperty("status")) {
  14456. options.status = ["autosave", "lines", "words", "cursor"];
  14457. }
  14458. // Add default preview rendering function
  14459. if(!options.previewRender) {
  14460. options.previewRender = function(plainText) {
  14461. // Note: "this" refers to the options object
  14462. return this.parent.markdown(plainText);
  14463. };
  14464. }
  14465. // Set default options for parsing config
  14466. options.parsingConfig = extend({
  14467. highlightFormatting: true // needed for toggleCodeBlock to detect types of code
  14468. }, options.parsingConfig || {});
  14469. // Merging the insertTexts, with the given options
  14470. options.insertTexts = extend({}, insertTexts, options.insertTexts || {});
  14471. // Merging the promptTexts, with the given options
  14472. options.promptTexts = promptTexts;
  14473. // Merging the blockStyles, with the given options
  14474. options.blockStyles = extend({}, blockStyles, options.blockStyles || {});
  14475. // Merging the shortcuts, with the given options
  14476. options.shortcuts = extend({}, shortcuts, options.shortcuts || {});
  14477. // Change unique_id to uniqueId for backwards compatibility
  14478. if(options.autosave != undefined && options.autosave.unique_id != undefined && options.autosave.unique_id != "")
  14479. options.autosave.uniqueId = options.autosave.unique_id;
  14480. // Update this options
  14481. this.options = options;
  14482. // Auto render
  14483. this.render();
  14484. // The codemirror component is only available after rendering
  14485. // so, the setter for the initialValue can only run after
  14486. // the element has been rendered
  14487. if(options.initialValue && (!this.options.autosave || this.options.autosave.foundSavedValue !== true)) {
  14488. this.value(options.initialValue);
  14489. }
  14490. }
  14491. /**
  14492. * Default markdown render.
  14493. */
  14494. SimpleMDE.prototype.markdown = function(text) {
  14495. if(marked) {
  14496. // Initialize
  14497. var markedOptions = {};
  14498. // Update options
  14499. if(this.options && this.options.renderingConfig && this.options.renderingConfig.singleLineBreaks === false) {
  14500. markedOptions.breaks = false;
  14501. } else {
  14502. markedOptions.breaks = true;
  14503. }
  14504. if(this.options && this.options.renderingConfig && this.options.renderingConfig.codeSyntaxHighlighting === true && window.hljs) {
  14505. markedOptions.highlight = function(code) {
  14506. return window.hljs.highlightAuto(code).value;
  14507. };
  14508. }
  14509. // Set options
  14510. marked.setOptions(markedOptions);
  14511. // Return
  14512. return marked(text);
  14513. }
  14514. };
  14515. /**
  14516. * Render editor to the given element.
  14517. */
  14518. SimpleMDE.prototype.render = function(el) {
  14519. if(!el) {
  14520. el = this.element || document.getElementsByTagName("textarea")[0];
  14521. }
  14522. if(this._rendered && this._rendered === el) {
  14523. // Already rendered.
  14524. return;
  14525. }
  14526. this.element = el;
  14527. var options = this.options;
  14528. var self = this;
  14529. var keyMaps = {};
  14530. for(var key in options.shortcuts) {
  14531. // null stands for "do not bind this command"
  14532. if(options.shortcuts[key] !== null && bindings[key] !== null) {
  14533. (function(key) {
  14534. keyMaps[fixShortcut(options.shortcuts[key])] = function() {
  14535. bindings[key](self);
  14536. };
  14537. })(key);
  14538. }
  14539. }
  14540. keyMaps["Enter"] = "newlineAndIndentContinueMarkdownList";
  14541. keyMaps["Tab"] = "tabAndIndentMarkdownList";
  14542. keyMaps["Shift-Tab"] = "shiftTabAndUnindentMarkdownList";
  14543. keyMaps["Esc"] = function(cm) {
  14544. if(cm.getOption("fullScreen")) toggleFullScreen(self);
  14545. };
  14546. document.addEventListener("keydown", function(e) {
  14547. e = e || window.event;
  14548. if(e.keyCode == 27) {
  14549. if(self.codemirror.getOption("fullScreen")) toggleFullScreen(self);
  14550. }
  14551. }, false);
  14552. var mode, backdrop;
  14553. if(options.spellChecker !== false) {
  14554. mode = "spell-checker";
  14555. backdrop = options.parsingConfig;
  14556. backdrop.name = "gfm";
  14557. backdrop.gitHubSpice = false;
  14558. CodeMirrorSpellChecker({
  14559. codeMirrorInstance: CodeMirror
  14560. });
  14561. } else {
  14562. mode = options.parsingConfig;
  14563. mode.name = "gfm";
  14564. mode.gitHubSpice = false;
  14565. }
  14566. this.codemirror = CodeMirror.fromTextArea(el, {
  14567. mode: mode,
  14568. backdrop: backdrop,
  14569. theme: "paper",
  14570. tabSize: (options.tabSize != undefined) ? options.tabSize : 2,
  14571. indentUnit: (options.tabSize != undefined) ? options.tabSize : 2,
  14572. indentWithTabs: (options.indentWithTabs === false) ? false : true,
  14573. lineNumbers: false,
  14574. autofocus: (options.autofocus === true) ? true : false,
  14575. extraKeys: keyMaps,
  14576. lineWrapping: (options.lineWrapping === false) ? false : true,
  14577. allowDropFileTypes: ["text/plain"],
  14578. placeholder: options.placeholder || el.getAttribute("placeholder") || "",
  14579. styleSelectedText: (options.styleSelectedText != undefined) ? options.styleSelectedText : true
  14580. });
  14581. if(options.forceSync === true) {
  14582. var cm = this.codemirror;
  14583. cm.on("change", function() {
  14584. cm.save();
  14585. });
  14586. }
  14587. this.gui = {};
  14588. if(options.toolbar !== false) {
  14589. this.gui.toolbar = this.createToolbar();
  14590. }
  14591. if(options.status !== false) {
  14592. this.gui.statusbar = this.createStatusbar();
  14593. }
  14594. if(options.autosave != undefined && options.autosave.enabled === true) {
  14595. this.autosave();
  14596. }
  14597. this.gui.sideBySide = this.createSideBySide();
  14598. this._rendered = this.element;
  14599. // Fixes CodeMirror bug (#344)
  14600. var temp_cm = this.codemirror;
  14601. setTimeout(function() {
  14602. temp_cm.refresh();
  14603. }.bind(temp_cm), 0);
  14604. };
  14605. // 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.
  14606. function isLocalStorageAvailable() {
  14607. if(typeof localStorage === "object") {
  14608. try {
  14609. localStorage.setItem("smde_localStorage", 1);
  14610. localStorage.removeItem("smde_localStorage");
  14611. } catch(e) {
  14612. return false;
  14613. }
  14614. } else {
  14615. return false;
  14616. }
  14617. return true;
  14618. }
  14619. SimpleMDE.prototype.autosave = function() {
  14620. if(isLocalStorageAvailable()) {
  14621. var simplemde = this;
  14622. if(this.options.autosave.uniqueId == undefined || this.options.autosave.uniqueId == "") {
  14623. console.log("SimpleMDE: You must set a uniqueId to use the autosave feature");
  14624. return;
  14625. }
  14626. if(simplemde.element.form != null && simplemde.element.form != undefined) {
  14627. simplemde.element.form.addEventListener("submit", function() {
  14628. localStorage.removeItem("smde_" + simplemde.options.autosave.uniqueId);
  14629. });
  14630. }
  14631. if(this.options.autosave.loaded !== true) {
  14632. if(typeof localStorage.getItem("smde_" + this.options.autosave.uniqueId) == "string" && localStorage.getItem("smde_" + this.options.autosave.uniqueId) != "") {
  14633. this.codemirror.setValue(localStorage.getItem("smde_" + this.options.autosave.uniqueId));
  14634. this.options.autosave.foundSavedValue = true;
  14635. }
  14636. this.options.autosave.loaded = true;
  14637. }
  14638. localStorage.setItem("smde_" + this.options.autosave.uniqueId, simplemde.value());
  14639. var el = document.getElementById("autosaved");
  14640. if(el != null && el != undefined && el != "") {
  14641. var d = new Date();
  14642. var hh = d.getHours();
  14643. var m = d.getMinutes();
  14644. var dd = "am";
  14645. var h = hh;
  14646. if(h >= 12) {
  14647. h = hh - 12;
  14648. dd = "pm";
  14649. }
  14650. if(h == 0) {
  14651. h = 12;
  14652. }
  14653. m = m < 10 ? "0" + m : m;
  14654. el.innerHTML = "Autosaved: " + h + ":" + m + " " + dd;
  14655. }
  14656. this.autosaveTimeoutId = setTimeout(function() {
  14657. simplemde.autosave();
  14658. }, this.options.autosave.delay || 10000);
  14659. } else {
  14660. console.log("SimpleMDE: localStorage not available, cannot autosave");
  14661. }
  14662. };
  14663. SimpleMDE.prototype.clearAutosavedValue = function() {
  14664. if(isLocalStorageAvailable()) {
  14665. if(this.options.autosave == undefined || this.options.autosave.uniqueId == undefined || this.options.autosave.uniqueId == "") {
  14666. console.log("SimpleMDE: You must set a uniqueId to clear the autosave value");
  14667. return;
  14668. }
  14669. localStorage.removeItem("smde_" + this.options.autosave.uniqueId);
  14670. } else {
  14671. console.log("SimpleMDE: localStorage not available, cannot autosave");
  14672. }
  14673. };
  14674. SimpleMDE.prototype.createSideBySide = function() {
  14675. var cm = this.codemirror;
  14676. var wrapper = cm.getWrapperElement();
  14677. var preview = wrapper.nextSibling;
  14678. if(!preview || !/editor-preview-side/.test(preview.className)) {
  14679. preview = document.createElement("div");
  14680. preview.className = "editor-preview-side";
  14681. wrapper.parentNode.insertBefore(preview, wrapper.nextSibling);
  14682. }
  14683. // Syncs scroll editor -> preview
  14684. var cScroll = false;
  14685. var pScroll = false;
  14686. cm.on("scroll", function(v) {
  14687. if(cScroll) {
  14688. cScroll = false;
  14689. return;
  14690. }
  14691. pScroll = true;
  14692. var height = v.getScrollInfo().height - v.getScrollInfo().clientHeight;
  14693. var ratio = parseFloat(v.getScrollInfo().top) / height;
  14694. var move = (preview.scrollHeight - preview.clientHeight) * ratio;
  14695. preview.scrollTop = move;
  14696. });
  14697. // Syncs scroll preview -> editor
  14698. preview.onscroll = function() {
  14699. if(pScroll) {
  14700. pScroll = false;
  14701. return;
  14702. }
  14703. cScroll = true;
  14704. var height = preview.scrollHeight - preview.clientHeight;
  14705. var ratio = parseFloat(preview.scrollTop) / height;
  14706. var move = (cm.getScrollInfo().height - cm.getScrollInfo().clientHeight) * ratio;
  14707. cm.scrollTo(0, move);
  14708. };
  14709. return preview;
  14710. };
  14711. SimpleMDE.prototype.createToolbar = function(items) {
  14712. items = items || this.options.toolbar;
  14713. if(!items || items.length === 0) {
  14714. return;
  14715. }
  14716. var i;
  14717. for(i = 0; i < items.length; i++) {
  14718. if(toolbarBuiltInButtons[items[i]] != undefined) {
  14719. items[i] = toolbarBuiltInButtons[items[i]];
  14720. }
  14721. }
  14722. var bar = document.createElement("div");
  14723. bar.className = "editor-toolbar";
  14724. var self = this;
  14725. var toolbarData = {};
  14726. self.toolbar = items;
  14727. for(i = 0; i < items.length; i++) {
  14728. if(items[i].name == "guide" && self.options.toolbarGuideIcon === false)
  14729. continue;
  14730. if(self.options.hideIcons && self.options.hideIcons.indexOf(items[i].name) != -1)
  14731. continue;
  14732. // Fullscreen does not work well on mobile devices (even tablets)
  14733. // In the future, hopefully this can be resolved
  14734. if((items[i].name == "fullscreen" || items[i].name == "side-by-side") && isMobile())
  14735. continue;
  14736. // Don't include trailing separators
  14737. if(items[i] === "|") {
  14738. var nonSeparatorIconsFollow = false;
  14739. for(var x = (i + 1); x < items.length; x++) {
  14740. if(items[x] !== "|" && (!self.options.hideIcons || self.options.hideIcons.indexOf(items[x].name) == -1)) {
  14741. nonSeparatorIconsFollow = true;
  14742. }
  14743. }
  14744. if(!nonSeparatorIconsFollow)
  14745. continue;
  14746. }
  14747. // Create the icon and append to the toolbar
  14748. (function(item) {
  14749. var el;
  14750. if(item === "|") {
  14751. el = createSep();
  14752. } else {
  14753. el = createIcon(item, self.options.toolbarTips, self.options.shortcuts);
  14754. }
  14755. // bind events, special for info
  14756. if(item.action) {
  14757. if(typeof item.action === "function") {
  14758. el.onclick = function(e) {
  14759. e.preventDefault();
  14760. item.action(self);
  14761. };
  14762. } else if(typeof item.action === "string") {
  14763. el.href = item.action;
  14764. el.target = "_blank";
  14765. }
  14766. }
  14767. toolbarData[item.name || item] = el;
  14768. bar.appendChild(el);
  14769. })(items[i]);
  14770. }
  14771. self.toolbarElements = toolbarData;
  14772. var cm = this.codemirror;
  14773. cm.on("cursorActivity", function() {
  14774. var stat = getState(cm);
  14775. for(var key in toolbarData) {
  14776. (function(key) {
  14777. var el = toolbarData[key];
  14778. if(stat[key]) {
  14779. el.className += " active";
  14780. } else if(key != "fullscreen" && key != "side-by-side") {
  14781. el.className = el.className.replace(/\s*active\s*/g, "");
  14782. }
  14783. })(key);
  14784. }
  14785. });
  14786. var cmWrapper = cm.getWrapperElement();
  14787. cmWrapper.parentNode.insertBefore(bar, cmWrapper);
  14788. return bar;
  14789. };
  14790. SimpleMDE.prototype.createStatusbar = function(status) {
  14791. // Initialize
  14792. status = status || this.options.status;
  14793. var options = this.options;
  14794. var cm = this.codemirror;
  14795. // Make sure the status variable is valid
  14796. if(!status || status.length === 0)
  14797. return;
  14798. // Set up the built-in items
  14799. var items = [];
  14800. var i, onUpdate, defaultValue;
  14801. for(i = 0; i < status.length; i++) {
  14802. // Reset some values
  14803. onUpdate = undefined;
  14804. defaultValue = undefined;
  14805. // Handle if custom or not
  14806. if(typeof status[i] === "object") {
  14807. items.push({
  14808. className: status[i].className,
  14809. defaultValue: status[i].defaultValue,
  14810. onUpdate: status[i].onUpdate
  14811. });
  14812. } else {
  14813. var name = status[i];
  14814. if(name === "words") {
  14815. defaultValue = function(el) {
  14816. el.innerHTML = wordCount(cm.getValue());
  14817. };
  14818. onUpdate = function(el) {
  14819. el.innerHTML = wordCount(cm.getValue());
  14820. };
  14821. } else if(name === "lines") {
  14822. defaultValue = function(el) {
  14823. el.innerHTML = cm.lineCount();
  14824. };
  14825. onUpdate = function(el) {
  14826. el.innerHTML = cm.lineCount();
  14827. };
  14828. } else if(name === "cursor") {
  14829. defaultValue = function(el) {
  14830. el.innerHTML = "0:0";
  14831. };
  14832. onUpdate = function(el) {
  14833. var pos = cm.getCursor();
  14834. el.innerHTML = pos.line + ":" + pos.ch;
  14835. };
  14836. } else if(name === "autosave") {
  14837. defaultValue = function(el) {
  14838. if(options.autosave != undefined && options.autosave.enabled === true) {
  14839. el.setAttribute("id", "autosaved");
  14840. }
  14841. };
  14842. }
  14843. items.push({
  14844. className: name,
  14845. defaultValue: defaultValue,
  14846. onUpdate: onUpdate
  14847. });
  14848. }
  14849. }
  14850. // Create element for the status bar
  14851. var bar = document.createElement("div");
  14852. bar.className = "editor-statusbar";
  14853. // Create a new span for each item
  14854. for(i = 0; i < items.length; i++) {
  14855. // Store in temporary variable
  14856. var item = items[i];
  14857. // Create span element
  14858. var el = document.createElement("span");
  14859. el.className = item.className;
  14860. // Ensure the defaultValue is a function
  14861. if(typeof item.defaultValue === "function") {
  14862. item.defaultValue(el);
  14863. }
  14864. // Ensure the onUpdate is a function
  14865. if(typeof item.onUpdate === "function") {
  14866. // Create a closure around the span of the current action, then execute the onUpdate handler
  14867. this.codemirror.on("update", (function(el, item) {
  14868. return function() {
  14869. item.onUpdate(el);
  14870. };
  14871. }(el, item)));
  14872. }
  14873. // Append the item to the status bar
  14874. bar.appendChild(el);
  14875. }
  14876. // Insert the status bar into the DOM
  14877. var cmWrapper = this.codemirror.getWrapperElement();
  14878. cmWrapper.parentNode.insertBefore(bar, cmWrapper.nextSibling);
  14879. return bar;
  14880. };
  14881. /**
  14882. * Get or set the text content.
  14883. */
  14884. SimpleMDE.prototype.value = function(val) {
  14885. if(val === undefined) {
  14886. return this.codemirror.getValue();
  14887. } else {
  14888. this.codemirror.getDoc().setValue(val);
  14889. return this;
  14890. }
  14891. };
  14892. /**
  14893. * Bind static methods for exports.
  14894. */
  14895. SimpleMDE.toggleBold = toggleBold;
  14896. SimpleMDE.toggleItalic = toggleItalic;
  14897. SimpleMDE.toggleStrikethrough = toggleStrikethrough;
  14898. SimpleMDE.toggleBlockquote = toggleBlockquote;
  14899. SimpleMDE.toggleHeadingSmaller = toggleHeadingSmaller;
  14900. SimpleMDE.toggleHeadingBigger = toggleHeadingBigger;
  14901. SimpleMDE.toggleHeading1 = toggleHeading1;
  14902. SimpleMDE.toggleHeading2 = toggleHeading2;
  14903. SimpleMDE.toggleHeading3 = toggleHeading3;
  14904. SimpleMDE.toggleCodeBlock = toggleCodeBlock;
  14905. SimpleMDE.toggleUnorderedList = toggleUnorderedList;
  14906. SimpleMDE.toggleOrderedList = toggleOrderedList;
  14907. SimpleMDE.cleanBlock = cleanBlock;
  14908. SimpleMDE.drawLink = drawLink;
  14909. SimpleMDE.drawImage = drawImage;
  14910. SimpleMDE.drawTable = drawTable;
  14911. SimpleMDE.drawHorizontalRule = drawHorizontalRule;
  14912. SimpleMDE.undo = undo;
  14913. SimpleMDE.redo = redo;
  14914. SimpleMDE.togglePreview = togglePreview;
  14915. SimpleMDE.toggleSideBySide = toggleSideBySide;
  14916. SimpleMDE.toggleFullScreen = toggleFullScreen;
  14917. /**
  14918. * Bind instance methods for exports.
  14919. */
  14920. SimpleMDE.prototype.toggleBold = function() {
  14921. toggleBold(this);
  14922. };
  14923. SimpleMDE.prototype.toggleItalic = function() {
  14924. toggleItalic(this);
  14925. };
  14926. SimpleMDE.prototype.toggleStrikethrough = function() {
  14927. toggleStrikethrough(this);
  14928. };
  14929. SimpleMDE.prototype.toggleBlockquote = function() {
  14930. toggleBlockquote(this);
  14931. };
  14932. SimpleMDE.prototype.toggleHeadingSmaller = function() {
  14933. toggleHeadingSmaller(this);
  14934. };
  14935. SimpleMDE.prototype.toggleHeadingBigger = function() {
  14936. toggleHeadingBigger(this);
  14937. };
  14938. SimpleMDE.prototype.toggleHeading1 = function() {
  14939. toggleHeading1(this);
  14940. };
  14941. SimpleMDE.prototype.toggleHeading2 = function() {
  14942. toggleHeading2(this);
  14943. };
  14944. SimpleMDE.prototype.toggleHeading3 = function() {
  14945. toggleHeading3(this);
  14946. };
  14947. SimpleMDE.prototype.toggleCodeBlock = function() {
  14948. toggleCodeBlock(this);
  14949. };
  14950. SimpleMDE.prototype.toggleUnorderedList = function() {
  14951. toggleUnorderedList(this);
  14952. };
  14953. SimpleMDE.prototype.toggleOrderedList = function() {
  14954. toggleOrderedList(this);
  14955. };
  14956. SimpleMDE.prototype.cleanBlock = function() {
  14957. cleanBlock(this);
  14958. };
  14959. SimpleMDE.prototype.drawLink = function() {
  14960. drawLink(this);
  14961. };
  14962. SimpleMDE.prototype.drawImage = function() {
  14963. drawImage(this);
  14964. };
  14965. SimpleMDE.prototype.drawTable = function() {
  14966. drawTable(this);
  14967. };
  14968. SimpleMDE.prototype.drawHorizontalRule = function() {
  14969. drawHorizontalRule(this);
  14970. };
  14971. SimpleMDE.prototype.undo = function() {
  14972. undo(this);
  14973. };
  14974. SimpleMDE.prototype.redo = function() {
  14975. redo(this);
  14976. };
  14977. SimpleMDE.prototype.togglePreview = function() {
  14978. togglePreview(this);
  14979. };
  14980. SimpleMDE.prototype.toggleSideBySide = function() {
  14981. toggleSideBySide(this);
  14982. };
  14983. SimpleMDE.prototype.toggleFullScreen = function() {
  14984. toggleFullScreen(this);
  14985. };
  14986. SimpleMDE.prototype.isPreviewActive = function() {
  14987. var cm = this.codemirror;
  14988. var wrapper = cm.getWrapperElement();
  14989. var preview = wrapper.lastChild;
  14990. return /editor-preview-active/.test(preview.className);
  14991. };
  14992. SimpleMDE.prototype.isSideBySideActive = function() {
  14993. var cm = this.codemirror;
  14994. var wrapper = cm.getWrapperElement();
  14995. var preview = wrapper.nextSibling;
  14996. return /editor-preview-active-side/.test(preview.className);
  14997. };
  14998. SimpleMDE.prototype.isFullscreenActive = function() {
  14999. var cm = this.codemirror;
  15000. return cm.getOption("fullScreen");
  15001. };
  15002. SimpleMDE.prototype.getState = function() {
  15003. var cm = this.codemirror;
  15004. return getState(cm);
  15005. };
  15006. SimpleMDE.prototype.toTextArea = function() {
  15007. var cm = this.codemirror;
  15008. var wrapper = cm.getWrapperElement();
  15009. if(wrapper.parentNode) {
  15010. if(this.gui.toolbar) {
  15011. wrapper.parentNode.removeChild(this.gui.toolbar);
  15012. }
  15013. if(this.gui.statusbar) {
  15014. wrapper.parentNode.removeChild(this.gui.statusbar);
  15015. }
  15016. if(this.gui.sideBySide) {
  15017. wrapper.parentNode.removeChild(this.gui.sideBySide);
  15018. }
  15019. }
  15020. cm.toTextArea();
  15021. if(this.autosaveTimeoutId) {
  15022. clearTimeout(this.autosaveTimeoutId);
  15023. this.autosaveTimeoutId = undefined;
  15024. this.clearAutosavedValue();
  15025. }
  15026. };
  15027. module.exports = SimpleMDE;
  15028. },{"./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)
  15029. });